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