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