Improve BasicAA CS-CS queries (redux)
[oota-llvm.git] / lib / Analysis / BasicAliasAnalysis.cpp
1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the primary stateless implementation of the
11 // Alias Analysis interface that implements identities (two different
12 // globals cannot alias, etc), but does no stateful analysis.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Analysis/Passes.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/Analysis/CaptureTracking.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43
44 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
45 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
46 /// careful with value equivalence. We use reachability to make sure a value
47 /// cannot be involved in a cycle.
48 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
49
50 // The max limit of the search depth in DecomposeGEPExpression() and
51 // GetUnderlyingObject(), both functions need to use the same search
52 // depth otherwise the algorithm in aliasGEP will assert.
53 static const unsigned MaxLookupSearchDepth = 6;
54
55 //===----------------------------------------------------------------------===//
56 // Useful predicates
57 //===----------------------------------------------------------------------===//
58
59 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
60 /// object that never escapes from the function.
61 static bool isNonEscapingLocalObject(const Value *V) {
62   // If this is a local allocation, check to see if it escapes.
63   if (isa<AllocaInst>(V) || isNoAliasCall(V))
64     // Set StoreCaptures to True so that we can assume in our callers that the
65     // pointer is not the result of a load instruction. Currently
66     // PointerMayBeCaptured doesn't have any special analysis for the
67     // StoreCaptures=false case; if it did, our callers could be refined to be
68     // more precise.
69     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
70
71   // If this is an argument that corresponds to a byval or noalias argument,
72   // then it has not escaped before entering the function.  Check if it escapes
73   // inside the function.
74   if (const Argument *A = dyn_cast<Argument>(V))
75     if (A->hasByValAttr() || A->hasNoAliasAttr())
76       // Note even if the argument is marked nocapture we still need to check
77       // for copies made inside the function. The nocapture attribute only
78       // specifies that there are no copies made that outlive the function.
79       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
80
81   return false;
82 }
83
84 /// isEscapeSource - Return true if the pointer is one which would have
85 /// been considered an escape by isNonEscapingLocalObject.
86 static bool isEscapeSource(const Value *V) {
87   if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
88     return true;
89
90   // The load case works because isNonEscapingLocalObject considers all
91   // stores to be escapes (it passes true for the StoreCaptures argument
92   // to PointerMayBeCaptured).
93   if (isa<LoadInst>(V))
94     return true;
95
96   return false;
97 }
98
99 /// getObjectSize - Return the size of the object specified by V, or
100 /// UnknownSize if unknown.
101 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
102                               const TargetLibraryInfo &TLI,
103                               bool RoundToAlign = false) {
104   uint64_t Size;
105   if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign))
106     return Size;
107   return AliasAnalysis::UnknownSize;
108 }
109
110 /// isObjectSmallerThan - Return true if we can prove that the object specified
111 /// by V is smaller than Size.
112 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
113                                 const DataLayout &DL,
114                                 const TargetLibraryInfo &TLI) {
115   // Note that the meanings of the "object" are slightly different in the
116   // following contexts:
117   //    c1: llvm::getObjectSize()
118   //    c2: llvm.objectsize() intrinsic
119   //    c3: isObjectSmallerThan()
120   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
121   // refers to the "entire object".
122   //
123   //  Consider this example:
124   //     char *p = (char*)malloc(100)
125   //     char *q = p+80;
126   //
127   //  In the context of c1 and c2, the "object" pointed by q refers to the
128   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
129   //
130   //  However, in the context of c3, the "object" refers to the chunk of memory
131   // being allocated. So, the "object" has 100 bytes, and q points to the middle
132   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
133   // parameter, before the llvm::getObjectSize() is called to get the size of
134   // entire object, we should:
135   //    - either rewind the pointer q to the base-address of the object in
136   //      question (in this case rewind to p), or
137   //    - just give up. It is up to caller to make sure the pointer is pointing
138   //      to the base address the object.
139   //
140   // We go for 2nd option for simplicity.
141   if (!isIdentifiedObject(V))
142     return false;
143
144   // This function needs to use the aligned object size because we allow
145   // reads a bit past the end given sufficient alignment.
146   uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
147
148   return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
149 }
150
151 /// isObjectSize - Return true if we can prove that the object specified
152 /// by V has size Size.
153 static bool isObjectSize(const Value *V, uint64_t Size,
154                          const DataLayout &DL, const TargetLibraryInfo &TLI) {
155   uint64_t ObjectSize = getObjectSize(V, DL, TLI);
156   return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
157 }
158
159 /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
160 /// at the function-level. Different IdentifiedFunctionLocals can't alias.
161 /// Further, an IdentifiedFunctionLocal can not alias with any function
162 /// arguments other than itself, which is not necessarily true for
163 /// IdentifiedObjects.
164 static bool isIdentifiedFunctionLocal(const Value *V)
165 {
166   return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
167 }
168
169
170 //===----------------------------------------------------------------------===//
171 // GetElementPtr Instruction Decomposition and Analysis
172 //===----------------------------------------------------------------------===//
173
174 namespace {
175   enum ExtensionKind {
176     EK_NotExtended,
177     EK_SignExt,
178     EK_ZeroExt
179   };
180
181   struct VariableGEPIndex {
182     const Value *V;
183     ExtensionKind Extension;
184     int64_t Scale;
185
186     bool operator==(const VariableGEPIndex &Other) const {
187       return V == Other.V && Extension == Other.Extension &&
188         Scale == Other.Scale;
189     }
190
191     bool operator!=(const VariableGEPIndex &Other) const {
192       return !operator==(Other);
193     }
194   };
195 }
196
197
198 /// GetLinearExpression - Analyze the specified value as a linear expression:
199 /// "A*V + B", where A and B are constant integers.  Return the scale and offset
200 /// values as APInts and return V as a Value*, and return whether we looked
201 /// through any sign or zero extends.  The incoming Value is known to have
202 /// IntegerType and it may already be sign or zero extended.
203 ///
204 /// Note that this looks through extends, so the high bits may not be
205 /// represented in the result.
206 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
207                                   ExtensionKind &Extension,
208                                   const DataLayout &DL, unsigned Depth) {
209   assert(V->getType()->isIntegerTy() && "Not an integer value");
210
211   // Limit our recursion depth.
212   if (Depth == 6) {
213     Scale = 1;
214     Offset = 0;
215     return V;
216   }
217
218   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
219     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
220       switch (BOp->getOpcode()) {
221       default: break;
222       case Instruction::Or:
223         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
224         // analyze it.
225         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL))
226           break;
227         // FALL THROUGH.
228       case Instruction::Add:
229         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
230                                 DL, Depth+1);
231         Offset += RHSC->getValue();
232         return V;
233       case Instruction::Mul:
234         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
235                                 DL, Depth+1);
236         Offset *= RHSC->getValue();
237         Scale *= RHSC->getValue();
238         return V;
239       case Instruction::Shl:
240         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
241                                 DL, Depth+1);
242         Offset <<= RHSC->getValue().getLimitedValue();
243         Scale <<= RHSC->getValue().getLimitedValue();
244         return V;
245       }
246     }
247   }
248
249   // Since GEP indices are sign extended anyway, we don't care about the high
250   // bits of a sign or zero extended value - just scales and offsets.  The
251   // extensions have to be consistent though.
252   if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
253       (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
254     Value *CastOp = cast<CastInst>(V)->getOperand(0);
255     unsigned OldWidth = Scale.getBitWidth();
256     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
257     Scale = Scale.trunc(SmallWidth);
258     Offset = Offset.trunc(SmallWidth);
259     Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
260
261     Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
262                                         DL, Depth+1);
263     Scale = Scale.zext(OldWidth);
264     Offset = Offset.zext(OldWidth);
265
266     return Result;
267   }
268
269   Scale = 1;
270   Offset = 0;
271   return V;
272 }
273
274 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
275 /// into a base pointer with a constant offset and a number of scaled symbolic
276 /// offsets.
277 ///
278 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
279 /// the VarIndices vector) are Value*'s that are known to be scaled by the
280 /// specified amount, but which may have other unrepresented high bits. As such,
281 /// the gep cannot necessarily be reconstructed from its decomposed form.
282 ///
283 /// When DataLayout is around, this function is capable of analyzing everything
284 /// that GetUnderlyingObject can look through. To be able to do that
285 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
286 /// depth (MaxLookupSearchDepth).
287 /// When DataLayout not is around, it just looks through pointer casts.
288 ///
289 static const Value *
290 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
291                        SmallVectorImpl<VariableGEPIndex> &VarIndices,
292                        bool &MaxLookupReached, const DataLayout *DL) {
293   // Limit recursion depth to limit compile time in crazy cases.
294   unsigned MaxLookup = MaxLookupSearchDepth;
295   MaxLookupReached = false;
296
297   BaseOffs = 0;
298   do {
299     // See if this is a bitcast or GEP.
300     const Operator *Op = dyn_cast<Operator>(V);
301     if (!Op) {
302       // The only non-operator case we can handle are GlobalAliases.
303       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
304         if (!GA->mayBeOverridden()) {
305           V = GA->getAliasee();
306           continue;
307         }
308       }
309       return V;
310     }
311
312     if (Op->getOpcode() == Instruction::BitCast ||
313         Op->getOpcode() == Instruction::AddrSpaceCast) {
314       V = Op->getOperand(0);
315       continue;
316     }
317
318     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
319     if (!GEPOp) {
320       // If it's not a GEP, hand it off to SimplifyInstruction to see if it
321       // can come up with something. This matches what GetUnderlyingObject does.
322       if (const Instruction *I = dyn_cast<Instruction>(V))
323         // TODO: Get a DominatorTree and use it here.
324         if (const Value *Simplified =
325               SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
326           V = Simplified;
327           continue;
328         }
329
330       return V;
331     }
332
333     // Don't attempt to analyze GEPs over unsized objects.
334     if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
335       return V;
336
337     // If we are lacking DataLayout information, we can't compute the offets of
338     // elements computed by GEPs.  However, we can handle bitcast equivalent
339     // GEPs.
340     if (!DL) {
341       if (!GEPOp->hasAllZeroIndices())
342         return V;
343       V = GEPOp->getOperand(0);
344       continue;
345     }
346
347     unsigned AS = GEPOp->getPointerAddressSpace();
348     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
349     gep_type_iterator GTI = gep_type_begin(GEPOp);
350     for (User::const_op_iterator I = GEPOp->op_begin()+1,
351          E = GEPOp->op_end(); I != E; ++I) {
352       Value *Index = *I;
353       // Compute the (potentially symbolic) offset in bytes for this index.
354       if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
355         // For a struct, add the member offset.
356         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
357         if (FieldNo == 0) continue;
358
359         BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
360         continue;
361       }
362
363       // For an array/pointer, add the element offset, explicitly scaled.
364       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
365         if (CIdx->isZero()) continue;
366         BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
367         continue;
368       }
369
370       uint64_t Scale = DL->getTypeAllocSize(*GTI);
371       ExtensionKind Extension = EK_NotExtended;
372
373       // If the integer type is smaller than the pointer size, it is implicitly
374       // sign extended to pointer size.
375       unsigned Width = Index->getType()->getIntegerBitWidth();
376       if (DL->getPointerSizeInBits(AS) > Width)
377         Extension = EK_SignExt;
378
379       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
380       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
381       Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
382                                   *DL, 0);
383
384       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
385       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
386       BaseOffs += IndexOffset.getSExtValue()*Scale;
387       Scale *= IndexScale.getSExtValue();
388
389       // If we already had an occurrence of this index variable, merge this
390       // scale into it.  For example, we want to handle:
391       //   A[x][x] -> x*16 + x*4 -> x*20
392       // This also ensures that 'x' only appears in the index list once.
393       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
394         if (VarIndices[i].V == Index &&
395             VarIndices[i].Extension == Extension) {
396           Scale += VarIndices[i].Scale;
397           VarIndices.erase(VarIndices.begin()+i);
398           break;
399         }
400       }
401
402       // Make sure that we have a scale that makes sense for this target's
403       // pointer size.
404       if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
405         Scale <<= ShiftBits;
406         Scale = (int64_t)Scale >> ShiftBits;
407       }
408
409       if (Scale) {
410         VariableGEPIndex Entry = {Index, Extension,
411                                   static_cast<int64_t>(Scale)};
412         VarIndices.push_back(Entry);
413       }
414     }
415
416     // Analyze the base pointer next.
417     V = GEPOp->getOperand(0);
418   } while (--MaxLookup);
419
420   // If the chain of expressions is too deep, just return early.
421   MaxLookupReached = true;
422   return V;
423 }
424
425 //===----------------------------------------------------------------------===//
426 // BasicAliasAnalysis Pass
427 //===----------------------------------------------------------------------===//
428
429 #ifndef NDEBUG
430 static const Function *getParent(const Value *V) {
431   if (const Instruction *inst = dyn_cast<Instruction>(V))
432     return inst->getParent()->getParent();
433
434   if (const Argument *arg = dyn_cast<Argument>(V))
435     return arg->getParent();
436
437   return nullptr;
438 }
439
440 static bool notDifferentParent(const Value *O1, const Value *O2) {
441
442   const Function *F1 = getParent(O1);
443   const Function *F2 = getParent(O2);
444
445   return !F1 || !F2 || F1 == F2;
446 }
447 #endif
448
449 namespace {
450   /// BasicAliasAnalysis - This is the primary alias analysis implementation.
451   struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
452     static char ID; // Class identification, replacement for typeinfo
453     BasicAliasAnalysis() : ImmutablePass(ID) {
454       initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
455     }
456
457     void initializePass() override {
458       InitializeAliasAnalysis(this);
459     }
460
461     void getAnalysisUsage(AnalysisUsage &AU) const override {
462       AU.addRequired<AliasAnalysis>();
463       AU.addRequired<TargetLibraryInfo>();
464     }
465
466     AliasResult alias(const Location &LocA, const Location &LocB) override {
467       assert(AliasCache.empty() && "AliasCache must be cleared after use!");
468       assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
469              "BasicAliasAnalysis doesn't support interprocedural queries.");
470       AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.TBAATag,
471                                      LocB.Ptr, LocB.Size, LocB.TBAATag);
472       // AliasCache rarely has more than 1 or 2 elements, always use
473       // shrink_and_clear so it quickly returns to the inline capacity of the
474       // SmallDenseMap if it ever grows larger.
475       // FIXME: This should really be shrink_to_inline_capacity_and_clear().
476       AliasCache.shrink_and_clear();
477       VisitedPhiBBs.clear();
478       return Alias;
479     }
480
481     ModRefResult getModRefInfo(ImmutableCallSite CS,
482                                const Location &Loc) override;
483
484     ModRefResult getModRefInfo(ImmutableCallSite CS1,
485                                ImmutableCallSite CS2) override {
486       // The AliasAnalysis base class has some smarts, lets use them.
487       return AliasAnalysis::getModRefInfo(CS1, CS2);
488     }
489
490     /// pointsToConstantMemory - Chase pointers until we find a (constant
491     /// global) or not.
492     bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
493
494     /// Get the location associated with a pointer argument of a callsite.
495     Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
496                             ModRefResult &Mask) override;
497
498     /// getModRefBehavior - Return the behavior when calling the given
499     /// call site.
500     ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
501
502     /// getModRefBehavior - Return the behavior when calling the given function.
503     /// For use when the call site is not known.
504     ModRefBehavior getModRefBehavior(const Function *F) override;
505
506     /// getAdjustedAnalysisPointer - This method is used when a pass implements
507     /// an analysis interface through multiple inheritance.  If needed, it
508     /// should override this to adjust the this pointer as needed for the
509     /// specified pass info.
510     void *getAdjustedAnalysisPointer(const void *ID) override {
511       if (ID == &AliasAnalysis::ID)
512         return (AliasAnalysis*)this;
513       return this;
514     }
515
516   private:
517     // AliasCache - Track alias queries to guard against recursion.
518     typedef std::pair<Location, Location> LocPair;
519     typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
520     AliasCacheTy AliasCache;
521
522     /// \brief Track phi nodes we have visited. When interpret "Value" pointer
523     /// equality as value equality we need to make sure that the "Value" is not
524     /// part of a cycle. Otherwise, two uses could come from different
525     /// "iterations" of a cycle and see different values for the same "Value"
526     /// pointer.
527     /// The following example shows the problem:
528     ///   %p = phi(%alloca1, %addr2)
529     ///   %l = load %ptr
530     ///   %addr1 = gep, %alloca2, 0, %l
531     ///   %addr2 = gep  %alloca2, 0, (%l + 1)
532     ///      alias(%p, %addr1) -> MayAlias !
533     ///   store %l, ...
534     SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
535
536     // Visited - Track instructions visited by pointsToConstantMemory.
537     SmallPtrSet<const Value*, 16> Visited;
538
539     /// \brief Check whether two Values can be considered equivalent.
540     ///
541     /// In addition to pointer equivalence of \p V1 and \p V2 this checks
542     /// whether they can not be part of a cycle in the value graph by looking at
543     /// all visited phi nodes an making sure that the phis cannot reach the
544     /// value. We have to do this because we are looking through phi nodes (That
545     /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
546     bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
547
548     /// \brief Dest and Src are the variable indices from two decomposed
549     /// GetElementPtr instructions GEP1 and GEP2 which have common base
550     /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
551     /// difference between the two pointers.
552     void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
553                             const SmallVectorImpl<VariableGEPIndex> &Src);
554
555     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
556     // instruction against another.
557     AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
558                          const MDNode *V1TBAAInfo,
559                          const Value *V2, uint64_t V2Size,
560                          const MDNode *V2TBAAInfo,
561                          const Value *UnderlyingV1, const Value *UnderlyingV2);
562
563     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
564     // instruction against another.
565     AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
566                          const MDNode *PNTBAAInfo,
567                          const Value *V2, uint64_t V2Size,
568                          const MDNode *V2TBAAInfo);
569
570     /// aliasSelect - Disambiguate a Select instruction against another value.
571     AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
572                             const MDNode *SITBAAInfo,
573                             const Value *V2, uint64_t V2Size,
574                             const MDNode *V2TBAAInfo);
575
576     AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
577                            const MDNode *V1TBAATag,
578                            const Value *V2, uint64_t V2Size,
579                            const MDNode *V2TBAATag);
580   };
581 }  // End of anonymous namespace
582
583 // Register this pass...
584 char BasicAliasAnalysis::ID = 0;
585 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
586                    "Basic Alias Analysis (stateless AA impl)",
587                    false, true, false)
588 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
589 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
590                    "Basic Alias Analysis (stateless AA impl)",
591                    false, true, false)
592
593
594 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
595   return new BasicAliasAnalysis();
596 }
597
598 /// pointsToConstantMemory - Returns whether the given pointer value
599 /// points to memory that is local to the function, with global constants being
600 /// considered local to all functions.
601 bool
602 BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
603   assert(Visited.empty() && "Visited must be cleared after use!");
604
605   unsigned MaxLookup = 8;
606   SmallVector<const Value *, 16> Worklist;
607   Worklist.push_back(Loc.Ptr);
608   do {
609     const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
610     if (!Visited.insert(V)) {
611       Visited.clear();
612       return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
613     }
614
615     // An alloca instruction defines local memory.
616     if (OrLocal && isa<AllocaInst>(V))
617       continue;
618
619     // A global constant counts as local memory for our purposes.
620     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
621       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
622       // global to be marked constant in some modules and non-constant in
623       // others.  GV may even be a declaration, not a definition.
624       if (!GV->isConstant()) {
625         Visited.clear();
626         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
627       }
628       continue;
629     }
630
631     // If both select values point to local memory, then so does the select.
632     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
633       Worklist.push_back(SI->getTrueValue());
634       Worklist.push_back(SI->getFalseValue());
635       continue;
636     }
637
638     // If all values incoming to a phi node point to local memory, then so does
639     // the phi.
640     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
641       // Don't bother inspecting phi nodes with many operands.
642       if (PN->getNumIncomingValues() > MaxLookup) {
643         Visited.clear();
644         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
645       }
646       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
647         Worklist.push_back(PN->getIncomingValue(i));
648       continue;
649     }
650
651     // Otherwise be conservative.
652     Visited.clear();
653     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
654
655   } while (!Worklist.empty() && --MaxLookup);
656
657   Visited.clear();
658   return Worklist.empty();
659 }
660
661 static bool isMemsetPattern16(const Function *MS,
662                               const TargetLibraryInfo &TLI) {
663   if (TLI.has(LibFunc::memset_pattern16) &&
664       MS->getName() == "memset_pattern16") {
665     FunctionType *MemsetType = MS->getFunctionType();
666     if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
667         isa<PointerType>(MemsetType->getParamType(0)) &&
668         isa<PointerType>(MemsetType->getParamType(1)) &&
669         isa<IntegerType>(MemsetType->getParamType(2)))
670       return true;
671   }
672
673   return false;
674 }
675
676 /// getModRefBehavior - Return the behavior when calling the given call site.
677 AliasAnalysis::ModRefBehavior
678 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
679   if (CS.doesNotAccessMemory())
680     // Can't do better than this.
681     return DoesNotAccessMemory;
682
683   ModRefBehavior Min = UnknownModRefBehavior;
684
685   // If the callsite knows it only reads memory, don't return worse
686   // than that.
687   if (CS.onlyReadsMemory())
688     Min = OnlyReadsMemory;
689
690   // The AliasAnalysis base class has some smarts, lets use them.
691   return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
692 }
693
694 /// getModRefBehavior - Return the behavior when calling the given function.
695 /// For use when the call site is not known.
696 AliasAnalysis::ModRefBehavior
697 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
698   // If the function declares it doesn't access memory, we can't do better.
699   if (F->doesNotAccessMemory())
700     return DoesNotAccessMemory;
701
702   // For intrinsics, we can check the table.
703   if (unsigned iid = F->getIntrinsicID()) {
704 #define GET_INTRINSIC_MODREF_BEHAVIOR
705 #include "llvm/IR/Intrinsics.gen"
706 #undef GET_INTRINSIC_MODREF_BEHAVIOR
707   }
708
709   ModRefBehavior Min = UnknownModRefBehavior;
710
711   // If the function declares it only reads memory, go with that.
712   if (F->onlyReadsMemory())
713     Min = OnlyReadsMemory;
714
715   const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
716   if (isMemsetPattern16(F, TLI))
717     Min = OnlyAccessesArgumentPointees;
718
719   // Otherwise be conservative.
720   return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
721 }
722
723 AliasAnalysis::Location
724 BasicAliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
725                                    ModRefResult &Mask) {
726   Location Loc = AliasAnalysis::getArgLocation(CS, ArgIdx, Mask);
727   const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
728   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
729   if (II != nullptr)
730     switch (II->getIntrinsicID()) {
731     default: break;
732     case Intrinsic::memset:
733     case Intrinsic::memcpy:
734     case Intrinsic::memmove: {
735       assert((ArgIdx == 0 || ArgIdx == 1) &&
736              "Invalid argument index for memory intrinsic");
737       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
738         Loc.Size = LenCI->getZExtValue();
739       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
740              "Memory intrinsic location pointer not argument?");
741       Mask = ArgIdx ? Ref : Mod;
742       break;
743     }
744     case Intrinsic::lifetime_start:
745     case Intrinsic::lifetime_end:
746     case Intrinsic::invariant_start: {
747       assert(ArgIdx == 1 && "Invalid argument index");
748       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
749              "Intrinsic location pointer not argument?");
750       Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
751       break;
752     }
753     case Intrinsic::invariant_end: {
754       assert(ArgIdx == 2 && "Invalid argument index");
755       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
756              "Intrinsic location pointer not argument?");
757       Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
758       break;
759     }
760     case Intrinsic::arm_neon_vld1: {
761       assert(ArgIdx == 0 && "Invalid argument index");
762       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
763              "Intrinsic location pointer not argument?");
764       // LLVM's vld1 and vst1 intrinsics currently only support a single
765       // vector register.
766       if (DL)
767         Loc.Size = DL->getTypeStoreSize(II->getType());
768       break;
769     }
770     case Intrinsic::arm_neon_vst1: {
771       assert(ArgIdx == 0 && "Invalid argument index");
772       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
773              "Intrinsic location pointer not argument?");
774       if (DL)
775         Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType());
776       break;
777     }
778     }
779
780   // We can bound the aliasing properties of memset_pattern16 just as we can
781   // for memcpy/memset.  This is particularly important because the
782   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
783   // whenever possible.
784   else if (CS.getCalledFunction() &&
785            isMemsetPattern16(CS.getCalledFunction(), TLI)) {
786     assert((ArgIdx == 0 || ArgIdx == 1) &&
787            "Invalid argument index for memset_pattern16");
788     if (ArgIdx == 1)
789       Loc.Size = 16;
790     else if (const ConstantInt *LenCI =
791              dyn_cast<ConstantInt>(CS.getArgument(2)))
792       Loc.Size = LenCI->getZExtValue();
793     assert(Loc.Ptr == CS.getArgument(ArgIdx) &&
794            "memset_pattern16 location pointer not argument?");
795     Mask = ArgIdx ? Ref : Mod;
796   }
797   // FIXME: Handle memset_pattern4 and memset_pattern8 also.
798
799   return Loc;
800 }
801
802 /// getModRefInfo - Check to see if the specified callsite can clobber the
803 /// specified memory object.  Since we only look at local properties of this
804 /// function, we really can't say much about this query.  We do, however, use
805 /// simple "address taken" analysis on local objects.
806 AliasAnalysis::ModRefResult
807 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
808                                   const Location &Loc) {
809   assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
810          "AliasAnalysis query involving multiple functions!");
811
812   const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
813
814   // If this is a tail call and Loc.Ptr points to a stack location, we know that
815   // the tail call cannot access or modify the local stack.
816   // We cannot exclude byval arguments here; these belong to the caller of
817   // the current function not to the current function, and a tail callee
818   // may reference them.
819   if (isa<AllocaInst>(Object))
820     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
821       if (CI->isTailCall())
822         return NoModRef;
823
824   // If the pointer is to a locally allocated object that does not escape,
825   // then the call can not mod/ref the pointer unless the call takes the pointer
826   // as an argument, and itself doesn't capture it.
827   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
828       isNonEscapingLocalObject(Object)) {
829     bool PassedAsArg = false;
830     unsigned ArgNo = 0;
831     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
832          CI != CE; ++CI, ++ArgNo) {
833       // Only look at the no-capture or byval pointer arguments.  If this
834       // pointer were passed to arguments that were neither of these, then it
835       // couldn't be no-capture.
836       if (!(*CI)->getType()->isPointerTy() ||
837           (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
838         continue;
839
840       // If this is a no-capture pointer argument, see if we can tell that it
841       // is impossible to alias the pointer we're checking.  If not, we have to
842       // assume that the call could touch the pointer, even though it doesn't
843       // escape.
844       if (!isNoAlias(Location(*CI), Location(Object))) {
845         PassedAsArg = true;
846         break;
847       }
848     }
849
850     if (!PassedAsArg)
851       return NoModRef;
852   }
853
854   // The AliasAnalysis base class has some smarts, lets use them.
855   return AliasAnalysis::getModRefInfo(CS, Loc);
856 }
857
858 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
859 /// against another pointer.  We know that V1 is a GEP, but we don't know
860 /// anything about V2.  UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
861 /// UnderlyingV2 is the same for V2.
862 ///
863 AliasAnalysis::AliasResult
864 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
865                              const MDNode *V1TBAAInfo,
866                              const Value *V2, uint64_t V2Size,
867                              const MDNode *V2TBAAInfo,
868                              const Value *UnderlyingV1,
869                              const Value *UnderlyingV2) {
870   int64_t GEP1BaseOffset;
871   bool GEP1MaxLookupReached;
872   SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
873
874   // If we have two gep instructions with must-alias or not-alias'ing base
875   // pointers, figure out if the indexes to the GEP tell us anything about the
876   // derived pointer.
877   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
878     // Do the base pointers alias?
879     AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
880                                        UnderlyingV2, UnknownSize, nullptr);
881
882     // Check for geps of non-aliasing underlying pointers where the offsets are
883     // identical.
884     if ((BaseAlias == MayAlias) && V1Size == V2Size) {
885       // Do the base pointers alias assuming type and size.
886       AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
887                                                 V1TBAAInfo, UnderlyingV2,
888                                                 V2Size, V2TBAAInfo);
889       if (PreciseBaseAlias == NoAlias) {
890         // See if the computed offset from the common pointer tells us about the
891         // relation of the resulting pointer.
892         int64_t GEP2BaseOffset;
893         bool GEP2MaxLookupReached;
894         SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
895         const Value *GEP2BasePtr =
896           DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
897                                  GEP2MaxLookupReached, DL);
898         const Value *GEP1BasePtr =
899           DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
900                                  GEP1MaxLookupReached, DL);
901         // DecomposeGEPExpression and GetUnderlyingObject should return the
902         // same result except when DecomposeGEPExpression has no DataLayout.
903         if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
904           assert(!DL &&
905                  "DecomposeGEPExpression and GetUnderlyingObject disagree!");
906           return MayAlias;
907         }
908         // If the max search depth is reached the result is undefined
909         if (GEP2MaxLookupReached || GEP1MaxLookupReached)
910           return MayAlias;
911
912         // Same offsets.
913         if (GEP1BaseOffset == GEP2BaseOffset &&
914             GEP1VariableIndices == GEP2VariableIndices)
915           return NoAlias;
916         GEP1VariableIndices.clear();
917       }
918     }
919
920     // If we get a No or May, then return it immediately, no amount of analysis
921     // will improve this situation.
922     if (BaseAlias != MustAlias) return BaseAlias;
923
924     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
925     // exactly, see if the computed offset from the common pointer tells us
926     // about the relation of the resulting pointer.
927     const Value *GEP1BasePtr =
928       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
929                              GEP1MaxLookupReached, DL);
930
931     int64_t GEP2BaseOffset;
932     bool GEP2MaxLookupReached;
933     SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
934     const Value *GEP2BasePtr =
935       DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
936                              GEP2MaxLookupReached, DL);
937
938     // DecomposeGEPExpression and GetUnderlyingObject should return the
939     // same result except when DecomposeGEPExpression has no DataLayout.
940     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
941       assert(!DL &&
942              "DecomposeGEPExpression and GetUnderlyingObject disagree!");
943       return MayAlias;
944     }
945     // If the max search depth is reached the result is undefined
946     if (GEP2MaxLookupReached || GEP1MaxLookupReached)
947       return MayAlias;
948
949     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
950     // symbolic difference.
951     GEP1BaseOffset -= GEP2BaseOffset;
952     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
953
954   } else {
955     // Check to see if these two pointers are related by the getelementptr
956     // instruction.  If one pointer is a GEP with a non-zero index of the other
957     // pointer, we know they cannot alias.
958
959     // If both accesses are unknown size, we can't do anything useful here.
960     if (V1Size == UnknownSize && V2Size == UnknownSize)
961       return MayAlias;
962
963     AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
964                                V2, V2Size, V2TBAAInfo);
965     if (R != MustAlias)
966       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
967       // If V2 is known not to alias GEP base pointer, then the two values
968       // cannot alias per GEP semantics: "A pointer value formed from a
969       // getelementptr instruction is associated with the addresses associated
970       // with the first operand of the getelementptr".
971       return R;
972
973     const Value *GEP1BasePtr =
974       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
975                              GEP1MaxLookupReached, DL);
976
977     // DecomposeGEPExpression and GetUnderlyingObject should return the
978     // same result except when DecomposeGEPExpression has no DataLayout.
979     if (GEP1BasePtr != UnderlyingV1) {
980       assert(!DL &&
981              "DecomposeGEPExpression and GetUnderlyingObject disagree!");
982       return MayAlias;
983     }
984     // If the max search depth is reached the result is undefined
985     if (GEP1MaxLookupReached)
986       return MayAlias;
987   }
988
989   // In the two GEP Case, if there is no difference in the offsets of the
990   // computed pointers, the resultant pointers are a must alias.  This
991   // hapens when we have two lexically identical GEP's (for example).
992   //
993   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
994   // must aliases the GEP, the end result is a must alias also.
995   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
996     return MustAlias;
997
998   // If there is a constant difference between the pointers, but the difference
999   // is less than the size of the associated memory object, then we know
1000   // that the objects are partially overlapping.  If the difference is
1001   // greater, we know they do not overlap.
1002   if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
1003     if (GEP1BaseOffset >= 0) {
1004       if (V2Size != UnknownSize) {
1005         if ((uint64_t)GEP1BaseOffset < V2Size)
1006           return PartialAlias;
1007         return NoAlias;
1008       }
1009     } else {
1010       // We have the situation where:
1011       // +                +
1012       // | BaseOffset     |
1013       // ---------------->|
1014       // |-->V1Size       |-------> V2Size
1015       // GEP1             V2
1016       // We need to know that V2Size is not unknown, otherwise we might have
1017       // stripped a gep with negative index ('gep <ptr>, -1, ...).
1018       if (V1Size != UnknownSize && V2Size != UnknownSize) {
1019         if (-(uint64_t)GEP1BaseOffset < V1Size)
1020           return PartialAlias;
1021         return NoAlias;
1022       }
1023     }
1024   }
1025
1026   // Try to distinguish something like &A[i][1] against &A[42][0].
1027   // Grab the least significant bit set in any of the scales.
1028   if (!GEP1VariableIndices.empty()) {
1029     uint64_t Modulo = 0;
1030     for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i)
1031       Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
1032     Modulo = Modulo ^ (Modulo & (Modulo - 1));
1033
1034     // We can compute the difference between the two addresses
1035     // mod Modulo. Check whether that difference guarantees that the
1036     // two locations do not alias.
1037     uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1038     if (V1Size != UnknownSize && V2Size != UnknownSize &&
1039         ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1040       return NoAlias;
1041   }
1042
1043   // Statically, we can see that the base objects are the same, but the
1044   // pointers have dynamic offsets which we can't resolve. And none of our
1045   // little tricks above worked.
1046   //
1047   // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1048   // practical effect of this is protecting TBAA in the case of dynamic
1049   // indices into arrays of unions or malloc'd memory.
1050   return PartialAlias;
1051 }
1052
1053 static AliasAnalysis::AliasResult
1054 MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1055   // If the results agree, take it.
1056   if (A == B)
1057     return A;
1058   // A mix of PartialAlias and MustAlias is PartialAlias.
1059   if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1060       (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1061     return AliasAnalysis::PartialAlias;
1062   // Otherwise, we don't know anything.
1063   return AliasAnalysis::MayAlias;
1064 }
1065
1066 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1067 /// instruction against another.
1068 AliasAnalysis::AliasResult
1069 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
1070                                 const MDNode *SITBAAInfo,
1071                                 const Value *V2, uint64_t V2Size,
1072                                 const MDNode *V2TBAAInfo) {
1073   // If the values are Selects with the same condition, we can do a more precise
1074   // check: just check for aliases between the values on corresponding arms.
1075   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1076     if (SI->getCondition() == SI2->getCondition()) {
1077       AliasResult Alias =
1078         aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
1079                    SI2->getTrueValue(), V2Size, V2TBAAInfo);
1080       if (Alias == MayAlias)
1081         return MayAlias;
1082       AliasResult ThisAlias =
1083         aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
1084                    SI2->getFalseValue(), V2Size, V2TBAAInfo);
1085       return MergeAliasResults(ThisAlias, Alias);
1086     }
1087
1088   // If both arms of the Select node NoAlias or MustAlias V2, then returns
1089   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1090   AliasResult Alias =
1091     aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
1092   if (Alias == MayAlias)
1093     return MayAlias;
1094
1095   AliasResult ThisAlias =
1096     aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
1097   return MergeAliasResults(ThisAlias, Alias);
1098 }
1099
1100 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
1101 // against another.
1102 AliasAnalysis::AliasResult
1103 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1104                              const MDNode *PNTBAAInfo,
1105                              const Value *V2, uint64_t V2Size,
1106                              const MDNode *V2TBAAInfo) {
1107   // Track phi nodes we have visited. We use this information when we determine
1108   // value equivalence.
1109   VisitedPhiBBs.insert(PN->getParent());
1110
1111   // If the values are PHIs in the same block, we can do a more precise
1112   // as well as efficient check: just check for aliases between the values
1113   // on corresponding edges.
1114   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1115     if (PN2->getParent() == PN->getParent()) {
1116       LocPair Locs(Location(PN, PNSize, PNTBAAInfo),
1117                    Location(V2, V2Size, V2TBAAInfo));
1118       if (PN > V2)
1119         std::swap(Locs.first, Locs.second);
1120       // Analyse the PHIs' inputs under the assumption that the PHIs are
1121       // NoAlias.
1122       // If the PHIs are May/MustAlias there must be (recursively) an input
1123       // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1124       // there must be an operation on the PHIs within the PHIs' value cycle
1125       // that causes a MayAlias.
1126       // Pretend the phis do not alias.
1127       AliasResult Alias = NoAlias;
1128       assert(AliasCache.count(Locs) &&
1129              "There must exist an entry for the phi node");
1130       AliasResult OrigAliasResult = AliasCache[Locs];
1131       AliasCache[Locs] = NoAlias;
1132
1133       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1134         AliasResult ThisAlias =
1135           aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
1136                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1137                      V2Size, V2TBAAInfo);
1138         Alias = MergeAliasResults(ThisAlias, Alias);
1139         if (Alias == MayAlias)
1140           break;
1141       }
1142
1143       // Reset if speculation failed.
1144       if (Alias != NoAlias)
1145         AliasCache[Locs] = OrigAliasResult;
1146
1147       return Alias;
1148     }
1149
1150   SmallPtrSet<Value*, 4> UniqueSrc;
1151   SmallVector<Value*, 4> V1Srcs;
1152   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1153     Value *PV1 = PN->getIncomingValue(i);
1154     if (isa<PHINode>(PV1))
1155       // If any of the source itself is a PHI, return MayAlias conservatively
1156       // to avoid compile time explosion. The worst possible case is if both
1157       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1158       // and 'n' are the number of PHI sources.
1159       return MayAlias;
1160     if (UniqueSrc.insert(PV1))
1161       V1Srcs.push_back(PV1);
1162   }
1163
1164   AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
1165                                  V1Srcs[0], PNSize, PNTBAAInfo);
1166   // Early exit if the check of the first PHI source against V2 is MayAlias.
1167   // Other results are not possible.
1168   if (Alias == MayAlias)
1169     return MayAlias;
1170
1171   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1172   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1173   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1174     Value *V = V1Srcs[i];
1175
1176     AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
1177                                        V, PNSize, PNTBAAInfo);
1178     Alias = MergeAliasResults(ThisAlias, Alias);
1179     if (Alias == MayAlias)
1180       break;
1181   }
1182
1183   return Alias;
1184 }
1185
1186 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1187 // such as array references.
1188 //
1189 AliasAnalysis::AliasResult
1190 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1191                                const MDNode *V1TBAAInfo,
1192                                const Value *V2, uint64_t V2Size,
1193                                const MDNode *V2TBAAInfo) {
1194   // If either of the memory references is empty, it doesn't matter what the
1195   // pointer values are.
1196   if (V1Size == 0 || V2Size == 0)
1197     return NoAlias;
1198
1199   // Strip off any casts if they exist.
1200   V1 = V1->stripPointerCasts();
1201   V2 = V2->stripPointerCasts();
1202
1203   // Are we checking for alias of the same value?
1204   // Because we look 'through' phi nodes we could look at "Value" pointers from
1205   // different iterations. We must therefore make sure that this is not the
1206   // case. The function isValueEqualInPotentialCycles ensures that this cannot
1207   // happen by looking at the visited phi nodes and making sure they cannot
1208   // reach the value.
1209   if (isValueEqualInPotentialCycles(V1, V2))
1210     return MustAlias;
1211
1212   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1213     return NoAlias;  // Scalars cannot alias each other
1214
1215   // Figure out what objects these things are pointing to if we can.
1216   const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1217   const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
1218
1219   // Null values in the default address space don't point to any object, so they
1220   // don't alias any other pointer.
1221   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1222     if (CPN->getType()->getAddressSpace() == 0)
1223       return NoAlias;
1224   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1225     if (CPN->getType()->getAddressSpace() == 0)
1226       return NoAlias;
1227
1228   if (O1 != O2) {
1229     // If V1/V2 point to two different objects we know that we have no alias.
1230     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1231       return NoAlias;
1232
1233     // Constant pointers can't alias with non-const isIdentifiedObject objects.
1234     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1235         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1236       return NoAlias;
1237
1238     // Function arguments can't alias with things that are known to be
1239     // unambigously identified at the function level.
1240     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1241         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1242       return NoAlias;
1243
1244     // Most objects can't alias null.
1245     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1246         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1247       return NoAlias;
1248
1249     // If one pointer is the result of a call/invoke or load and the other is a
1250     // non-escaping local object within the same function, then we know the
1251     // object couldn't escape to a point where the call could return it.
1252     //
1253     // Note that if the pointers are in different functions, there are a
1254     // variety of complications. A call with a nocapture argument may still
1255     // temporary store the nocapture argument's value in a temporary memory
1256     // location if that memory location doesn't escape. Or it may pass a
1257     // nocapture value to other functions as long as they don't capture it.
1258     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1259       return NoAlias;
1260     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1261       return NoAlias;
1262   }
1263
1264   // If the size of one access is larger than the entire object on the other
1265   // side, then we know such behavior is undefined and can assume no alias.
1266   if (DL)
1267     if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1268         (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1269       return NoAlias;
1270
1271   // Check the cache before climbing up use-def chains. This also terminates
1272   // otherwise infinitely recursive queries.
1273   LocPair Locs(Location(V1, V1Size, V1TBAAInfo),
1274                Location(V2, V2Size, V2TBAAInfo));
1275   if (V1 > V2)
1276     std::swap(Locs.first, Locs.second);
1277   std::pair<AliasCacheTy::iterator, bool> Pair =
1278     AliasCache.insert(std::make_pair(Locs, MayAlias));
1279   if (!Pair.second)
1280     return Pair.first->second;
1281
1282   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1283   // GEP can't simplify, we don't even look at the PHI cases.
1284   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1285     std::swap(V1, V2);
1286     std::swap(V1Size, V2Size);
1287     std::swap(O1, O2);
1288     std::swap(V1TBAAInfo, V2TBAAInfo);
1289   }
1290   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1291     AliasResult Result = aliasGEP(GV1, V1Size, V1TBAAInfo, V2, V2Size, V2TBAAInfo, O1, O2);
1292     if (Result != MayAlias) return AliasCache[Locs] = Result;
1293   }
1294
1295   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1296     std::swap(V1, V2);
1297     std::swap(V1Size, V2Size);
1298     std::swap(V1TBAAInfo, V2TBAAInfo);
1299   }
1300   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1301     AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1302                                   V2, V2Size, V2TBAAInfo);
1303     if (Result != MayAlias) return AliasCache[Locs] = Result;
1304   }
1305
1306   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1307     std::swap(V1, V2);
1308     std::swap(V1Size, V2Size);
1309     std::swap(V1TBAAInfo, V2TBAAInfo);
1310   }
1311   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1312     AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1313                                      V2, V2Size, V2TBAAInfo);
1314     if (Result != MayAlias) return AliasCache[Locs] = Result;
1315   }
1316
1317   // If both pointers are pointing into the same object and one of them
1318   // accesses is accessing the entire object, then the accesses must
1319   // overlap in some way.
1320   if (DL && O1 == O2)
1321     if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1322         (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
1323       return AliasCache[Locs] = PartialAlias;
1324
1325   AliasResult Result =
1326     AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1327                          Location(V2, V2Size, V2TBAAInfo));
1328   return AliasCache[Locs] = Result;
1329 }
1330
1331 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1332                                                        const Value *V2) {
1333   if (V != V2)
1334     return false;
1335
1336   const Instruction *Inst = dyn_cast<Instruction>(V);
1337   if (!Inst)
1338     return true;
1339
1340   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1341     return false;
1342
1343   // Use dominance or loop info if available.
1344   DominatorTreeWrapperPass *DTWP =
1345       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1346   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1347   LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
1348
1349   // Make sure that the visited phis cannot reach the Value. This ensures that
1350   // the Values cannot come from different iterations of a potential cycle the
1351   // phi nodes could be involved in.
1352   for (SmallPtrSet<const BasicBlock *, 8>::iterator PI = VisitedPhiBBs.begin(),
1353                                                     PE = VisitedPhiBBs.end();
1354        PI != PE; ++PI)
1355     if (isPotentiallyReachable((*PI)->begin(), Inst, DT, LI))
1356       return false;
1357
1358   return true;
1359 }
1360
1361 /// GetIndexDifference - Dest and Src are the variable indices from two
1362 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1363 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
1364 /// difference between the two pointers.
1365 void BasicAliasAnalysis::GetIndexDifference(
1366     SmallVectorImpl<VariableGEPIndex> &Dest,
1367     const SmallVectorImpl<VariableGEPIndex> &Src) {
1368   if (Src.empty())
1369     return;
1370
1371   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1372     const Value *V = Src[i].V;
1373     ExtensionKind Extension = Src[i].Extension;
1374     int64_t Scale = Src[i].Scale;
1375
1376     // Find V in Dest.  This is N^2, but pointer indices almost never have more
1377     // than a few variable indexes.
1378     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1379       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1380           Dest[j].Extension != Extension)
1381         continue;
1382
1383       // If we found it, subtract off Scale V's from the entry in Dest.  If it
1384       // goes to zero, remove the entry.
1385       if (Dest[j].Scale != Scale)
1386         Dest[j].Scale -= Scale;
1387       else
1388         Dest.erase(Dest.begin() + j);
1389       Scale = 0;
1390       break;
1391     }
1392
1393     // If we didn't consume this entry, add it to the end of the Dest list.
1394     if (Scale) {
1395       VariableGEPIndex Entry = { V, Extension, -Scale };
1396       Dest.push_back(Entry);
1397     }
1398   }
1399 }