LLVM  mainline
BasicAliasAnalysis.cpp
Go to the documentation of this file.
00001 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the primary stateless implementation of the
00011 // Alias Analysis interface that implements identities (two different
00012 // globals cannot alias, etc), but does no stateful analysis.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Analysis/Passes.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/Analysis/AliasAnalysis.h"
00020 #include "llvm/Analysis/AssumptionCache.h"
00021 #include "llvm/Analysis/CFG.h"
00022 #include "llvm/Analysis/CaptureTracking.h"
00023 #include "llvm/Analysis/InstructionSimplify.h"
00024 #include "llvm/Analysis/LoopInfo.h"
00025 #include "llvm/Analysis/MemoryBuiltins.h"
00026 #include "llvm/Analysis/TargetLibraryInfo.h"
00027 #include "llvm/Analysis/ValueTracking.h"
00028 #include "llvm/IR/Constants.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/DerivedTypes.h"
00031 #include "llvm/IR/Dominators.h"
00032 #include "llvm/IR/Function.h"
00033 #include "llvm/IR/GetElementPtrTypeIterator.h"
00034 #include "llvm/IR/GlobalAlias.h"
00035 #include "llvm/IR/GlobalVariable.h"
00036 #include "llvm/IR/Instructions.h"
00037 #include "llvm/IR/IntrinsicInst.h"
00038 #include "llvm/IR/LLVMContext.h"
00039 #include "llvm/IR/Operator.h"
00040 #include "llvm/Pass.h"
00041 #include "llvm/Support/ErrorHandling.h"
00042 #include <algorithm>
00043 using namespace llvm;
00044 
00045 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
00046 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
00047 /// careful with value equivalence. We use reachability to make sure a value
00048 /// cannot be involved in a cycle.
00049 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
00050 
00051 // The max limit of the search depth in DecomposeGEPExpression() and
00052 // GetUnderlyingObject(), both functions need to use the same search
00053 // depth otherwise the algorithm in aliasGEP will assert.
00054 static const unsigned MaxLookupSearchDepth = 6;
00055 
00056 //===----------------------------------------------------------------------===//
00057 // Useful predicates
00058 //===----------------------------------------------------------------------===//
00059 
00060 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
00061 /// object that never escapes from the function.
00062 static bool isNonEscapingLocalObject(const Value *V) {
00063   // If this is a local allocation, check to see if it escapes.
00064   if (isa<AllocaInst>(V) || isNoAliasCall(V))
00065     // Set StoreCaptures to True so that we can assume in our callers that the
00066     // pointer is not the result of a load instruction. Currently
00067     // PointerMayBeCaptured doesn't have any special analysis for the
00068     // StoreCaptures=false case; if it did, our callers could be refined to be
00069     // more precise.
00070     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
00071 
00072   // If this is an argument that corresponds to a byval or noalias argument,
00073   // then it has not escaped before entering the function.  Check if it escapes
00074   // inside the function.
00075   if (const Argument *A = dyn_cast<Argument>(V))
00076     if (A->hasByValAttr() || A->hasNoAliasAttr())
00077       // Note even if the argument is marked nocapture we still need to check
00078       // for copies made inside the function. The nocapture attribute only
00079       // specifies that there are no copies made that outlive the function.
00080       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
00081 
00082   return false;
00083 }
00084 
00085 /// isEscapeSource - Return true if the pointer is one which would have
00086 /// been considered an escape by isNonEscapingLocalObject.
00087 static bool isEscapeSource(const Value *V) {
00088   if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
00089     return true;
00090 
00091   // The load case works because isNonEscapingLocalObject considers all
00092   // stores to be escapes (it passes true for the StoreCaptures argument
00093   // to PointerMayBeCaptured).
00094   if (isa<LoadInst>(V))
00095     return true;
00096 
00097   return false;
00098 }
00099 
00100 /// getObjectSize - Return the size of the object specified by V, or
00101 /// UnknownSize if unknown.
00102 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
00103                               const TargetLibraryInfo &TLI,
00104                               bool RoundToAlign = false) {
00105   uint64_t Size;
00106   if (getObjectSize(V, Size, DL, &TLI, RoundToAlign))
00107     return Size;
00108   return AliasAnalysis::UnknownSize;
00109 }
00110 
00111 /// isObjectSmallerThan - Return true if we can prove that the object specified
00112 /// by V is smaller than Size.
00113 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
00114                                 const DataLayout &DL,
00115                                 const TargetLibraryInfo &TLI) {
00116   // Note that the meanings of the "object" are slightly different in the
00117   // following contexts:
00118   //    c1: llvm::getObjectSize()
00119   //    c2: llvm.objectsize() intrinsic
00120   //    c3: isObjectSmallerThan()
00121   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
00122   // refers to the "entire object".
00123   //
00124   //  Consider this example:
00125   //     char *p = (char*)malloc(100)
00126   //     char *q = p+80;
00127   //
00128   //  In the context of c1 and c2, the "object" pointed by q refers to the
00129   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
00130   //
00131   //  However, in the context of c3, the "object" refers to the chunk of memory
00132   // being allocated. So, the "object" has 100 bytes, and q points to the middle
00133   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
00134   // parameter, before the llvm::getObjectSize() is called to get the size of
00135   // entire object, we should:
00136   //    - either rewind the pointer q to the base-address of the object in
00137   //      question (in this case rewind to p), or
00138   //    - just give up. It is up to caller to make sure the pointer is pointing
00139   //      to the base address the object.
00140   //
00141   // We go for 2nd option for simplicity.
00142   if (!isIdentifiedObject(V))
00143     return false;
00144 
00145   // This function needs to use the aligned object size because we allow
00146   // reads a bit past the end given sufficient alignment.
00147   uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
00148 
00149   return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
00150 }
00151 
00152 /// isObjectSize - Return true if we can prove that the object specified
00153 /// by V has size Size.
00154 static bool isObjectSize(const Value *V, uint64_t Size,
00155                          const DataLayout &DL, const TargetLibraryInfo &TLI) {
00156   uint64_t ObjectSize = getObjectSize(V, DL, TLI);
00157   return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
00158 }
00159 
00160 //===----------------------------------------------------------------------===//
00161 // GetElementPtr Instruction Decomposition and Analysis
00162 //===----------------------------------------------------------------------===//
00163 
00164 namespace {
00165   enum ExtensionKind {
00166     EK_NotExtended,
00167     EK_SignExt,
00168     EK_ZeroExt
00169   };
00170 
00171   struct VariableGEPIndex {
00172     const Value *V;
00173     ExtensionKind Extension;
00174     int64_t Scale;
00175 
00176     bool operator==(const VariableGEPIndex &Other) const {
00177       return V == Other.V && Extension == Other.Extension &&
00178         Scale == Other.Scale;
00179     }
00180 
00181     bool operator!=(const VariableGEPIndex &Other) const {
00182       return !operator==(Other);
00183     }
00184   };
00185 }
00186 
00187 
00188 /// GetLinearExpression - Analyze the specified value as a linear expression:
00189 /// "A*V + B", where A and B are constant integers.  Return the scale and offset
00190 /// values as APInts and return V as a Value*, and return whether we looked
00191 /// through any sign or zero extends.  The incoming Value is known to have
00192 /// IntegerType and it may already be sign or zero extended.
00193 ///
00194 /// Note that this looks through extends, so the high bits may not be
00195 /// represented in the result.
00196 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
00197                                   ExtensionKind &Extension,
00198                                   const DataLayout &DL, unsigned Depth,
00199                                   AssumptionCache *AC, DominatorTree *DT) {
00200   assert(V->getType()->isIntegerTy() && "Not an integer value");
00201 
00202   // Limit our recursion depth.
00203   if (Depth == 6) {
00204     Scale = 1;
00205     Offset = 0;
00206     return V;
00207   }
00208 
00209   if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
00210     // if it's a constant, just convert it to an offset
00211     // and remove the variable.
00212     Offset += Const->getValue();
00213     assert(Scale == 0 && "Constant values don't have a scale");
00214     return V;
00215   }
00216 
00217   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
00218     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
00219       switch (BOp->getOpcode()) {
00220       default: break;
00221       case Instruction::Or:
00222         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
00223         // analyze it.
00224         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
00225                                BOp, DT))
00226           break;
00227         // FALL THROUGH.
00228       case Instruction::Add:
00229         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
00230                                 DL, Depth + 1, AC, DT);
00231         Offset += RHSC->getValue();
00232         return V;
00233       case Instruction::Mul:
00234         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
00235                                 DL, Depth + 1, AC, DT);
00236         Offset *= RHSC->getValue();
00237         Scale *= RHSC->getValue();
00238         return V;
00239       case Instruction::Shl:
00240         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
00241                                 DL, Depth + 1, AC, DT);
00242         Offset <<= RHSC->getValue().getLimitedValue();
00243         Scale <<= RHSC->getValue().getLimitedValue();
00244         return V;
00245       }
00246     }
00247   }
00248 
00249   // Since GEP indices are sign extended anyway, we don't care about the high
00250   // bits of a sign or zero extended value - just scales and offsets.  The
00251   // extensions have to be consistent though.
00252   if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
00253       (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
00254     Value *CastOp = cast<CastInst>(V)->getOperand(0);
00255     unsigned OldWidth = Scale.getBitWidth();
00256     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
00257     Scale = Scale.trunc(SmallWidth);
00258     Offset = Offset.trunc(SmallWidth);
00259     Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
00260 
00261     Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
00262                                         Depth + 1, AC, DT);
00263     Scale = Scale.zext(OldWidth);
00264 
00265     // We have to sign-extend even if Extension == EK_ZeroExt as we can't
00266     // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
00267     Offset = Offset.sext(OldWidth);
00268 
00269     return Result;
00270   }
00271 
00272   Scale = 1;
00273   Offset = 0;
00274   return V;
00275 }
00276 
00277 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
00278 /// into a base pointer with a constant offset and a number of scaled symbolic
00279 /// offsets.
00280 ///
00281 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
00282 /// the VarIndices vector) are Value*'s that are known to be scaled by the
00283 /// specified amount, but which may have other unrepresented high bits. As such,
00284 /// the gep cannot necessarily be reconstructed from its decomposed form.
00285 ///
00286 /// When DataLayout is around, this function is capable of analyzing everything
00287 /// that GetUnderlyingObject can look through. To be able to do that
00288 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
00289 /// depth (MaxLookupSearchDepth).
00290 /// When DataLayout not is around, it just looks through pointer casts.
00291 ///
00292 static const Value *
00293 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
00294                        SmallVectorImpl<VariableGEPIndex> &VarIndices,
00295                        bool &MaxLookupReached, const DataLayout &DL,
00296                        AssumptionCache *AC, DominatorTree *DT) {
00297   // Limit recursion depth to limit compile time in crazy cases.
00298   unsigned MaxLookup = MaxLookupSearchDepth;
00299   MaxLookupReached = false;
00300 
00301   BaseOffs = 0;
00302   do {
00303     // See if this is a bitcast or GEP.
00304     const Operator *Op = dyn_cast<Operator>(V);
00305     if (!Op) {
00306       // The only non-operator case we can handle are GlobalAliases.
00307       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00308         if (!GA->mayBeOverridden()) {
00309           V = GA->getAliasee();
00310           continue;
00311         }
00312       }
00313       return V;
00314     }
00315 
00316     if (Op->getOpcode() == Instruction::BitCast ||
00317         Op->getOpcode() == Instruction::AddrSpaceCast) {
00318       V = Op->getOperand(0);
00319       continue;
00320     }
00321 
00322     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
00323     if (!GEPOp) {
00324       // If it's not a GEP, hand it off to SimplifyInstruction to see if it
00325       // can come up with something. This matches what GetUnderlyingObject does.
00326       if (const Instruction *I = dyn_cast<Instruction>(V))
00327         // TODO: Get a DominatorTree and AssumptionCache and use them here
00328         // (these are both now available in this function, but this should be
00329         // updated when GetUnderlyingObject is updated). TLI should be
00330         // provided also.
00331         if (const Value *Simplified =
00332               SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
00333           V = Simplified;
00334           continue;
00335         }
00336 
00337       return V;
00338     }
00339 
00340     // Don't attempt to analyze GEPs over unsized objects.
00341     if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
00342       return V;
00343 
00344     unsigned AS = GEPOp->getPointerAddressSpace();
00345     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
00346     gep_type_iterator GTI = gep_type_begin(GEPOp);
00347     for (User::const_op_iterator I = GEPOp->op_begin()+1,
00348          E = GEPOp->op_end(); I != E; ++I) {
00349       Value *Index = *I;
00350       // Compute the (potentially symbolic) offset in bytes for this index.
00351       if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
00352         // For a struct, add the member offset.
00353         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
00354         if (FieldNo == 0) continue;
00355 
00356         BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
00357         continue;
00358       }
00359 
00360       // For an array/pointer, add the element offset, explicitly scaled.
00361       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
00362         if (CIdx->isZero()) continue;
00363         BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
00364         continue;
00365       }
00366 
00367       uint64_t Scale = DL.getTypeAllocSize(*GTI);
00368       ExtensionKind Extension = EK_NotExtended;
00369 
00370       // If the integer type is smaller than the pointer size, it is implicitly
00371       // sign extended to pointer size.
00372       unsigned Width = Index->getType()->getIntegerBitWidth();
00373       if (DL.getPointerSizeInBits(AS) > Width)
00374         Extension = EK_SignExt;
00375 
00376       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
00377       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
00378       Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, DL,
00379                                   0, AC, DT);
00380 
00381       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
00382       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
00383       BaseOffs += IndexOffset.getSExtValue()*Scale;
00384       Scale *= IndexScale.getSExtValue();
00385 
00386       // If we already had an occurrence of this index variable, merge this
00387       // scale into it.  For example, we want to handle:
00388       //   A[x][x] -> x*16 + x*4 -> x*20
00389       // This also ensures that 'x' only appears in the index list once.
00390       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
00391         if (VarIndices[i].V == Index &&
00392             VarIndices[i].Extension == Extension) {
00393           Scale += VarIndices[i].Scale;
00394           VarIndices.erase(VarIndices.begin()+i);
00395           break;
00396         }
00397       }
00398 
00399       // Make sure that we have a scale that makes sense for this target's
00400       // pointer size.
00401       if (unsigned ShiftBits = 64 - DL.getPointerSizeInBits(AS)) {
00402         Scale <<= ShiftBits;
00403         Scale = (int64_t)Scale >> ShiftBits;
00404       }
00405 
00406       if (Scale) {
00407         VariableGEPIndex Entry = {Index, Extension,
00408                                   static_cast<int64_t>(Scale)};
00409         VarIndices.push_back(Entry);
00410       }
00411     }
00412 
00413     // Analyze the base pointer next.
00414     V = GEPOp->getOperand(0);
00415   } while (--MaxLookup);
00416 
00417   // If the chain of expressions is too deep, just return early.
00418   MaxLookupReached = true;
00419   return V;
00420 }
00421 
00422 //===----------------------------------------------------------------------===//
00423 // BasicAliasAnalysis Pass
00424 //===----------------------------------------------------------------------===//
00425 
00426 #ifndef NDEBUG
00427 static const Function *getParent(const Value *V) {
00428   if (const Instruction *inst = dyn_cast<Instruction>(V))
00429     return inst->getParent()->getParent();
00430 
00431   if (const Argument *arg = dyn_cast<Argument>(V))
00432     return arg->getParent();
00433 
00434   return nullptr;
00435 }
00436 
00437 static bool notDifferentParent(const Value *O1, const Value *O2) {
00438 
00439   const Function *F1 = getParent(O1);
00440   const Function *F2 = getParent(O2);
00441 
00442   return !F1 || !F2 || F1 == F2;
00443 }
00444 #endif
00445 
00446 namespace {
00447   /// BasicAliasAnalysis - This is the primary alias analysis implementation.
00448   struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
00449     static char ID; // Class identification, replacement for typeinfo
00450     BasicAliasAnalysis() : ImmutablePass(ID) {
00451       initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
00452     }
00453 
00454     bool doInitialization(Module &M) override;
00455 
00456     void getAnalysisUsage(AnalysisUsage &AU) const override {
00457       AU.addRequired<AliasAnalysis>();
00458       AU.addRequired<AssumptionCacheTracker>();
00459       AU.addRequired<TargetLibraryInfoWrapperPass>();
00460     }
00461 
00462     AliasResult alias(const Location &LocA, const Location &LocB) override {
00463       assert(AliasCache.empty() && "AliasCache must be cleared after use!");
00464       assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
00465              "BasicAliasAnalysis doesn't support interprocedural queries.");
00466       AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
00467                                      LocB.Ptr, LocB.Size, LocB.AATags);
00468       // AliasCache rarely has more than 1 or 2 elements, always use
00469       // shrink_and_clear so it quickly returns to the inline capacity of the
00470       // SmallDenseMap if it ever grows larger.
00471       // FIXME: This should really be shrink_to_inline_capacity_and_clear().
00472       AliasCache.shrink_and_clear();
00473       VisitedPhiBBs.clear();
00474       return Alias;
00475     }
00476 
00477     ModRefResult getModRefInfo(ImmutableCallSite CS,
00478                                const Location &Loc) override;
00479 
00480     ModRefResult getModRefInfo(ImmutableCallSite CS1,
00481                                ImmutableCallSite CS2) override;
00482 
00483     /// pointsToConstantMemory - Chase pointers until we find a (constant
00484     /// global) or not.
00485     bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
00486 
00487     /// Get the location associated with a pointer argument of a callsite.
00488     Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
00489                             ModRefResult &Mask) override;
00490 
00491     /// getModRefBehavior - Return the behavior when calling the given
00492     /// call site.
00493     ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
00494 
00495     /// getModRefBehavior - Return the behavior when calling the given function.
00496     /// For use when the call site is not known.
00497     ModRefBehavior getModRefBehavior(const Function *F) override;
00498 
00499     /// getAdjustedAnalysisPointer - This method is used when a pass implements
00500     /// an analysis interface through multiple inheritance.  If needed, it
00501     /// should override this to adjust the this pointer as needed for the
00502     /// specified pass info.
00503     void *getAdjustedAnalysisPointer(const void *ID) override {
00504       if (ID == &AliasAnalysis::ID)
00505         return (AliasAnalysis*)this;
00506       return this;
00507     }
00508 
00509   private:
00510     // AliasCache - Track alias queries to guard against recursion.
00511     typedef std::pair<Location, Location> LocPair;
00512     typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
00513     AliasCacheTy AliasCache;
00514 
00515     /// \brief Track phi nodes we have visited. When interpret "Value" pointer
00516     /// equality as value equality we need to make sure that the "Value" is not
00517     /// part of a cycle. Otherwise, two uses could come from different
00518     /// "iterations" of a cycle and see different values for the same "Value"
00519     /// pointer.
00520     /// The following example shows the problem:
00521     ///   %p = phi(%alloca1, %addr2)
00522     ///   %l = load %ptr
00523     ///   %addr1 = gep, %alloca2, 0, %l
00524     ///   %addr2 = gep  %alloca2, 0, (%l + 1)
00525     ///      alias(%p, %addr1) -> MayAlias !
00526     ///   store %l, ...
00527     SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
00528 
00529     // Visited - Track instructions visited by pointsToConstantMemory.
00530     SmallPtrSet<const Value*, 16> Visited;
00531 
00532     /// \brief Check whether two Values can be considered equivalent.
00533     ///
00534     /// In addition to pointer equivalence of \p V1 and \p V2 this checks
00535     /// whether they can not be part of a cycle in the value graph by looking at
00536     /// all visited phi nodes an making sure that the phis cannot reach the
00537     /// value. We have to do this because we are looking through phi nodes (That
00538     /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
00539     bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
00540 
00541     /// \brief Dest and Src are the variable indices from two decomposed
00542     /// GetElementPtr instructions GEP1 and GEP2 which have common base
00543     /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
00544     /// difference between the two pointers.
00545     void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
00546                             const SmallVectorImpl<VariableGEPIndex> &Src);
00547 
00548     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
00549     // instruction against another.
00550     AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
00551                          const AAMDNodes &V1AAInfo,
00552                          const Value *V2, uint64_t V2Size,
00553                          const AAMDNodes &V2AAInfo,
00554                          const Value *UnderlyingV1, const Value *UnderlyingV2);
00555 
00556     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
00557     // instruction against another.
00558     AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
00559                          const AAMDNodes &PNAAInfo,
00560                          const Value *V2, uint64_t V2Size,
00561                          const AAMDNodes &V2AAInfo);
00562 
00563     /// aliasSelect - Disambiguate a Select instruction against another value.
00564     AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
00565                             const AAMDNodes &SIAAInfo,
00566                             const Value *V2, uint64_t V2Size,
00567                             const AAMDNodes &V2AAInfo);
00568 
00569     AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
00570                            AAMDNodes V1AATag,
00571                            const Value *V2, uint64_t V2Size,
00572                            AAMDNodes V2AATag);
00573   };
00574 }  // End of anonymous namespace
00575 
00576 // Register this pass...
00577 char BasicAliasAnalysis::ID = 0;
00578 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
00579                    "Basic Alias Analysis (stateless AA impl)",
00580                    false, true, false)
00581 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00582 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00583 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
00584                    "Basic Alias Analysis (stateless AA impl)",
00585                    false, true, false)
00586 
00587 
00588 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
00589   return new BasicAliasAnalysis();
00590 }
00591 
00592 /// pointsToConstantMemory - Returns whether the given pointer value
00593 /// points to memory that is local to the function, with global constants being
00594 /// considered local to all functions.
00595 bool
00596 BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
00597   assert(Visited.empty() && "Visited must be cleared after use!");
00598 
00599   unsigned MaxLookup = 8;
00600   SmallVector<const Value *, 16> Worklist;
00601   Worklist.push_back(Loc.Ptr);
00602   do {
00603     const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
00604     if (!Visited.insert(V).second) {
00605       Visited.clear();
00606       return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
00607     }
00608 
00609     // An alloca instruction defines local memory.
00610     if (OrLocal && isa<AllocaInst>(V))
00611       continue;
00612 
00613     // A global constant counts as local memory for our purposes.
00614     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
00615       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
00616       // global to be marked constant in some modules and non-constant in
00617       // others.  GV may even be a declaration, not a definition.
00618       if (!GV->isConstant()) {
00619         Visited.clear();
00620         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
00621       }
00622       continue;
00623     }
00624 
00625     // If both select values point to local memory, then so does the select.
00626     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
00627       Worklist.push_back(SI->getTrueValue());
00628       Worklist.push_back(SI->getFalseValue());
00629       continue;
00630     }
00631 
00632     // If all values incoming to a phi node point to local memory, then so does
00633     // the phi.
00634     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
00635       // Don't bother inspecting phi nodes with many operands.
00636       if (PN->getNumIncomingValues() > MaxLookup) {
00637         Visited.clear();
00638         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
00639       }
00640       for (Value *IncValue : PN->incoming_values())
00641         Worklist.push_back(IncValue);
00642       continue;
00643     }
00644 
00645     // Otherwise be conservative.
00646     Visited.clear();
00647     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
00648 
00649   } while (!Worklist.empty() && --MaxLookup);
00650 
00651   Visited.clear();
00652   return Worklist.empty();
00653 }
00654 
00655 static bool isMemsetPattern16(const Function *MS,
00656                               const TargetLibraryInfo &TLI) {
00657   if (TLI.has(LibFunc::memset_pattern16) &&
00658       MS->getName() == "memset_pattern16") {
00659     FunctionType *MemsetType = MS->getFunctionType();
00660     if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
00661         isa<PointerType>(MemsetType->getParamType(0)) &&
00662         isa<PointerType>(MemsetType->getParamType(1)) &&
00663         isa<IntegerType>(MemsetType->getParamType(2)))
00664       return true;
00665   }
00666 
00667   return false;
00668 }
00669 
00670 /// getModRefBehavior - Return the behavior when calling the given call site.
00671 AliasAnalysis::ModRefBehavior
00672 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
00673   if (CS.doesNotAccessMemory())
00674     // Can't do better than this.
00675     return DoesNotAccessMemory;
00676 
00677   ModRefBehavior Min = UnknownModRefBehavior;
00678 
00679   // If the callsite knows it only reads memory, don't return worse
00680   // than that.
00681   if (CS.onlyReadsMemory())
00682     Min = OnlyReadsMemory;
00683 
00684   // The AliasAnalysis base class has some smarts, lets use them.
00685   return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
00686 }
00687 
00688 /// getModRefBehavior - Return the behavior when calling the given function.
00689 /// For use when the call site is not known.
00690 AliasAnalysis::ModRefBehavior
00691 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
00692   // If the function declares it doesn't access memory, we can't do better.
00693   if (F->doesNotAccessMemory())
00694     return DoesNotAccessMemory;
00695 
00696   // For intrinsics, we can check the table.
00697   if (Intrinsic::ID iid = F->getIntrinsicID()) {
00698 #define GET_INTRINSIC_MODREF_BEHAVIOR
00699 #include "llvm/IR/Intrinsics.gen"
00700 #undef GET_INTRINSIC_MODREF_BEHAVIOR
00701   }
00702 
00703   ModRefBehavior Min = UnknownModRefBehavior;
00704 
00705   // If the function declares it only reads memory, go with that.
00706   if (F->onlyReadsMemory())
00707     Min = OnlyReadsMemory;
00708 
00709   const TargetLibraryInfo &TLI =
00710       getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00711   if (isMemsetPattern16(F, TLI))
00712     Min = OnlyAccessesArgumentPointees;
00713 
00714   // Otherwise be conservative.
00715   return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
00716 }
00717 
00718 AliasAnalysis::Location
00719 BasicAliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
00720                                    ModRefResult &Mask) {
00721   Location Loc = AliasAnalysis::getArgLocation(CS, ArgIdx, Mask);
00722   const TargetLibraryInfo &TLI =
00723       getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00724   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
00725   if (II != nullptr)
00726     switch (II->getIntrinsicID()) {
00727     default: break;
00728     case Intrinsic::memset:
00729     case Intrinsic::memcpy:
00730     case Intrinsic::memmove: {
00731       assert((ArgIdx == 0 || ArgIdx == 1) &&
00732              "Invalid argument index for memory intrinsic");
00733       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
00734         Loc.Size = LenCI->getZExtValue();
00735       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
00736              "Memory intrinsic location pointer not argument?");
00737       Mask = ArgIdx ? Ref : Mod;
00738       break;
00739     }
00740     case Intrinsic::lifetime_start:
00741     case Intrinsic::lifetime_end:
00742     case Intrinsic::invariant_start: {
00743       assert(ArgIdx == 1 && "Invalid argument index");
00744       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
00745              "Intrinsic location pointer not argument?");
00746       Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
00747       break;
00748     }
00749     case Intrinsic::invariant_end: {
00750       assert(ArgIdx == 2 && "Invalid argument index");
00751       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
00752              "Intrinsic location pointer not argument?");
00753       Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
00754       break;
00755     }
00756     case Intrinsic::arm_neon_vld1: {
00757       assert(ArgIdx == 0 && "Invalid argument index");
00758       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
00759              "Intrinsic location pointer not argument?");
00760       // LLVM's vld1 and vst1 intrinsics currently only support a single
00761       // vector register.
00762       if (DL)
00763         Loc.Size = DL->getTypeStoreSize(II->getType());
00764       break;
00765     }
00766     case Intrinsic::arm_neon_vst1: {
00767       assert(ArgIdx == 0 && "Invalid argument index");
00768       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
00769              "Intrinsic location pointer not argument?");
00770       if (DL)
00771         Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType());
00772       break;
00773     }
00774     }
00775 
00776   // We can bound the aliasing properties of memset_pattern16 just as we can
00777   // for memcpy/memset.  This is particularly important because the
00778   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
00779   // whenever possible.
00780   else if (CS.getCalledFunction() &&
00781            isMemsetPattern16(CS.getCalledFunction(), TLI)) {
00782     assert((ArgIdx == 0 || ArgIdx == 1) &&
00783            "Invalid argument index for memset_pattern16");
00784     if (ArgIdx == 1)
00785       Loc.Size = 16;
00786     else if (const ConstantInt *LenCI =
00787              dyn_cast<ConstantInt>(CS.getArgument(2)))
00788       Loc.Size = LenCI->getZExtValue();
00789     assert(Loc.Ptr == CS.getArgument(ArgIdx) &&
00790            "memset_pattern16 location pointer not argument?");
00791     Mask = ArgIdx ? Ref : Mod;
00792   }
00793   // FIXME: Handle memset_pattern4 and memset_pattern8 also.
00794 
00795   return Loc;
00796 }
00797 
00798 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
00799   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
00800   if (II && II->getIntrinsicID() == Intrinsic::assume)
00801     return true;
00802 
00803   return false;
00804 }
00805 
00806 bool BasicAliasAnalysis::doInitialization(Module &M) {
00807   InitializeAliasAnalysis(this, &M.getDataLayout());
00808   return true;
00809 }
00810 
00811 /// getModRefInfo - Check to see if the specified callsite can clobber the
00812 /// specified memory object.  Since we only look at local properties of this
00813 /// function, we really can't say much about this query.  We do, however, use
00814 /// simple "address taken" analysis on local objects.
00815 AliasAnalysis::ModRefResult
00816 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
00817                                   const Location &Loc) {
00818   assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
00819          "AliasAnalysis query involving multiple functions!");
00820 
00821   const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
00822 
00823   // If this is a tail call and Loc.Ptr points to a stack location, we know that
00824   // the tail call cannot access or modify the local stack.
00825   // We cannot exclude byval arguments here; these belong to the caller of
00826   // the current function not to the current function, and a tail callee
00827   // may reference them.
00828   if (isa<AllocaInst>(Object))
00829     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
00830       if (CI->isTailCall())
00831         return NoModRef;
00832 
00833   // If the pointer is to a locally allocated object that does not escape,
00834   // then the call can not mod/ref the pointer unless the call takes the pointer
00835   // as an argument, and itself doesn't capture it.
00836   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
00837       isNonEscapingLocalObject(Object)) {
00838     bool PassedAsArg = false;
00839     unsigned ArgNo = 0;
00840     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
00841          CI != CE; ++CI, ++ArgNo) {
00842       // Only look at the no-capture or byval pointer arguments.  If this
00843       // pointer were passed to arguments that were neither of these, then it
00844       // couldn't be no-capture.
00845       if (!(*CI)->getType()->isPointerTy() ||
00846           (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
00847         continue;
00848 
00849       // If this is a no-capture pointer argument, see if we can tell that it
00850       // is impossible to alias the pointer we're checking.  If not, we have to
00851       // assume that the call could touch the pointer, even though it doesn't
00852       // escape.
00853       if (!isNoAlias(Location(*CI), Location(Object))) {
00854         PassedAsArg = true;
00855         break;
00856       }
00857     }
00858 
00859     if (!PassedAsArg)
00860       return NoModRef;
00861   }
00862 
00863   // While the assume intrinsic is marked as arbitrarily writing so that
00864   // proper control dependencies will be maintained, it never aliases any
00865   // particular memory location.
00866   if (isAssumeIntrinsic(CS))
00867     return NoModRef;
00868 
00869   // The AliasAnalysis base class has some smarts, lets use them.
00870   return AliasAnalysis::getModRefInfo(CS, Loc);
00871 }
00872 
00873 AliasAnalysis::ModRefResult
00874 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
00875                                   ImmutableCallSite CS2) {
00876   // While the assume intrinsic is marked as arbitrarily writing so that
00877   // proper control dependencies will be maintained, it never aliases any
00878   // particular memory location.
00879   if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
00880     return NoModRef;
00881 
00882   // The AliasAnalysis base class has some smarts, lets use them.
00883   return AliasAnalysis::getModRefInfo(CS1, CS2);
00884 }
00885 
00886 /// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
00887 /// operators, both having the exact same pointer operand.
00888 static AliasAnalysis::AliasResult
00889 aliasSameBasePointerGEPs(const GEPOperator *GEP1, uint64_t V1Size,
00890                          const GEPOperator *GEP2, uint64_t V2Size,
00891                          const DataLayout &DL) {
00892 
00893   assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
00894          "Expected GEPs with the same pointer operand");
00895 
00896   // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
00897   // such that the struct field accesses provably cannot alias.
00898   // We also need at least two indices (the pointer, and the struct field).
00899   if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
00900       GEP1->getNumIndices() < 2)
00901     return AliasAnalysis::MayAlias;
00902 
00903   // If we don't know the size of the accesses through both GEPs, we can't
00904   // determine whether the struct fields accessed can't alias.
00905   if (V1Size == AliasAnalysis::UnknownSize ||
00906       V2Size == AliasAnalysis::UnknownSize)
00907     return AliasAnalysis::MayAlias;
00908 
00909   ConstantInt *C1 =
00910       dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
00911   ConstantInt *C2 =
00912       dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
00913 
00914   // If the last (struct) indices aren't constants, we can't say anything.
00915   // If they're identical, the other indices might be also be dynamically
00916   // equal, so the GEPs can alias.
00917   if (!C1 || !C2 || C1 == C2)
00918     return AliasAnalysis::MayAlias;
00919 
00920   // Find the last-indexed type of the GEP, i.e., the type you'd get if
00921   // you stripped the last index.
00922   // On the way, look at each indexed type.  If there's something other
00923   // than an array, different indices can lead to different final types.
00924   SmallVector<Value *, 8> IntermediateIndices;
00925 
00926   // Insert the first index; we don't need to check the type indexed
00927   // through it as it only drops the pointer indirection.
00928   assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
00929   IntermediateIndices.push_back(GEP1->getOperand(1));
00930 
00931   // Insert all the remaining indices but the last one.
00932   // Also, check that they all index through arrays.
00933   for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
00934     if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
00935             GEP1->getSourceElementType(), IntermediateIndices)))
00936       return AliasAnalysis::MayAlias;
00937     IntermediateIndices.push_back(GEP1->getOperand(i + 1));
00938   }
00939 
00940   StructType *LastIndexedStruct =
00941       dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
00942           GEP1->getSourceElementType(), IntermediateIndices));
00943 
00944   if (!LastIndexedStruct)
00945     return AliasAnalysis::MayAlias;
00946 
00947   // We know that:
00948   // - both GEPs begin indexing from the exact same pointer;
00949   // - the last indices in both GEPs are constants, indexing into a struct;
00950   // - said indices are different, hence, the pointed-to fields are different;
00951   // - both GEPs only index through arrays prior to that.
00952   //
00953   // This lets us determine that the struct that GEP1 indexes into and the
00954   // struct that GEP2 indexes into must either precisely overlap or be
00955   // completely disjoint.  Because they cannot partially overlap, indexing into
00956   // different non-overlapping fields of the struct will never alias.
00957 
00958   // Therefore, the only remaining thing needed to show that both GEPs can't
00959   // alias is that the fields are not overlapping.
00960   const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
00961   const uint64_t StructSize = SL->getSizeInBytes();
00962   const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
00963   const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
00964 
00965   auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
00966                                       uint64_t V2Off, uint64_t V2Size) {
00967     return V1Off < V2Off && V1Off + V1Size <= V2Off &&
00968            ((V2Off + V2Size <= StructSize) ||
00969             (V2Off + V2Size - StructSize <= V1Off));
00970   };
00971 
00972   if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
00973       EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
00974     return AliasAnalysis::NoAlias;
00975 
00976   return AliasAnalysis::MayAlias;
00977 }
00978 
00979 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
00980 /// against another pointer.  We know that V1 is a GEP, but we don't know
00981 /// anything about V2.  UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
00982 /// UnderlyingV2 is the same for V2.
00983 ///
00984 AliasAnalysis::AliasResult
00985 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
00986                              const AAMDNodes &V1AAInfo,
00987                              const Value *V2, uint64_t V2Size,
00988                              const AAMDNodes &V2AAInfo,
00989                              const Value *UnderlyingV1,
00990                              const Value *UnderlyingV2) {
00991   int64_t GEP1BaseOffset;
00992   bool GEP1MaxLookupReached;
00993   SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
00994 
00995   // We have to get two AssumptionCaches here because GEP1 and V2 may be from
00996   // different functions.
00997   // FIXME: This really doesn't make any sense. We get a dominator tree below
00998   // that can only refer to a single function. But this function (aliasGEP) is
00999   // a method on an immutable pass that can be called when there *isn't*
01000   // a single function. The old pass management layer makes this "work", but
01001   // this isn't really a clean solution.
01002   AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
01003   AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
01004   if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
01005     AC1 = &ACT.getAssumptionCache(
01006         const_cast<Function &>(*GEP1I->getParent()->getParent()));
01007   if (auto *I2 = dyn_cast<Instruction>(V2))
01008     AC2 = &ACT.getAssumptionCache(
01009         const_cast<Function &>(*I2->getParent()->getParent()));
01010 
01011   DominatorTreeWrapperPass *DTWP =
01012       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
01013   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
01014 
01015   // If we have two gep instructions with must-alias or not-alias'ing base
01016   // pointers, figure out if the indexes to the GEP tell us anything about the
01017   // derived pointer.
01018   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
01019     // Do the base pointers alias?
01020     AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
01021                                        UnderlyingV2, UnknownSize, AAMDNodes());
01022 
01023     // Check for geps of non-aliasing underlying pointers where the offsets are
01024     // identical.
01025     if ((BaseAlias == MayAlias) && V1Size == V2Size) {
01026       // Do the base pointers alias assuming type and size.
01027       AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
01028                                                 V1AAInfo, UnderlyingV2,
01029                                                 V2Size, V2AAInfo);
01030       if (PreciseBaseAlias == NoAlias) {
01031         // See if the computed offset from the common pointer tells us about the
01032         // relation of the resulting pointer.
01033         int64_t GEP2BaseOffset;
01034         bool GEP2MaxLookupReached;
01035         SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
01036         const Value *GEP2BasePtr =
01037             DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
01038                                    GEP2MaxLookupReached, *DL, AC2, DT);
01039         const Value *GEP1BasePtr =
01040             DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
01041                                    GEP1MaxLookupReached, *DL, AC1, DT);
01042         // DecomposeGEPExpression and GetUnderlyingObject should return the
01043         // same result except when DecomposeGEPExpression has no DataLayout.
01044         if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
01045           assert(!DL &&
01046                  "DecomposeGEPExpression and GetUnderlyingObject disagree!");
01047           return MayAlias;
01048         }
01049         // If the max search depth is reached the result is undefined
01050         if (GEP2MaxLookupReached || GEP1MaxLookupReached)
01051           return MayAlias;
01052 
01053         // Same offsets.
01054         if (GEP1BaseOffset == GEP2BaseOffset &&
01055             GEP1VariableIndices == GEP2VariableIndices)
01056           return NoAlias;
01057         GEP1VariableIndices.clear();
01058       }
01059     }
01060 
01061     // If we get a No or May, then return it immediately, no amount of analysis
01062     // will improve this situation.
01063     if (BaseAlias != MustAlias) return BaseAlias;
01064 
01065     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
01066     // exactly, see if the computed offset from the common pointer tells us
01067     // about the relation of the resulting pointer.
01068     const Value *GEP1BasePtr =
01069         DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
01070                                GEP1MaxLookupReached, *DL, AC1, DT);
01071 
01072     int64_t GEP2BaseOffset;
01073     bool GEP2MaxLookupReached;
01074     SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
01075     const Value *GEP2BasePtr =
01076         DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
01077                                GEP2MaxLookupReached, *DL, AC2, DT);
01078 
01079     // DecomposeGEPExpression and GetUnderlyingObject should return the
01080     // same result except when DecomposeGEPExpression has no DataLayout.
01081     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
01082       assert(!DL &&
01083              "DecomposeGEPExpression and GetUnderlyingObject disagree!");
01084       return MayAlias;
01085     }
01086 
01087     // If we know the two GEPs are based off of the exact same pointer (and not
01088     // just the same underlying object), see if that tells us anything about
01089     // the resulting pointers.
01090     if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
01091       AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
01092       // If we couldn't find anything interesting, don't abandon just yet.
01093       if (R != MayAlias)
01094         return R;
01095     }
01096 
01097     // If the max search depth is reached the result is undefined
01098     if (GEP2MaxLookupReached || GEP1MaxLookupReached)
01099       return MayAlias;
01100 
01101     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
01102     // symbolic difference.
01103     GEP1BaseOffset -= GEP2BaseOffset;
01104     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
01105 
01106   } else {
01107     // Check to see if these two pointers are related by the getelementptr
01108     // instruction.  If one pointer is a GEP with a non-zero index of the other
01109     // pointer, we know they cannot alias.
01110 
01111     // If both accesses are unknown size, we can't do anything useful here.
01112     if (V1Size == UnknownSize && V2Size == UnknownSize)
01113       return MayAlias;
01114 
01115     AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
01116                                V2, V2Size, V2AAInfo);
01117     if (R != MustAlias)
01118       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
01119       // If V2 is known not to alias GEP base pointer, then the two values
01120       // cannot alias per GEP semantics: "A pointer value formed from a
01121       // getelementptr instruction is associated with the addresses associated
01122       // with the first operand of the getelementptr".
01123       return R;
01124 
01125     const Value *GEP1BasePtr =
01126         DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
01127                                GEP1MaxLookupReached, *DL, AC1, DT);
01128 
01129     // DecomposeGEPExpression and GetUnderlyingObject should return the
01130     // same result except when DecomposeGEPExpression has no DataLayout.
01131     if (GEP1BasePtr != UnderlyingV1) {
01132       assert(!DL &&
01133              "DecomposeGEPExpression and GetUnderlyingObject disagree!");
01134       return MayAlias;
01135     }
01136     // If the max search depth is reached the result is undefined
01137     if (GEP1MaxLookupReached)
01138       return MayAlias;
01139   }
01140 
01141   // In the two GEP Case, if there is no difference in the offsets of the
01142   // computed pointers, the resultant pointers are a must alias.  This
01143   // hapens when we have two lexically identical GEP's (for example).
01144   //
01145   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
01146   // must aliases the GEP, the end result is a must alias also.
01147   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
01148     return MustAlias;
01149 
01150   // If there is a constant difference between the pointers, but the difference
01151   // is less than the size of the associated memory object, then we know
01152   // that the objects are partially overlapping.  If the difference is
01153   // greater, we know they do not overlap.
01154   if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
01155     if (GEP1BaseOffset >= 0) {
01156       if (V2Size != UnknownSize) {
01157         if ((uint64_t)GEP1BaseOffset < V2Size)
01158           return PartialAlias;
01159         return NoAlias;
01160       }
01161     } else {
01162       // We have the situation where:
01163       // +                +
01164       // | BaseOffset     |
01165       // ---------------->|
01166       // |-->V1Size       |-------> V2Size
01167       // GEP1             V2
01168       // We need to know that V2Size is not unknown, otherwise we might have
01169       // stripped a gep with negative index ('gep <ptr>, -1, ...).
01170       if (V1Size != UnknownSize && V2Size != UnknownSize) {
01171         if (-(uint64_t)GEP1BaseOffset < V1Size)
01172           return PartialAlias;
01173         return NoAlias;
01174       }
01175     }
01176   }
01177 
01178   if (!GEP1VariableIndices.empty()) {
01179     uint64_t Modulo = 0;
01180     bool AllPositive = true;
01181     for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
01182 
01183       // Try to distinguish something like &A[i][1] against &A[42][0].
01184       // Grab the least significant bit set in any of the scales. We
01185       // don't need std::abs here (even if the scale's negative) as we'll
01186       // be ^'ing Modulo with itself later.
01187       Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
01188 
01189       if (AllPositive) {
01190         // If the Value could change between cycles, then any reasoning about
01191         // the Value this cycle may not hold in the next cycle. We'll just
01192         // give up if we can't determine conditions that hold for every cycle:
01193         const Value *V = GEP1VariableIndices[i].V;
01194 
01195         bool SignKnownZero, SignKnownOne;
01196         ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
01197                        0, AC1, nullptr, DT);
01198 
01199         // Zero-extension widens the variable, and so forces the sign
01200         // bit to zero.
01201         bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
01202         SignKnownZero |= IsZExt;
01203         SignKnownOne &= !IsZExt;
01204 
01205         // If the variable begins with a zero then we know it's
01206         // positive, regardless of whether the value is signed or
01207         // unsigned.
01208         int64_t Scale = GEP1VariableIndices[i].Scale;
01209         AllPositive =
01210           (SignKnownZero && Scale >= 0) ||
01211           (SignKnownOne && Scale < 0);
01212       }
01213     }
01214 
01215     Modulo = Modulo ^ (Modulo & (Modulo - 1));
01216 
01217     // We can compute the difference between the two addresses
01218     // mod Modulo. Check whether that difference guarantees that the
01219     // two locations do not alias.
01220     uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
01221     if (V1Size != UnknownSize && V2Size != UnknownSize &&
01222         ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
01223       return NoAlias;
01224 
01225     // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
01226     // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
01227     // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
01228     if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
01229       return NoAlias;
01230   }
01231 
01232   // Statically, we can see that the base objects are the same, but the
01233   // pointers have dynamic offsets which we can't resolve. And none of our
01234   // little tricks above worked.
01235   //
01236   // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
01237   // practical effect of this is protecting TBAA in the case of dynamic
01238   // indices into arrays of unions or malloc'd memory.
01239   return PartialAlias;
01240 }
01241 
01242 static AliasAnalysis::AliasResult
01243 MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
01244   // If the results agree, take it.
01245   if (A == B)
01246     return A;
01247   // A mix of PartialAlias and MustAlias is PartialAlias.
01248   if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
01249       (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
01250     return AliasAnalysis::PartialAlias;
01251   // Otherwise, we don't know anything.
01252   return AliasAnalysis::MayAlias;
01253 }
01254 
01255 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
01256 /// instruction against another.
01257 AliasAnalysis::AliasResult
01258 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
01259                                 const AAMDNodes &SIAAInfo,
01260                                 const Value *V2, uint64_t V2Size,
01261                                 const AAMDNodes &V2AAInfo) {
01262   // If the values are Selects with the same condition, we can do a more precise
01263   // check: just check for aliases between the values on corresponding arms.
01264   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
01265     if (SI->getCondition() == SI2->getCondition()) {
01266       AliasResult Alias =
01267         aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
01268                    SI2->getTrueValue(), V2Size, V2AAInfo);
01269       if (Alias == MayAlias)
01270         return MayAlias;
01271       AliasResult ThisAlias =
01272         aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
01273                    SI2->getFalseValue(), V2Size, V2AAInfo);
01274       return MergeAliasResults(ThisAlias, Alias);
01275     }
01276 
01277   // If both arms of the Select node NoAlias or MustAlias V2, then returns
01278   // NoAlias / MustAlias. Otherwise, returns MayAlias.
01279   AliasResult Alias =
01280     aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
01281   if (Alias == MayAlias)
01282     return MayAlias;
01283 
01284   AliasResult ThisAlias =
01285     aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
01286   return MergeAliasResults(ThisAlias, Alias);
01287 }
01288 
01289 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
01290 // against another.
01291 AliasAnalysis::AliasResult
01292 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
01293                              const AAMDNodes &PNAAInfo,
01294                              const Value *V2, uint64_t V2Size,
01295                              const AAMDNodes &V2AAInfo) {
01296   // Track phi nodes we have visited. We use this information when we determine
01297   // value equivalence.
01298   VisitedPhiBBs.insert(PN->getParent());
01299 
01300   // If the values are PHIs in the same block, we can do a more precise
01301   // as well as efficient check: just check for aliases between the values
01302   // on corresponding edges.
01303   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
01304     if (PN2->getParent() == PN->getParent()) {
01305       LocPair Locs(Location(PN, PNSize, PNAAInfo),
01306                    Location(V2, V2Size, V2AAInfo));
01307       if (PN > V2)
01308         std::swap(Locs.first, Locs.second);
01309       // Analyse the PHIs' inputs under the assumption that the PHIs are
01310       // NoAlias.
01311       // If the PHIs are May/MustAlias there must be (recursively) an input
01312       // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
01313       // there must be an operation on the PHIs within the PHIs' value cycle
01314       // that causes a MayAlias.
01315       // Pretend the phis do not alias.
01316       AliasResult Alias = NoAlias;
01317       assert(AliasCache.count(Locs) &&
01318              "There must exist an entry for the phi node");
01319       AliasResult OrigAliasResult = AliasCache[Locs];
01320       AliasCache[Locs] = NoAlias;
01321 
01322       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01323         AliasResult ThisAlias =
01324           aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
01325                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
01326                      V2Size, V2AAInfo);
01327         Alias = MergeAliasResults(ThisAlias, Alias);
01328         if (Alias == MayAlias)
01329           break;
01330       }
01331 
01332       // Reset if speculation failed.
01333       if (Alias != NoAlias)
01334         AliasCache[Locs] = OrigAliasResult;
01335 
01336       return Alias;
01337     }
01338 
01339   SmallPtrSet<Value*, 4> UniqueSrc;
01340   SmallVector<Value*, 4> V1Srcs;
01341   for (Value *PV1 : PN->incoming_values()) {
01342     if (isa<PHINode>(PV1))
01343       // If any of the source itself is a PHI, return MayAlias conservatively
01344       // to avoid compile time explosion. The worst possible case is if both
01345       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
01346       // and 'n' are the number of PHI sources.
01347       return MayAlias;
01348     if (UniqueSrc.insert(PV1).second)
01349       V1Srcs.push_back(PV1);
01350   }
01351 
01352   AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
01353                                  V1Srcs[0], PNSize, PNAAInfo);
01354   // Early exit if the check of the first PHI source against V2 is MayAlias.
01355   // Other results are not possible.
01356   if (Alias == MayAlias)
01357     return MayAlias;
01358 
01359   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
01360   // NoAlias / MustAlias. Otherwise, returns MayAlias.
01361   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
01362     Value *V = V1Srcs[i];
01363 
01364     AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
01365                                        V, PNSize, PNAAInfo);
01366     Alias = MergeAliasResults(ThisAlias, Alias);
01367     if (Alias == MayAlias)
01368       break;
01369   }
01370 
01371   return Alias;
01372 }
01373 
01374 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
01375 // such as array references.
01376 //
01377 AliasAnalysis::AliasResult
01378 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
01379                                AAMDNodes V1AAInfo,
01380                                const Value *V2, uint64_t V2Size,
01381                                AAMDNodes V2AAInfo) {
01382   // If either of the memory references is empty, it doesn't matter what the
01383   // pointer values are.
01384   if (V1Size == 0 || V2Size == 0)
01385     return NoAlias;
01386 
01387   // Strip off any casts if they exist.
01388   V1 = V1->stripPointerCasts();
01389   V2 = V2->stripPointerCasts();
01390 
01391   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
01392   // value for undef that aliases nothing in the program.
01393   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
01394     return NoAlias;
01395 
01396   // Are we checking for alias of the same value?
01397   // Because we look 'through' phi nodes we could look at "Value" pointers from
01398   // different iterations. We must therefore make sure that this is not the
01399   // case. The function isValueEqualInPotentialCycles ensures that this cannot
01400   // happen by looking at the visited phi nodes and making sure they cannot
01401   // reach the value.
01402   if (isValueEqualInPotentialCycles(V1, V2))
01403     return MustAlias;
01404 
01405   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
01406     return NoAlias;  // Scalars cannot alias each other
01407 
01408   // Figure out what objects these things are pointing to if we can.
01409   const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
01410   const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
01411 
01412   // Null values in the default address space don't point to any object, so they
01413   // don't alias any other pointer.
01414   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
01415     if (CPN->getType()->getAddressSpace() == 0)
01416       return NoAlias;
01417   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
01418     if (CPN->getType()->getAddressSpace() == 0)
01419       return NoAlias;
01420 
01421   if (O1 != O2) {
01422     // If V1/V2 point to two different objects we know that we have no alias.
01423     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
01424       return NoAlias;
01425 
01426     // Constant pointers can't alias with non-const isIdentifiedObject objects.
01427     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
01428         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
01429       return NoAlias;
01430 
01431     // Function arguments can't alias with things that are known to be
01432     // unambigously identified at the function level.
01433     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
01434         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
01435       return NoAlias;
01436 
01437     // Most objects can't alias null.
01438     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
01439         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
01440       return NoAlias;
01441 
01442     // If one pointer is the result of a call/invoke or load and the other is a
01443     // non-escaping local object within the same function, then we know the
01444     // object couldn't escape to a point where the call could return it.
01445     //
01446     // Note that if the pointers are in different functions, there are a
01447     // variety of complications. A call with a nocapture argument may still
01448     // temporary store the nocapture argument's value in a temporary memory
01449     // location if that memory location doesn't escape. Or it may pass a
01450     // nocapture value to other functions as long as they don't capture it.
01451     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
01452       return NoAlias;
01453     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
01454       return NoAlias;
01455   }
01456 
01457   // If the size of one access is larger than the entire object on the other
01458   // side, then we know such behavior is undefined and can assume no alias.
01459   if (DL)
01460     if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
01461         (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
01462       return NoAlias;
01463 
01464   // Check the cache before climbing up use-def chains. This also terminates
01465   // otherwise infinitely recursive queries.
01466   LocPair Locs(Location(V1, V1Size, V1AAInfo),
01467                Location(V2, V2Size, V2AAInfo));
01468   if (V1 > V2)
01469     std::swap(Locs.first, Locs.second);
01470   std::pair<AliasCacheTy::iterator, bool> Pair =
01471     AliasCache.insert(std::make_pair(Locs, MayAlias));
01472   if (!Pair.second)
01473     return Pair.first->second;
01474 
01475   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
01476   // GEP can't simplify, we don't even look at the PHI cases.
01477   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
01478     std::swap(V1, V2);
01479     std::swap(V1Size, V2Size);
01480     std::swap(O1, O2);
01481     std::swap(V1AAInfo, V2AAInfo);
01482   }
01483   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
01484     AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
01485     if (Result != MayAlias) return AliasCache[Locs] = Result;
01486   }
01487 
01488   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
01489     std::swap(V1, V2);
01490     std::swap(V1Size, V2Size);
01491     std::swap(V1AAInfo, V2AAInfo);
01492   }
01493   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
01494     AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
01495                                   V2, V2Size, V2AAInfo);
01496     if (Result != MayAlias) return AliasCache[Locs] = Result;
01497   }
01498 
01499   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
01500     std::swap(V1, V2);
01501     std::swap(V1Size, V2Size);
01502     std::swap(V1AAInfo, V2AAInfo);
01503   }
01504   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
01505     AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
01506                                      V2, V2Size, V2AAInfo);
01507     if (Result != MayAlias) return AliasCache[Locs] = Result;
01508   }
01509 
01510   // If both pointers are pointing into the same object and one of them
01511   // accesses is accessing the entire object, then the accesses must
01512   // overlap in some way.
01513   if (DL && O1 == O2)
01514     if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
01515         (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
01516       return AliasCache[Locs] = PartialAlias;
01517 
01518   AliasResult Result =
01519     AliasAnalysis::alias(Location(V1, V1Size, V1AAInfo),
01520                          Location(V2, V2Size, V2AAInfo));
01521   return AliasCache[Locs] = Result;
01522 }
01523 
01524 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
01525                                                        const Value *V2) {
01526   if (V != V2)
01527     return false;
01528 
01529   const Instruction *Inst = dyn_cast<Instruction>(V);
01530   if (!Inst)
01531     return true;
01532 
01533   if (VisitedPhiBBs.empty())
01534     return true;
01535 
01536   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
01537     return false;
01538 
01539   // Use dominance or loop info if available.
01540   DominatorTreeWrapperPass *DTWP =
01541       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
01542   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
01543   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
01544   LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
01545 
01546   // Make sure that the visited phis cannot reach the Value. This ensures that
01547   // the Values cannot come from different iterations of a potential cycle the
01548   // phi nodes could be involved in.
01549   for (auto *P : VisitedPhiBBs)
01550     if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
01551       return false;
01552 
01553   return true;
01554 }
01555 
01556 /// GetIndexDifference - Dest and Src are the variable indices from two
01557 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
01558 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
01559 /// difference between the two pointers.
01560 void BasicAliasAnalysis::GetIndexDifference(
01561     SmallVectorImpl<VariableGEPIndex> &Dest,
01562     const SmallVectorImpl<VariableGEPIndex> &Src) {
01563   if (Src.empty())
01564     return;
01565 
01566   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
01567     const Value *V = Src[i].V;
01568     ExtensionKind Extension = Src[i].Extension;
01569     int64_t Scale = Src[i].Scale;
01570 
01571     // Find V in Dest.  This is N^2, but pointer indices almost never have more
01572     // than a few variable indexes.
01573     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
01574       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
01575           Dest[j].Extension != Extension)
01576         continue;
01577 
01578       // If we found it, subtract off Scale V's from the entry in Dest.  If it
01579       // goes to zero, remove the entry.
01580       if (Dest[j].Scale != Scale)
01581         Dest[j].Scale -= Scale;
01582       else
01583         Dest.erase(Dest.begin() + j);
01584       Scale = 0;
01585       break;
01586     }
01587 
01588     // If we didn't consume this entry, add it to the end of the Dest list.
01589     if (Scale) {
01590       VariableGEPIndex Entry = { V, Extension, -Scale };
01591       Dest.push_back(Entry);
01592     }
01593   }
01594 }