LLVM API Documentation

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