Re-introduce the MaxLookup limit to BasicAliasAnalysis'
[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/AliasAnalysis.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalAlias.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/Analysis/MemoryBuiltins.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 //===----------------------------------------------------------------------===//
40 // Useful predicates
41 //===----------------------------------------------------------------------===//
42
43 /// isKnownNonNull - Return true if we know that the specified value is never
44 /// null.
45 static bool isKnownNonNull(const Value *V) {
46   // Alloca never returns null, malloc might.
47   if (isa<AllocaInst>(V)) return true;
48   
49   // A byval argument is never null.
50   if (const Argument *A = dyn_cast<Argument>(V))
51     return A->hasByValAttr();
52
53   // Global values are not null unless extern weak.
54   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
55     return !GV->hasExternalWeakLinkage();
56   return false;
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       // Don't bother analyzing arguments already known not to escape.
77       if (A->hasNoCaptureAttr())
78         return true;
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 /// isObjectSmallerThan - Return true if we can prove that the object specified
100 /// by V is smaller than Size.
101 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
102                                 const TargetData &TD) {
103   const Type *AccessTy;
104   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
105     AccessTy = GV->getType()->getElementType();
106   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
107     if (!AI->isArrayAllocation())
108       AccessTy = AI->getType()->getElementType();
109     else
110       return false;
111   } else if (const CallInst* CI = extractMallocCall(V)) {
112     if (!isArrayMalloc(V, &TD))
113       // The size is the argument to the malloc call.
114       if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getArgOperand(0)))
115         return (C->getZExtValue() < Size);
116     return false;
117   } else if (const Argument *A = dyn_cast<Argument>(V)) {
118     if (A->hasByValAttr())
119       AccessTy = cast<PointerType>(A->getType())->getElementType();
120     else
121       return false;
122   } else {
123     return false;
124   }
125   
126   if (AccessTy->isSized())
127     return TD.getTypeAllocSize(AccessTy) < Size;
128   return false;
129 }
130
131 //===----------------------------------------------------------------------===//
132 // GetElementPtr Instruction Decomposition and Analysis
133 //===----------------------------------------------------------------------===//
134
135 namespace {
136   enum ExtensionKind {
137     EK_NotExtended,
138     EK_SignExt,
139     EK_ZeroExt
140   };
141   
142   struct VariableGEPIndex {
143     const Value *V;
144     ExtensionKind Extension;
145     int64_t Scale;
146   };
147 }
148
149
150 /// GetLinearExpression - Analyze the specified value as a linear expression:
151 /// "A*V + B", where A and B are constant integers.  Return the scale and offset
152 /// values as APInts and return V as a Value*, and return whether we looked
153 /// through any sign or zero extends.  The incoming Value is known to have
154 /// IntegerType and it may already be sign or zero extended.
155 ///
156 /// Note that this looks through extends, so the high bits may not be
157 /// represented in the result.
158 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
159                                   ExtensionKind &Extension,
160                                   const TargetData &TD, unsigned Depth) {
161   assert(V->getType()->isIntegerTy() && "Not an integer value");
162
163   // Limit our recursion depth.
164   if (Depth == 6) {
165     Scale = 1;
166     Offset = 0;
167     return V;
168   }
169   
170   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
171     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
172       switch (BOp->getOpcode()) {
173       default: break;
174       case Instruction::Or:
175         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
176         // analyze it.
177         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &TD))
178           break;
179         // FALL THROUGH.
180       case Instruction::Add:
181         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
182                                 TD, Depth+1);
183         Offset += RHSC->getValue();
184         return V;
185       case Instruction::Mul:
186         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
187                                 TD, Depth+1);
188         Offset *= RHSC->getValue();
189         Scale *= RHSC->getValue();
190         return V;
191       case Instruction::Shl:
192         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
193                                 TD, Depth+1);
194         Offset <<= RHSC->getValue().getLimitedValue();
195         Scale <<= RHSC->getValue().getLimitedValue();
196         return V;
197       }
198     }
199   }
200   
201   // Since GEP indices are sign extended anyway, we don't care about the high
202   // bits of a sign or zero extended value - just scales and offsets.  The
203   // extensions have to be consistent though.
204   if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
205       (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
206     Value *CastOp = cast<CastInst>(V)->getOperand(0);
207     unsigned OldWidth = Scale.getBitWidth();
208     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
209     Scale.trunc(SmallWidth);
210     Offset.trunc(SmallWidth);
211     Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
212
213     Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
214                                         TD, Depth+1);
215     Scale.zext(OldWidth);
216     Offset.zext(OldWidth);
217     
218     return Result;
219   }
220   
221   Scale = 1;
222   Offset = 0;
223   return V;
224 }
225
226 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
227 /// into a base pointer with a constant offset and a number of scaled symbolic
228 /// offsets.
229 ///
230 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
231 /// the VarIndices vector) are Value*'s that are known to be scaled by the
232 /// specified amount, but which may have other unrepresented high bits. As such,
233 /// the gep cannot necessarily be reconstructed from its decomposed form.
234 ///
235 /// When TargetData is around, this function is capable of analyzing everything
236 /// that Value::getUnderlyingObject() can look through.  When not, it just looks
237 /// through pointer casts.
238 ///
239 static const Value *
240 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
241                        SmallVectorImpl<VariableGEPIndex> &VarIndices,
242                        const TargetData *TD) {
243   // Limit recursion depth to limit compile time in crazy cases.
244   unsigned MaxLookup = 6;
245   
246   BaseOffs = 0;
247   do {
248     // See if this is a bitcast or GEP.
249     const Operator *Op = dyn_cast<Operator>(V);
250     if (Op == 0) {
251       // The only non-operator case we can handle are GlobalAliases.
252       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
253         if (!GA->mayBeOverridden()) {
254           V = GA->getAliasee();
255           continue;
256         }
257       }
258       return V;
259     }
260     
261     if (Op->getOpcode() == Instruction::BitCast) {
262       V = Op->getOperand(0);
263       continue;
264     }
265     
266     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
267     if (GEPOp == 0)
268       return V;
269     
270     // Don't attempt to analyze GEPs over unsized objects.
271     if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
272         ->getElementType()->isSized())
273       return V;
274     
275     // If we are lacking TargetData information, we can't compute the offets of
276     // elements computed by GEPs.  However, we can handle bitcast equivalent
277     // GEPs.
278     if (TD == 0) {
279       if (!GEPOp->hasAllZeroIndices())
280         return V;
281       V = GEPOp->getOperand(0);
282       continue;
283     }
284     
285     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
286     gep_type_iterator GTI = gep_type_begin(GEPOp);
287     for (User::const_op_iterator I = GEPOp->op_begin()+1,
288          E = GEPOp->op_end(); I != E; ++I) {
289       Value *Index = *I;
290       // Compute the (potentially symbolic) offset in bytes for this index.
291       if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
292         // For a struct, add the member offset.
293         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
294         if (FieldNo == 0) continue;
295         
296         BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
297         continue;
298       }
299       
300       // For an array/pointer, add the element offset, explicitly scaled.
301       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
302         if (CIdx->isZero()) continue;
303         BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
304         continue;
305       }
306       
307       uint64_t Scale = TD->getTypeAllocSize(*GTI);
308       ExtensionKind Extension = EK_NotExtended;
309       
310       // If the integer type is smaller than the pointer size, it is implicitly
311       // sign extended to pointer size.
312       unsigned Width = cast<IntegerType>(Index->getType())->getBitWidth();
313       if (TD->getPointerSizeInBits() > Width)
314         Extension = EK_SignExt;
315       
316       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
317       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
318       Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
319                                   *TD, 0);
320       
321       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
322       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
323       BaseOffs += IndexOffset.getSExtValue()*Scale;
324       Scale *= IndexScale.getSExtValue();
325       
326       
327       // If we already had an occurrance of this index variable, merge this
328       // scale into it.  For example, we want to handle:
329       //   A[x][x] -> x*16 + x*4 -> x*20
330       // This also ensures that 'x' only appears in the index list once.
331       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
332         if (VarIndices[i].V == Index &&
333             VarIndices[i].Extension == Extension) {
334           Scale += VarIndices[i].Scale;
335           VarIndices.erase(VarIndices.begin()+i);
336           break;
337         }
338       }
339       
340       // Make sure that we have a scale that makes sense for this target's
341       // pointer size.
342       if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
343         Scale <<= ShiftBits;
344         Scale = (int64_t)Scale >> ShiftBits;
345       }
346       
347       if (Scale) {
348         VariableGEPIndex Entry = {Index, Extension, Scale};
349         VarIndices.push_back(Entry);
350       }
351     }
352     
353     // Analyze the base pointer next.
354     V = GEPOp->getOperand(0);
355   } while (--MaxLookup);
356   
357   // If the chain of expressions is too deep, just return early.
358   return V;
359 }
360
361 /// GetIndexDifference - Dest and Src are the variable indices from two
362 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
363 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
364 /// difference between the two pointers. 
365 static void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
366                                const SmallVectorImpl<VariableGEPIndex> &Src) {
367   if (Src.empty()) return;
368
369   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
370     const Value *V = Src[i].V;
371     ExtensionKind Extension = Src[i].Extension;
372     int64_t Scale = Src[i].Scale;
373     
374     // Find V in Dest.  This is N^2, but pointer indices almost never have more
375     // than a few variable indexes.
376     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
377       if (Dest[j].V != V || Dest[j].Extension != Extension) continue;
378       
379       // If we found it, subtract off Scale V's from the entry in Dest.  If it
380       // goes to zero, remove the entry.
381       if (Dest[j].Scale != Scale)
382         Dest[j].Scale -= Scale;
383       else
384         Dest.erase(Dest.begin()+j);
385       Scale = 0;
386       break;
387     }
388     
389     // If we didn't consume this entry, add it to the end of the Dest list.
390     if (Scale) {
391       VariableGEPIndex Entry = { V, Extension, -Scale };
392       Dest.push_back(Entry);
393     }
394   }
395 }
396
397 //===----------------------------------------------------------------------===//
398 // BasicAliasAnalysis Pass
399 //===----------------------------------------------------------------------===//
400
401 #ifndef NDEBUG
402 static const Function *getParent(const Value *V) {
403   if (const Instruction *inst = dyn_cast<Instruction>(V))
404     return inst->getParent()->getParent();
405
406   if (const Argument *arg = dyn_cast<Argument>(V))
407     return arg->getParent();
408
409   return NULL;
410 }
411
412 static bool notDifferentParent(const Value *O1, const Value *O2) {
413
414   const Function *F1 = getParent(O1);
415   const Function *F2 = getParent(O2);
416
417   return !F1 || !F2 || F1 == F2;
418 }
419 #endif
420
421 namespace {
422   /// BasicAliasAnalysis - This is the primary alias analysis implementation.
423   struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
424     static char ID; // Class identification, replacement for typeinfo
425     BasicAliasAnalysis() : ImmutablePass(ID) {
426       initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
427     }
428
429     virtual void initializePass() {
430       InitializeAliasAnalysis(this);
431     }
432
433     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
434       AU.addRequired<AliasAnalysis>();
435     }
436
437     virtual AliasResult alias(const Location &LocA,
438                               const Location &LocB) {
439       assert(Visited.empty() && "Visited must be cleared after use!");
440       assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
441              "BasicAliasAnalysis doesn't support interprocedural queries.");
442       AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.TBAATag,
443                                      LocB.Ptr, LocB.Size, LocB.TBAATag);
444       Visited.clear();
445       return Alias;
446     }
447
448     virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
449                                        const Location &Loc);
450
451     virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
452                                        ImmutableCallSite CS2) {
453       // The AliasAnalysis base class has some smarts, lets use them.
454       return AliasAnalysis::getModRefInfo(CS1, CS2);
455     }
456
457     /// pointsToConstantMemory - Chase pointers until we find a (constant
458     /// global) or not.
459     virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
460
461     /// getModRefBehavior - Return the behavior when calling the given
462     /// call site.
463     virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
464
465     /// getModRefBehavior - Return the behavior when calling the given function.
466     /// For use when the call site is not known.
467     virtual ModRefBehavior getModRefBehavior(const Function *F);
468
469     /// getAdjustedAnalysisPointer - This method is used when a pass implements
470     /// an analysis interface through multiple inheritance.  If needed, it
471     /// should override this to adjust the this pointer as needed for the
472     /// specified pass info.
473     virtual void *getAdjustedAnalysisPointer(const void *ID) {
474       if (ID == &AliasAnalysis::ID)
475         return (AliasAnalysis*)this;
476       return this;
477     }
478     
479   private:
480     // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
481     SmallPtrSet<const Value*, 16> Visited;
482
483     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
484     // instruction against another.
485     AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
486                          const Value *V2, uint64_t V2Size,
487                          const MDNode *V2TBAAInfo,
488                          const Value *UnderlyingV1, const Value *UnderlyingV2);
489
490     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
491     // instruction against another.
492     AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
493                          const MDNode *PNTBAAInfo,
494                          const Value *V2, uint64_t V2Size,
495                          const MDNode *V2TBAAInfo);
496
497     /// aliasSelect - Disambiguate a Select instruction against another value.
498     AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
499                             const MDNode *SITBAAInfo,
500                             const Value *V2, uint64_t V2Size,
501                             const MDNode *V2TBAAInfo);
502
503     AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
504                            const MDNode *V1TBAATag,
505                            const Value *V2, uint64_t V2Size,
506                            const MDNode *V2TBAATag);
507   };
508 }  // End of anonymous namespace
509
510 // Register this pass...
511 char BasicAliasAnalysis::ID = 0;
512 INITIALIZE_AG_PASS(BasicAliasAnalysis, AliasAnalysis, "basicaa",
513                    "Basic Alias Analysis (stateless AA impl)",
514                    false, true, false)
515
516 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
517   return new BasicAliasAnalysis();
518 }
519
520 /// pointsToConstantMemory - Returns whether the given pointer value
521 /// points to memory that is local to the function, with global constants being
522 /// considered local to all functions.
523 bool
524 BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
525   assert(Visited.empty() && "Visited must be cleared after use!");
526
527   unsigned MaxLookup = 8;
528   SmallVector<const Value *, 16> Worklist;
529   Worklist.push_back(Loc.Ptr);
530   do {
531     const Value *V = Worklist.pop_back_val()->getUnderlyingObject();
532     if (!Visited.insert(V)) {
533       Visited.clear();
534       return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
535     }
536
537     // An alloca instruction defines local memory.
538     if (OrLocal && isa<AllocaInst>(V))
539       continue;
540
541     // A global constant counts as local memory for our purposes.
542     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
543       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
544       // global to be marked constant in some modules and non-constant in
545       // others.  GV may even be a declaration, not a definition.
546       if (!GV->isConstant()) {
547         Visited.clear();
548         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
549       }
550       continue;
551     }
552
553     // If both select values point to local memory, then so does the select.
554     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
555       Worklist.push_back(SI->getTrueValue());
556       Worklist.push_back(SI->getFalseValue());
557       continue;
558     }
559
560     // If all values incoming to a phi node point to local memory, then so does
561     // the phi.
562     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
563       // Don't bother inspecting phi nodes with many operands.
564       if (PN->getNumIncomingValues() > MaxLookup) {
565         Visited.clear();
566         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
567       }
568       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
569         Worklist.push_back(PN->getIncomingValue(i));
570       continue;
571     }
572
573     // Otherwise be conservative.
574     Visited.clear();
575     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
576
577   } while (!Worklist.empty() && --MaxLookup);
578
579   Visited.clear();
580   return Worklist.empty();
581 }
582
583 /// getModRefBehavior - Return the behavior when calling the given call site.
584 AliasAnalysis::ModRefBehavior
585 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
586   if (CS.doesNotAccessMemory())
587     // Can't do better than this.
588     return DoesNotAccessMemory;
589
590   ModRefBehavior Min = UnknownModRefBehavior;
591
592   // If the callsite knows it only reads memory, don't return worse
593   // than that.
594   if (CS.onlyReadsMemory())
595     Min = OnlyReadsMemory;
596
597   // The AliasAnalysis base class has some smarts, lets use them.
598   return std::min(AliasAnalysis::getModRefBehavior(CS), Min);
599 }
600
601 /// getModRefBehavior - Return the behavior when calling the given function.
602 /// For use when the call site is not known.
603 AliasAnalysis::ModRefBehavior
604 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
605   // If the function declares it doesn't access memory, we can't do better.
606   if (F->doesNotAccessMemory())
607     return DoesNotAccessMemory;
608
609   // For intrinsics, we can check the table.
610   if (unsigned iid = F->getIntrinsicID()) {
611 #define GET_INTRINSIC_MODREF_BEHAVIOR
612 #include "llvm/Intrinsics.gen"
613 #undef GET_INTRINSIC_MODREF_BEHAVIOR
614   }
615
616   // If the function declares it only reads memory, go with that.
617   if (F->onlyReadsMemory())
618     return OnlyReadsMemory;
619
620   // Otherwise be conservative.
621   return AliasAnalysis::getModRefBehavior(F);
622 }
623
624 /// getModRefInfo - Check to see if the specified callsite can clobber the
625 /// specified memory object.  Since we only look at local properties of this
626 /// function, we really can't say much about this query.  We do, however, use
627 /// simple "address taken" analysis on local objects.
628 AliasAnalysis::ModRefResult
629 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
630                                   const Location &Loc) {
631   assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
632          "AliasAnalysis query involving multiple functions!");
633
634   const Value *Object = Loc.Ptr->getUnderlyingObject();
635   
636   // If this is a tail call and Loc.Ptr points to a stack location, we know that
637   // the tail call cannot access or modify the local stack.
638   // We cannot exclude byval arguments here; these belong to the caller of
639   // the current function not to the current function, and a tail callee
640   // may reference them.
641   if (isa<AllocaInst>(Object))
642     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
643       if (CI->isTailCall())
644         return NoModRef;
645   
646   // If the pointer is to a locally allocated object that does not escape,
647   // then the call can not mod/ref the pointer unless the call takes the pointer
648   // as an argument, and itself doesn't capture it.
649   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
650       isNonEscapingLocalObject(Object)) {
651     bool PassedAsArg = false;
652     unsigned ArgNo = 0;
653     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
654          CI != CE; ++CI, ++ArgNo) {
655       // Only look at the no-capture pointer arguments.
656       if (!(*CI)->getType()->isPointerTy() ||
657           !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
658         continue;
659       
660       // If this is a no-capture pointer argument, see if we can tell that it
661       // is impossible to alias the pointer we're checking.  If not, we have to
662       // assume that the call could touch the pointer, even though it doesn't
663       // escape.
664       if (!isNoAlias(Location(cast<Value>(CI)), Loc)) {
665         PassedAsArg = true;
666         break;
667       }
668     }
669     
670     if (!PassedAsArg)
671       return NoModRef;
672   }
673
674   // Finally, handle specific knowledge of intrinsics.
675   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
676   if (II != 0)
677     switch (II->getIntrinsicID()) {
678     default: break;
679     case Intrinsic::memcpy:
680     case Intrinsic::memmove: {
681       uint64_t Len = UnknownSize;
682       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
683         Len = LenCI->getZExtValue();
684       Value *Dest = II->getArgOperand(0);
685       Value *Src = II->getArgOperand(1);
686       if (isNoAlias(Location(Dest, Len), Loc)) {
687         if (isNoAlias(Location(Src, Len), Loc))
688           return NoModRef;
689         return Ref;
690       }
691       break;
692     }
693     case Intrinsic::memset:
694       // Since memset is 'accesses arguments' only, the AliasAnalysis base class
695       // will handle it for the variable length case.
696       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
697         uint64_t Len = LenCI->getZExtValue();
698         Value *Dest = II->getArgOperand(0);
699         if (isNoAlias(Location(Dest, Len), Loc))
700           return NoModRef;
701       }
702       break;
703     case Intrinsic::atomic_cmp_swap:
704     case Intrinsic::atomic_swap:
705     case Intrinsic::atomic_load_add:
706     case Intrinsic::atomic_load_sub:
707     case Intrinsic::atomic_load_and:
708     case Intrinsic::atomic_load_nand:
709     case Intrinsic::atomic_load_or:
710     case Intrinsic::atomic_load_xor:
711     case Intrinsic::atomic_load_max:
712     case Intrinsic::atomic_load_min:
713     case Intrinsic::atomic_load_umax:
714     case Intrinsic::atomic_load_umin:
715       if (TD) {
716         Value *Op1 = II->getArgOperand(0);
717         uint64_t Op1Size = TD->getTypeStoreSize(Op1->getType());
718         MDNode *Tag = II->getMetadata(LLVMContext::MD_tbaa);
719         if (isNoAlias(Location(Op1, Op1Size, Tag), Loc))
720           return NoModRef;
721       }
722       break;
723     case Intrinsic::lifetime_start:
724     case Intrinsic::lifetime_end:
725     case Intrinsic::invariant_start: {
726       uint64_t PtrSize =
727         cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
728       if (isNoAlias(Location(II->getArgOperand(1),
729                              PtrSize,
730                              II->getMetadata(LLVMContext::MD_tbaa)),
731                     Loc))
732         return NoModRef;
733       break;
734     }
735     case Intrinsic::invariant_end: {
736       uint64_t PtrSize =
737         cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
738       if (isNoAlias(Location(II->getArgOperand(2),
739                              PtrSize,
740                              II->getMetadata(LLVMContext::MD_tbaa)),
741                     Loc))
742         return NoModRef;
743       break;
744     }
745     }
746
747   // The AliasAnalysis base class has some smarts, lets use them.
748   return AliasAnalysis::getModRefInfo(CS, Loc);
749 }
750
751 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
752 /// against another pointer.  We know that V1 is a GEP, but we don't know
753 /// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
754 /// UnderlyingV2 is the same for V2.
755 ///
756 AliasAnalysis::AliasResult
757 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
758                              const Value *V2, uint64_t V2Size,
759                              const MDNode *V2TBAAInfo,
760                              const Value *UnderlyingV1,
761                              const Value *UnderlyingV2) {
762   // If this GEP has been visited before, we're on a use-def cycle.
763   // Such cycles are only valid when PHI nodes are involved or in unreachable
764   // code. The visitPHI function catches cycles containing PHIs, but there
765   // could still be a cycle without PHIs in unreachable code.
766   if (!Visited.insert(GEP1))
767     return MayAlias;
768
769   int64_t GEP1BaseOffset;
770   SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
771
772   // If we have two gep instructions with must-alias'ing base pointers, figure
773   // out if the indexes to the GEP tell us anything about the derived pointer.
774   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
775     // Do the base pointers alias?
776     AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, 0,
777                                        UnderlyingV2, UnknownSize, 0);
778     
779     // If we get a No or May, then return it immediately, no amount of analysis
780     // will improve this situation.
781     if (BaseAlias != MustAlias) return BaseAlias;
782     
783     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
784     // exactly, see if the computed offset from the common pointer tells us
785     // about the relation of the resulting pointer.
786     const Value *GEP1BasePtr =
787       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
788     
789     int64_t GEP2BaseOffset;
790     SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
791     const Value *GEP2BasePtr =
792       DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
793     
794     // If DecomposeGEPExpression isn't able to look all the way through the
795     // addressing operation, we must not have TD and this is too complex for us
796     // to handle without it.
797     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
798       assert(TD == 0 &&
799              "DecomposeGEPExpression and getUnderlyingObject disagree!");
800       return MayAlias;
801     }
802     
803     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
804     // symbolic difference.
805     GEP1BaseOffset -= GEP2BaseOffset;
806     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
807     
808   } else {
809     // Check to see if these two pointers are related by the getelementptr
810     // instruction.  If one pointer is a GEP with a non-zero index of the other
811     // pointer, we know they cannot alias.
812
813     // If both accesses are unknown size, we can't do anything useful here.
814     if (V1Size == UnknownSize && V2Size == UnknownSize)
815       return MayAlias;
816
817     AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, 0,
818                                V2, V2Size, V2TBAAInfo);
819     if (R != MustAlias)
820       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
821       // If V2 is known not to alias GEP base pointer, then the two values
822       // cannot alias per GEP semantics: "A pointer value formed from a
823       // getelementptr instruction is associated with the addresses associated
824       // with the first operand of the getelementptr".
825       return R;
826
827     const Value *GEP1BasePtr =
828       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
829     
830     // If DecomposeGEPExpression isn't able to look all the way through the
831     // addressing operation, we must not have TD and this is too complex for us
832     // to handle without it.
833     if (GEP1BasePtr != UnderlyingV1) {
834       assert(TD == 0 &&
835              "DecomposeGEPExpression and getUnderlyingObject disagree!");
836       return MayAlias;
837     }
838   }
839   
840   // In the two GEP Case, if there is no difference in the offsets of the
841   // computed pointers, the resultant pointers are a must alias.  This
842   // hapens when we have two lexically identical GEP's (for example).
843   //
844   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
845   // must aliases the GEP, the end result is a must alias also.
846   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
847     return MustAlias;
848
849   // If we have a known constant offset, see if this offset is larger than the
850   // access size being queried.  If so, and if no variable indices can remove
851   // pieces of this constant, then we know we have a no-alias.  For example,
852   //   &A[100] != &A.
853   
854   // In order to handle cases like &A[100][i] where i is an out of range
855   // subscript, we have to ignore all constant offset pieces that are a multiple
856   // of a scaled index.  Do this by removing constant offsets that are a
857   // multiple of any of our variable indices.  This allows us to transform
858   // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
859   // provides an offset of 4 bytes (assuming a <= 4 byte access).
860   for (unsigned i = 0, e = GEP1VariableIndices.size();
861        i != e && GEP1BaseOffset;++i)
862     if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].Scale)
863       GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].Scale;
864   
865   // If our known offset is bigger than the access size, we know we don't have
866   // an alias.
867   if (GEP1BaseOffset) {
868     if (GEP1BaseOffset >= 0 ?
869         (V2Size != UnknownSize && (uint64_t)GEP1BaseOffset >= V2Size) :
870         (V1Size != UnknownSize && -(uint64_t)GEP1BaseOffset >= V1Size &&
871          GEP1BaseOffset != INT64_MIN))
872       return NoAlias;
873   }
874   
875   return MayAlias;
876 }
877
878 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
879 /// instruction against another.
880 AliasAnalysis::AliasResult
881 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
882                                 const MDNode *SITBAAInfo,
883                                 const Value *V2, uint64_t V2Size,
884                                 const MDNode *V2TBAAInfo) {
885   // If this select has been visited before, we're on a use-def cycle.
886   // Such cycles are only valid when PHI nodes are involved or in unreachable
887   // code. The visitPHI function catches cycles containing PHIs, but there
888   // could still be a cycle without PHIs in unreachable code.
889   if (!Visited.insert(SI))
890     return MayAlias;
891
892   // If the values are Selects with the same condition, we can do a more precise
893   // check: just check for aliases between the values on corresponding arms.
894   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
895     if (SI->getCondition() == SI2->getCondition()) {
896       AliasResult Alias =
897         aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
898                    SI2->getTrueValue(), V2Size, V2TBAAInfo);
899       if (Alias == MayAlias)
900         return MayAlias;
901       AliasResult ThisAlias =
902         aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
903                    SI2->getFalseValue(), V2Size, V2TBAAInfo);
904       if (ThisAlias != Alias)
905         return MayAlias;
906       return Alias;
907     }
908
909   // If both arms of the Select node NoAlias or MustAlias V2, then returns
910   // NoAlias / MustAlias. Otherwise, returns MayAlias.
911   AliasResult Alias =
912     aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
913   if (Alias == MayAlias)
914     return MayAlias;
915
916   // If V2 is visited, the recursive case will have been caught in the
917   // above aliasCheck call, so these subsequent calls to aliasCheck
918   // don't need to assume that V2 is being visited recursively.
919   Visited.erase(V2);
920
921   AliasResult ThisAlias =
922     aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
923   if (ThisAlias != Alias)
924     return MayAlias;
925   return Alias;
926 }
927
928 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
929 // against another.
930 AliasAnalysis::AliasResult
931 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
932                              const MDNode *PNTBAAInfo,
933                              const Value *V2, uint64_t V2Size,
934                              const MDNode *V2TBAAInfo) {
935   // The PHI node has already been visited, avoid recursion any further.
936   if (!Visited.insert(PN))
937     return MayAlias;
938
939   // If the values are PHIs in the same block, we can do a more precise
940   // as well as efficient check: just check for aliases between the values
941   // on corresponding edges.
942   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
943     if (PN2->getParent() == PN->getParent()) {
944       AliasResult Alias =
945         aliasCheck(PN->getIncomingValue(0), PNSize, PNTBAAInfo,
946                    PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
947                    V2Size, V2TBAAInfo);
948       if (Alias == MayAlias)
949         return MayAlias;
950       for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
951         AliasResult ThisAlias =
952           aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
953                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
954                      V2Size, V2TBAAInfo);
955         if (ThisAlias != Alias)
956           return MayAlias;
957       }
958       return Alias;
959     }
960
961   SmallPtrSet<Value*, 4> UniqueSrc;
962   SmallVector<Value*, 4> V1Srcs;
963   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
964     Value *PV1 = PN->getIncomingValue(i);
965     if (isa<PHINode>(PV1))
966       // If any of the source itself is a PHI, return MayAlias conservatively
967       // to avoid compile time explosion. The worst possible case is if both
968       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
969       // and 'n' are the number of PHI sources.
970       return MayAlias;
971     if (UniqueSrc.insert(PV1))
972       V1Srcs.push_back(PV1);
973   }
974
975   AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
976                                  V1Srcs[0], PNSize, PNTBAAInfo);
977   // Early exit if the check of the first PHI source against V2 is MayAlias.
978   // Other results are not possible.
979   if (Alias == MayAlias)
980     return MayAlias;
981
982   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
983   // NoAlias / MustAlias. Otherwise, returns MayAlias.
984   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
985     Value *V = V1Srcs[i];
986
987     // If V2 is visited, the recursive case will have been caught in the
988     // above aliasCheck call, so these subsequent calls to aliasCheck
989     // don't need to assume that V2 is being visited recursively.
990     Visited.erase(V2);
991
992     AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
993                                        V, PNSize, PNTBAAInfo);
994     if (ThisAlias != Alias || ThisAlias == MayAlias)
995       return MayAlias;
996   }
997
998   return Alias;
999 }
1000
1001 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1002 // such as array references.
1003 //
1004 AliasAnalysis::AliasResult
1005 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1006                                const MDNode *V1TBAAInfo,
1007                                const Value *V2, uint64_t V2Size,
1008                                const MDNode *V2TBAAInfo) {
1009   // If either of the memory references is empty, it doesn't matter what the
1010   // pointer values are.
1011   if (V1Size == 0 || V2Size == 0)
1012     return NoAlias;
1013
1014   // Strip off any casts if they exist.
1015   V1 = V1->stripPointerCasts();
1016   V2 = V2->stripPointerCasts();
1017
1018   // Are we checking for alias of the same value?
1019   if (V1 == V2) return MustAlias;
1020
1021   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1022     return NoAlias;  // Scalars cannot alias each other
1023
1024   // Figure out what objects these things are pointing to if we can.
1025   const Value *O1 = V1->getUnderlyingObject();
1026   const Value *O2 = V2->getUnderlyingObject();
1027
1028   // Null values in the default address space don't point to any object, so they
1029   // don't alias any other pointer.
1030   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1031     if (CPN->getType()->getAddressSpace() == 0)
1032       return NoAlias;
1033   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1034     if (CPN->getType()->getAddressSpace() == 0)
1035       return NoAlias;
1036
1037   if (O1 != O2) {
1038     // If V1/V2 point to two different objects we know that we have no alias.
1039     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1040       return NoAlias;
1041
1042     // Constant pointers can't alias with non-const isIdentifiedObject objects.
1043     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1044         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1045       return NoAlias;
1046
1047     // Arguments can't alias with local allocations or noalias calls
1048     // in the same function.
1049     if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
1050          (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
1051       return NoAlias;
1052
1053     // Most objects can't alias null.
1054     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1055         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1056       return NoAlias;
1057   
1058     // If one pointer is the result of a call/invoke or load and the other is a
1059     // non-escaping local object within the same function, then we know the
1060     // object couldn't escape to a point where the call could return it.
1061     //
1062     // Note that if the pointers are in different functions, there are a
1063     // variety of complications. A call with a nocapture argument may still
1064     // temporary store the nocapture argument's value in a temporary memory
1065     // location if that memory location doesn't escape. Or it may pass a
1066     // nocapture value to other functions as long as they don't capture it.
1067     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1068       return NoAlias;
1069     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1070       return NoAlias;
1071   }
1072
1073   // If the size of one access is larger than the entire object on the other
1074   // side, then we know such behavior is undefined and can assume no alias.
1075   if (TD)
1076     if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
1077         (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
1078       return NoAlias;
1079   
1080   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1081   // GEP can't simplify, we don't even look at the PHI cases.
1082   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1083     std::swap(V1, V2);
1084     std::swap(V1Size, V2Size);
1085     std::swap(O1, O2);
1086   }
1087   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1088     AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, V2TBAAInfo, O1, O2);
1089     if (Result != MayAlias) return Result;
1090   }
1091
1092   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1093     std::swap(V1, V2);
1094     std::swap(V1Size, V2Size);
1095   }
1096   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1097     AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1098                                   V2, V2Size, V2TBAAInfo);
1099     if (Result != MayAlias) return Result;
1100   }
1101
1102   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1103     std::swap(V1, V2);
1104     std::swap(V1Size, V2Size);
1105   }
1106   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1107     AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1108                                      V2, V2Size, V2TBAAInfo);
1109     if (Result != MayAlias) return Result;
1110   }
1111
1112   return AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1113                               Location(V2, V2Size, V2TBAAInfo));
1114 }