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