Teach BasicAliasAnalysis::getModRefBehavior(const Function *F)
[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);
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
521 /// pointsToConstantMemory - Chase pointers until we find a (constant
522 /// global) or not.
523 bool BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc) {
524   if (const GlobalVariable *GV = 
525         dyn_cast<GlobalVariable>(Loc.Ptr->getUnderlyingObject()))
526     // Note: this doesn't require GV to be "ODR" because it isn't legal for a
527     // global to be marked constant in some modules and non-constant in others.
528     // GV may even be a declaration, not a definition.
529     return GV->isConstant();
530
531   return AliasAnalysis::pointsToConstantMemory(Loc);
532 }
533
534 /// getModRefBehavior - Return the behavior when calling the given call site.
535 AliasAnalysis::ModRefBehavior
536 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
537   if (CS.doesNotAccessMemory())
538     // Can't do better than this.
539     return DoesNotAccessMemory;
540
541   ModRefBehavior Min = UnknownModRefBehavior;
542
543   // If the callsite knows it only reads memory, don't return worse
544   // than that.
545   if (CS.onlyReadsMemory())
546     Min = OnlyReadsMemory;
547
548   // The AliasAnalysis base class has some smarts, lets use them.
549   return std::min(AliasAnalysis::getModRefBehavior(CS), Min);
550 }
551
552 /// getModRefBehavior - Return the behavior when calling the given function.
553 /// For use when the call site is not known.
554 AliasAnalysis::ModRefBehavior
555 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
556   // If the function declares it doesn't access memory, we can't do better.
557   if (F->doesNotAccessMemory())
558     return DoesNotAccessMemory;
559
560   // For intrinsics, we can check the table.
561   if (unsigned iid = F->getIntrinsicID()) {
562 #define GET_INTRINSIC_MODREF_BEHAVIOR
563 #include "llvm/Intrinsics.gen"
564 #undef GET_INTRINSIC_MODREF_BEHAVIOR
565   }
566
567   // If the function declares it only reads memory, go with that.
568   if (F->onlyReadsMemory())
569     return OnlyReadsMemory;
570
571   // Otherwise be conservative.
572   return AliasAnalysis::getModRefBehavior(F);
573 }
574
575 /// getModRefInfo - Check to see if the specified callsite can clobber the
576 /// specified memory object.  Since we only look at local properties of this
577 /// function, we really can't say much about this query.  We do, however, use
578 /// simple "address taken" analysis on local objects.
579 AliasAnalysis::ModRefResult
580 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
581                                   const Location &Loc) {
582   assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
583          "AliasAnalysis query involving multiple functions!");
584
585   const Value *Object = Loc.Ptr->getUnderlyingObject();
586   
587   // If this is a tail call and Loc.Ptr points to a stack location, we know that
588   // the tail call cannot access or modify the local stack.
589   // We cannot exclude byval arguments here; these belong to the caller of
590   // the current function not to the current function, and a tail callee
591   // may reference them.
592   if (isa<AllocaInst>(Object))
593     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
594       if (CI->isTailCall())
595         return NoModRef;
596   
597   // If the pointer is to a locally allocated object that does not escape,
598   // then the call can not mod/ref the pointer unless the call takes the pointer
599   // as an argument, and itself doesn't capture it.
600   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
601       isNonEscapingLocalObject(Object)) {
602     bool PassedAsArg = false;
603     unsigned ArgNo = 0;
604     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
605          CI != CE; ++CI, ++ArgNo) {
606       // Only look at the no-capture pointer arguments.
607       if (!(*CI)->getType()->isPointerTy() ||
608           !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
609         continue;
610       
611       // If this is a no-capture pointer argument, see if we can tell that it
612       // is impossible to alias the pointer we're checking.  If not, we have to
613       // assume that the call could touch the pointer, even though it doesn't
614       // escape.
615       if (!isNoAlias(Location(cast<Value>(CI)), Loc)) {
616         PassedAsArg = true;
617         break;
618       }
619     }
620     
621     if (!PassedAsArg)
622       return NoModRef;
623   }
624
625   // Finally, handle specific knowledge of intrinsics.
626   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
627   if (II != 0)
628     switch (II->getIntrinsicID()) {
629     default: break;
630     case Intrinsic::memcpy:
631     case Intrinsic::memmove: {
632       uint64_t Len = UnknownSize;
633       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
634         Len = LenCI->getZExtValue();
635       Value *Dest = II->getArgOperand(0);
636       Value *Src = II->getArgOperand(1);
637       if (isNoAlias(Location(Dest, Len), Loc)) {
638         if (isNoAlias(Location(Src, Len), Loc))
639           return NoModRef;
640         return Ref;
641       }
642       break;
643     }
644     case Intrinsic::memset:
645       // Since memset is 'accesses arguments' only, the AliasAnalysis base class
646       // will handle it for the variable length case.
647       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
648         uint64_t Len = LenCI->getZExtValue();
649         Value *Dest = II->getArgOperand(0);
650         if (isNoAlias(Location(Dest, Len), Loc))
651           return NoModRef;
652       }
653       break;
654     case Intrinsic::atomic_cmp_swap:
655     case Intrinsic::atomic_swap:
656     case Intrinsic::atomic_load_add:
657     case Intrinsic::atomic_load_sub:
658     case Intrinsic::atomic_load_and:
659     case Intrinsic::atomic_load_nand:
660     case Intrinsic::atomic_load_or:
661     case Intrinsic::atomic_load_xor:
662     case Intrinsic::atomic_load_max:
663     case Intrinsic::atomic_load_min:
664     case Intrinsic::atomic_load_umax:
665     case Intrinsic::atomic_load_umin:
666       if (TD) {
667         Value *Op1 = II->getArgOperand(0);
668         uint64_t Op1Size = TD->getTypeStoreSize(Op1->getType());
669         MDNode *Tag = II->getMetadata(LLVMContext::MD_tbaa);
670         if (isNoAlias(Location(Op1, Op1Size, Tag), Loc))
671           return NoModRef;
672       }
673       break;
674     case Intrinsic::lifetime_start:
675     case Intrinsic::lifetime_end:
676     case Intrinsic::invariant_start: {
677       uint64_t PtrSize =
678         cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
679       if (isNoAlias(Location(II->getArgOperand(1),
680                              PtrSize,
681                              II->getMetadata(LLVMContext::MD_tbaa)),
682                     Loc))
683         return NoModRef;
684       break;
685     }
686     case Intrinsic::invariant_end: {
687       uint64_t PtrSize =
688         cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
689       if (isNoAlias(Location(II->getArgOperand(2),
690                              PtrSize,
691                              II->getMetadata(LLVMContext::MD_tbaa)),
692                     Loc))
693         return NoModRef;
694       break;
695     }
696     }
697
698   // The AliasAnalysis base class has some smarts, lets use them.
699   return AliasAnalysis::getModRefInfo(CS, Loc);
700 }
701
702 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
703 /// against another pointer.  We know that V1 is a GEP, but we don't know
704 /// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
705 /// UnderlyingV2 is the same for V2.
706 ///
707 AliasAnalysis::AliasResult
708 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
709                              const Value *V2, uint64_t V2Size,
710                              const MDNode *V2TBAAInfo,
711                              const Value *UnderlyingV1,
712                              const Value *UnderlyingV2) {
713   // If this GEP has been visited before, we're on a use-def cycle.
714   // Such cycles are only valid when PHI nodes are involved or in unreachable
715   // code. The visitPHI function catches cycles containing PHIs, but there
716   // could still be a cycle without PHIs in unreachable code.
717   if (!Visited.insert(GEP1))
718     return MayAlias;
719
720   int64_t GEP1BaseOffset;
721   SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
722
723   // If we have two gep instructions with must-alias'ing base pointers, figure
724   // out if the indexes to the GEP tell us anything about the derived pointer.
725   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
726     // Do the base pointers alias?
727     AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, 0,
728                                        UnderlyingV2, UnknownSize, 0);
729     
730     // If we get a No or May, then return it immediately, no amount of analysis
731     // will improve this situation.
732     if (BaseAlias != MustAlias) return BaseAlias;
733     
734     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
735     // exactly, see if the computed offset from the common pointer tells us
736     // about the relation of the resulting pointer.
737     const Value *GEP1BasePtr =
738       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
739     
740     int64_t GEP2BaseOffset;
741     SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
742     const Value *GEP2BasePtr =
743       DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
744     
745     // If DecomposeGEPExpression isn't able to look all the way through the
746     // addressing operation, we must not have TD and this is too complex for us
747     // to handle without it.
748     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
749       assert(TD == 0 &&
750              "DecomposeGEPExpression and getUnderlyingObject disagree!");
751       return MayAlias;
752     }
753     
754     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
755     // symbolic difference.
756     GEP1BaseOffset -= GEP2BaseOffset;
757     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
758     
759   } else {
760     // Check to see if these two pointers are related by the getelementptr
761     // instruction.  If one pointer is a GEP with a non-zero index of the other
762     // pointer, we know they cannot alias.
763
764     // If both accesses are unknown size, we can't do anything useful here.
765     if (V1Size == UnknownSize && V2Size == UnknownSize)
766       return MayAlias;
767
768     AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, 0,
769                                V2, V2Size, V2TBAAInfo);
770     if (R != MustAlias)
771       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
772       // If V2 is known not to alias GEP base pointer, then the two values
773       // cannot alias per GEP semantics: "A pointer value formed from a
774       // getelementptr instruction is associated with the addresses associated
775       // with the first operand of the getelementptr".
776       return R;
777
778     const Value *GEP1BasePtr =
779       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
780     
781     // If DecomposeGEPExpression isn't able to look all the way through the
782     // addressing operation, we must not have TD and this is too complex for us
783     // to handle without it.
784     if (GEP1BasePtr != UnderlyingV1) {
785       assert(TD == 0 &&
786              "DecomposeGEPExpression and getUnderlyingObject disagree!");
787       return MayAlias;
788     }
789   }
790   
791   // In the two GEP Case, if there is no difference in the offsets of the
792   // computed pointers, the resultant pointers are a must alias.  This
793   // hapens when we have two lexically identical GEP's (for example).
794   //
795   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
796   // must aliases the GEP, the end result is a must alias also.
797   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
798     return MustAlias;
799
800   // If we have a known constant offset, see if this offset is larger than the
801   // access size being queried.  If so, and if no variable indices can remove
802   // pieces of this constant, then we know we have a no-alias.  For example,
803   //   &A[100] != &A.
804   
805   // In order to handle cases like &A[100][i] where i is an out of range
806   // subscript, we have to ignore all constant offset pieces that are a multiple
807   // of a scaled index.  Do this by removing constant offsets that are a
808   // multiple of any of our variable indices.  This allows us to transform
809   // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
810   // provides an offset of 4 bytes (assuming a <= 4 byte access).
811   for (unsigned i = 0, e = GEP1VariableIndices.size();
812        i != e && GEP1BaseOffset;++i)
813     if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].Scale)
814       GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].Scale;
815   
816   // If our known offset is bigger than the access size, we know we don't have
817   // an alias.
818   if (GEP1BaseOffset) {
819     if (GEP1BaseOffset >= 0 ?
820         (V2Size != UnknownSize && (uint64_t)GEP1BaseOffset >= V2Size) :
821         (V1Size != UnknownSize && -(uint64_t)GEP1BaseOffset >= V1Size &&
822          GEP1BaseOffset != INT64_MIN))
823       return NoAlias;
824   }
825   
826   return MayAlias;
827 }
828
829 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
830 /// instruction against another.
831 AliasAnalysis::AliasResult
832 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
833                                 const MDNode *SITBAAInfo,
834                                 const Value *V2, uint64_t V2Size,
835                                 const MDNode *V2TBAAInfo) {
836   // If this select has been visited before, we're on a use-def cycle.
837   // Such cycles are only valid when PHI nodes are involved or in unreachable
838   // code. The visitPHI function catches cycles containing PHIs, but there
839   // could still be a cycle without PHIs in unreachable code.
840   if (!Visited.insert(SI))
841     return MayAlias;
842
843   // If the values are Selects with the same condition, we can do a more precise
844   // check: just check for aliases between the values on corresponding arms.
845   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
846     if (SI->getCondition() == SI2->getCondition()) {
847       AliasResult Alias =
848         aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
849                    SI2->getTrueValue(), V2Size, V2TBAAInfo);
850       if (Alias == MayAlias)
851         return MayAlias;
852       AliasResult ThisAlias =
853         aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
854                    SI2->getFalseValue(), V2Size, V2TBAAInfo);
855       if (ThisAlias != Alias)
856         return MayAlias;
857       return Alias;
858     }
859
860   // If both arms of the Select node NoAlias or MustAlias V2, then returns
861   // NoAlias / MustAlias. Otherwise, returns MayAlias.
862   AliasResult Alias =
863     aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
864   if (Alias == MayAlias)
865     return MayAlias;
866
867   // If V2 is visited, the recursive case will have been caught in the
868   // above aliasCheck call, so these subsequent calls to aliasCheck
869   // don't need to assume that V2 is being visited recursively.
870   Visited.erase(V2);
871
872   AliasResult ThisAlias =
873     aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
874   if (ThisAlias != Alias)
875     return MayAlias;
876   return Alias;
877 }
878
879 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
880 // against another.
881 AliasAnalysis::AliasResult
882 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
883                              const MDNode *PNTBAAInfo,
884                              const Value *V2, uint64_t V2Size,
885                              const MDNode *V2TBAAInfo) {
886   // The PHI node has already been visited, avoid recursion any further.
887   if (!Visited.insert(PN))
888     return MayAlias;
889
890   // If the values are PHIs in the same block, we can do a more precise
891   // as well as efficient check: just check for aliases between the values
892   // on corresponding edges.
893   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
894     if (PN2->getParent() == PN->getParent()) {
895       AliasResult Alias =
896         aliasCheck(PN->getIncomingValue(0), PNSize, PNTBAAInfo,
897                    PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
898                    V2Size, V2TBAAInfo);
899       if (Alias == MayAlias)
900         return MayAlias;
901       for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
902         AliasResult ThisAlias =
903           aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
904                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
905                      V2Size, V2TBAAInfo);
906         if (ThisAlias != Alias)
907           return MayAlias;
908       }
909       return Alias;
910     }
911
912   SmallPtrSet<Value*, 4> UniqueSrc;
913   SmallVector<Value*, 4> V1Srcs;
914   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
915     Value *PV1 = PN->getIncomingValue(i);
916     if (isa<PHINode>(PV1))
917       // If any of the source itself is a PHI, return MayAlias conservatively
918       // to avoid compile time explosion. The worst possible case is if both
919       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
920       // and 'n' are the number of PHI sources.
921       return MayAlias;
922     if (UniqueSrc.insert(PV1))
923       V1Srcs.push_back(PV1);
924   }
925
926   AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
927                                  V1Srcs[0], PNSize, PNTBAAInfo);
928   // Early exit if the check of the first PHI source against V2 is MayAlias.
929   // Other results are not possible.
930   if (Alias == MayAlias)
931     return MayAlias;
932
933   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
934   // NoAlias / MustAlias. Otherwise, returns MayAlias.
935   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
936     Value *V = V1Srcs[i];
937
938     // If V2 is visited, the recursive case will have been caught in the
939     // above aliasCheck call, so these subsequent calls to aliasCheck
940     // don't need to assume that V2 is being visited recursively.
941     Visited.erase(V2);
942
943     AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
944                                        V, PNSize, PNTBAAInfo);
945     if (ThisAlias != Alias || ThisAlias == MayAlias)
946       return MayAlias;
947   }
948
949   return Alias;
950 }
951
952 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
953 // such as array references.
954 //
955 AliasAnalysis::AliasResult
956 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
957                                const MDNode *V1TBAAInfo,
958                                const Value *V2, uint64_t V2Size,
959                                const MDNode *V2TBAAInfo) {
960   // If either of the memory references is empty, it doesn't matter what the
961   // pointer values are.
962   if (V1Size == 0 || V2Size == 0)
963     return NoAlias;
964
965   // Strip off any casts if they exist.
966   V1 = V1->stripPointerCasts();
967   V2 = V2->stripPointerCasts();
968
969   // Are we checking for alias of the same value?
970   if (V1 == V2) return MustAlias;
971
972   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
973     return NoAlias;  // Scalars cannot alias each other
974
975   // Figure out what objects these things are pointing to if we can.
976   const Value *O1 = V1->getUnderlyingObject();
977   const Value *O2 = V2->getUnderlyingObject();
978
979   // Null values in the default address space don't point to any object, so they
980   // don't alias any other pointer.
981   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
982     if (CPN->getType()->getAddressSpace() == 0)
983       return NoAlias;
984   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
985     if (CPN->getType()->getAddressSpace() == 0)
986       return NoAlias;
987
988   if (O1 != O2) {
989     // If V1/V2 point to two different objects we know that we have no alias.
990     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
991       return NoAlias;
992
993     // Constant pointers can't alias with non-const isIdentifiedObject objects.
994     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
995         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
996       return NoAlias;
997
998     // Arguments can't alias with local allocations or noalias calls
999     // in the same function.
1000     if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
1001          (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
1002       return NoAlias;
1003
1004     // Most objects can't alias null.
1005     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1006         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1007       return NoAlias;
1008   
1009     // If one pointer is the result of a call/invoke or load and the other is a
1010     // non-escaping local object within the same function, then we know the
1011     // object couldn't escape to a point where the call could return it.
1012     //
1013     // Note that if the pointers are in different functions, there are a
1014     // variety of complications. A call with a nocapture argument may still
1015     // temporary store the nocapture argument's value in a temporary memory
1016     // location if that memory location doesn't escape. Or it may pass a
1017     // nocapture value to other functions as long as they don't capture it.
1018     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1019       return NoAlias;
1020     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1021       return NoAlias;
1022   }
1023
1024   // If the size of one access is larger than the entire object on the other
1025   // side, then we know such behavior is undefined and can assume no alias.
1026   if (TD)
1027     if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
1028         (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
1029       return NoAlias;
1030   
1031   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1032   // GEP can't simplify, we don't even look at the PHI cases.
1033   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1034     std::swap(V1, V2);
1035     std::swap(V1Size, V2Size);
1036     std::swap(O1, O2);
1037   }
1038   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1039     AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, V2TBAAInfo, O1, O2);
1040     if (Result != MayAlias) return Result;
1041   }
1042
1043   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1044     std::swap(V1, V2);
1045     std::swap(V1Size, V2Size);
1046   }
1047   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1048     AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1049                                   V2, V2Size, V2TBAAInfo);
1050     if (Result != MayAlias) return Result;
1051   }
1052
1053   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1054     std::swap(V1, V2);
1055     std::swap(V1Size, V2Size);
1056   }
1057   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1058     AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1059                                      V2, V2Size, V2TBAAInfo);
1060     if (Result != MayAlias) return Result;
1061   }
1062
1063   return AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1064                               Location(V2, V2Size, V2TBAAInfo));
1065 }