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