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