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