c038b2070582ebeae30ebfb2195eb1867513ddf6
[oota-llvm.git] / lib / Analysis / BasicAliasAnalysis.cpp
1 //===- BasicAliasAnalysis.cpp - Local 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 default implementation of the Alias Analysis interface
11 // that simply implements a few identities (two different globals cannot alias,
12 // etc), but otherwise does no 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/Operator.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.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
85 /// isObjectSmallerThan - Return true if we can prove that the object specified
86 /// by V is smaller than Size.
87 static bool isObjectSmallerThan(const Value *V, unsigned Size,
88                                 const TargetData &TD) {
89   const Type *AccessTy;
90   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
91     AccessTy = GV->getType()->getElementType();
92   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
93     if (!AI->isArrayAllocation())
94       AccessTy = AI->getType()->getElementType();
95     else
96       return false;
97   } else if (const CallInst* CI = extractMallocCall(V)) {
98     if (!isArrayMalloc(V, &TD))
99       // The size is the argument to the malloc call.
100       if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
101         return (C->getZExtValue() < Size);
102     return false;
103   } else if (const Argument *A = dyn_cast<Argument>(V)) {
104     if (A->hasByValAttr())
105       AccessTy = cast<PointerType>(A->getType())->getElementType();
106     else
107       return false;
108   } else {
109     return false;
110   }
111   
112   if (AccessTy->isSized())
113     return TD.getTypeAllocSize(AccessTy) < Size;
114   return false;
115 }
116
117 //===----------------------------------------------------------------------===//
118 // NoAA Pass
119 //===----------------------------------------------------------------------===//
120
121 namespace {
122   /// NoAA - This class implements the -no-aa pass, which always returns "I
123   /// don't know" for alias queries.  NoAA is unlike other alias analysis
124   /// implementations, in that it does not chain to a previous analysis.  As
125   /// such it doesn't follow many of the rules that other alias analyses must.
126   ///
127   struct NoAA : public ImmutablePass, public AliasAnalysis {
128     static char ID; // Class identification, replacement for typeinfo
129     NoAA() : ImmutablePass(&ID) {}
130     explicit NoAA(void *PID) : ImmutablePass(PID) { }
131
132     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
133     }
134
135     virtual void initializePass() {
136       TD = getAnalysisIfAvailable<TargetData>();
137     }
138
139     virtual AliasResult alias(const Value *V1, unsigned V1Size,
140                               const Value *V2, unsigned V2Size) {
141       return MayAlias;
142     }
143
144     virtual void getArgumentAccesses(Function *F, CallSite CS,
145                                      std::vector<PointerAccessInfo> &Info) {
146       llvm_unreachable("This method may not be called on this function!");
147     }
148
149     virtual bool pointsToConstantMemory(const Value *P) { return false; }
150     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
151       return ModRef;
152     }
153     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
154       return ModRef;
155     }
156
157     virtual void deleteValue(Value *V) {}
158     virtual void copyValue(Value *From, Value *To) {}
159   };
160 }  // End of anonymous namespace
161
162 // Register this pass...
163 char NoAA::ID = 0;
164 static RegisterPass<NoAA>
165 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
166
167 // Declare that we implement the AliasAnalysis interface
168 static RegisterAnalysisGroup<AliasAnalysis> V(U);
169
170 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
171
172 //===----------------------------------------------------------------------===//
173 // BasicAA Pass
174 //===----------------------------------------------------------------------===//
175
176 namespace {
177   /// BasicAliasAnalysis - This is the default alias analysis implementation.
178   /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
179   /// derives from the NoAA class.
180   struct BasicAliasAnalysis : public NoAA {
181     static char ID; // Class identification, replacement for typeinfo
182     BasicAliasAnalysis() : NoAA(&ID) {}
183     AliasResult alias(const Value *V1, unsigned V1Size,
184                       const Value *V2, unsigned V2Size) {
185       assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
186       AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
187       VisitedPHIs.clear();
188       return Alias;
189     }
190
191     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
192     ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
193
194     /// pointsToConstantMemory - Chase pointers until we find a (constant
195     /// global) or not.
196     bool pointsToConstantMemory(const Value *P);
197
198   private:
199     // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
200     SmallPtrSet<const Value*, 16> VisitedPHIs;
201
202     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
203     // instruction against another.
204     AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
205                          const Value *V2, unsigned V2Size,
206                          const Value *UnderlyingV1, const Value *UnderlyingV2);
207
208     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
209     // instruction against another.
210     AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
211                          const Value *V2, unsigned V2Size);
212
213     /// aliasSelect - Disambiguate a Select instruction against another value.
214     AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
215                             const Value *V2, unsigned V2Size);
216
217     AliasResult aliasCheck(const Value *V1, unsigned V1Size,
218                            const Value *V2, unsigned V2Size);
219   };
220 }  // End of anonymous namespace
221
222 // Register this pass...
223 char BasicAliasAnalysis::ID = 0;
224 static RegisterPass<BasicAliasAnalysis>
225 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
226
227 // Declare that we implement the AliasAnalysis interface
228 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
229
230 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
231   return new BasicAliasAnalysis();
232 }
233
234
235 /// pointsToConstantMemory - Chase pointers until we find a (constant
236 /// global) or not.
237 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
238   if (const GlobalVariable *GV = 
239         dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
240     // Note: this doesn't require GV to be "ODR" because it isn't legal for a
241     // global to be marked constant in some modules and non-constant in others.
242     // GV may even be a declaration, not a definition.
243     return GV->isConstant();
244   return false;
245 }
246
247
248 /// getModRefInfo - Check to see if the specified callsite can clobber the
249 /// specified memory object.  Since we only look at local properties of this
250 /// function, we really can't say much about this query.  We do, however, use
251 /// simple "address taken" analysis on local objects.
252 AliasAnalysis::ModRefResult
253 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
254   const Value *Object = P->getUnderlyingObject();
255   
256   // If this is a tail call and P points to a stack location, we know that
257   // the tail call cannot access or modify the local stack.
258   // We cannot exclude byval arguments here; these belong to the caller of
259   // the current function not to the current function, and a tail callee
260   // may reference them.
261   if (isa<AllocaInst>(Object))
262     if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
263       if (CI->isTailCall())
264         return NoModRef;
265   
266   // If the pointer is to a locally allocated object that does not escape,
267   // then the call can not mod/ref the pointer unless the call takes the pointer
268   // as an argument, and itself doesn't capture it.
269   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
270       isNonEscapingLocalObject(Object)) {
271     bool PassedAsArg = false;
272     unsigned ArgNo = 0;
273     for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
274          CI != CE; ++CI, ++ArgNo) {
275       // Only look at the no-capture pointer arguments.
276       if (!isa<PointerType>((*CI)->getType()) ||
277           !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
278         continue;
279       
280       // If  this is a no-capture pointer argument, see if we can tell that it
281       // is impossible to alias the pointer we're checking.  If not, we have to
282       // assume that the call could touch the pointer, even though it doesn't
283       // escape.
284       if (!isNoAlias(cast<Value>(CI), ~0U, P, ~0U)) {
285         PassedAsArg = true;
286         break;
287       }
288     }
289     
290     if (!PassedAsArg)
291       return NoModRef;
292   }
293
294   // Finally, handle specific knowledge of intrinsics.
295   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
296   if (II == 0)
297     return AliasAnalysis::getModRefInfo(CS, P, Size);
298
299   switch (II->getIntrinsicID()) {
300   default: break;
301   case Intrinsic::memcpy:
302   case Intrinsic::memmove: {
303     unsigned Len = ~0U;
304     if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
305       Len = LenCI->getZExtValue();
306     Value *Dest = II->getOperand(1);
307     Value *Src = II->getOperand(2);
308     if (isNoAlias(Dest, Len, P, Size)) {
309       if (isNoAlias(Src, Len, P, Size))
310         return NoModRef;
311       return Ref;
312     }
313     break;
314   }
315   case Intrinsic::memset:
316     // Since memset is 'accesses arguments' only, the AliasAnalysis base class
317     // will handle it for the variable length case.
318     if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
319       unsigned Len = LenCI->getZExtValue();
320       Value *Dest = II->getOperand(1);
321       if (isNoAlias(Dest, Len, P, Size))
322         return NoModRef;
323     }
324     break;
325   case Intrinsic::atomic_cmp_swap:
326   case Intrinsic::atomic_swap:
327   case Intrinsic::atomic_load_add:
328   case Intrinsic::atomic_load_sub:
329   case Intrinsic::atomic_load_and:
330   case Intrinsic::atomic_load_nand:
331   case Intrinsic::atomic_load_or:
332   case Intrinsic::atomic_load_xor:
333   case Intrinsic::atomic_load_max:
334   case Intrinsic::atomic_load_min:
335   case Intrinsic::atomic_load_umax:
336   case Intrinsic::atomic_load_umin:
337     if (TD) {
338       Value *Op1 = II->getOperand(1);
339       unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
340       if (isNoAlias(Op1, Op1Size, P, Size))
341         return NoModRef;
342     }
343     break;
344   case Intrinsic::lifetime_start:
345   case Intrinsic::lifetime_end:
346   case Intrinsic::invariant_start: {
347     unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
348     if (isNoAlias(II->getOperand(2), PtrSize, P, Size))
349       return NoModRef;
350     break;
351   }
352   case Intrinsic::invariant_end: {
353     unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
354     if (isNoAlias(II->getOperand(3), PtrSize, P, Size))
355       return NoModRef;
356     break;
357   }
358   }
359
360   // The AliasAnalysis base class has some smarts, lets use them.
361   return AliasAnalysis::getModRefInfo(CS, P, Size);
362 }
363
364
365 AliasAnalysis::ModRefResult 
366 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
367   // If CS1 or CS2 are readnone, they don't interact.
368   ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
369   if (CS1B == DoesNotAccessMemory) return NoModRef;
370   
371   ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
372   if (CS2B == DoesNotAccessMemory) return NoModRef;
373   
374   // If they both only read from memory, just return ref.
375   if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
376     return Ref;
377   
378   // Otherwise, fall back to NoAA (mod+ref).
379   return NoAA::getModRefInfo(CS1, CS2);
380 }
381
382 /// GetLinearExpression - Analyze the specified value as a linear expression:
383 /// "A*V + B".  Return the scale and offset values as APInts and return V as a
384 /// Value*.  The incoming Value is known to be a scalar integer.
385 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
386                                   const TargetData *TD) {
387   assert(isa<IntegerType>(V->getType()) && "Not an integer value");
388   
389   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
390     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
391       switch (BOp->getOpcode()) {
392       default: break;
393       case Instruction::Or:
394         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
395         // analyze it.
396         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), TD))
397           break;
398         // FALL THROUGH.
399       case Instruction::Add:
400         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, TD);
401         Offset += RHSC->getValue();
402         return V;
403       // TODO: SHL, MUL.
404       }
405     }
406   }
407
408   Scale = 1;
409   Offset = 0;
410   return V;
411 }
412
413 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
414 /// into a base pointer with a constant offset and a number of scaled symbolic
415 /// offsets.
416 ///
417 /// When TargetData is around, this function is capable of analyzing everything
418 /// that Value::getUnderlyingObject() can look through.  When not, it just looks
419 /// through pointer casts.
420 ///
421 /// FIXME: Move this out to ValueTracking.cpp
422 ///
423 static const Value *DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
424                  SmallVectorImpl<std::pair<const Value*, int64_t> > &VarIndices,
425                                            const TargetData *TD) {
426   // FIXME: Should limit depth like getUnderlyingObject?
427   BaseOffs = 0;
428   while (1) {
429     // See if this is a bitcast or GEP.
430     const Operator *Op = dyn_cast<Operator>(V);
431     if (Op == 0) {
432       // The only non-operator case we can handle are GlobalAliases.
433       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
434         if (!GA->mayBeOverridden()) {
435           V = GA->getAliasee();
436           continue;
437         }
438       }
439       return V;
440     }
441     
442     if (Op->getOpcode() == Instruction::BitCast) {
443       V = Op->getOperand(0);
444       continue;
445     }
446     
447     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
448     if (GEPOp == 0)
449       return V;
450     
451     // Don't attempt to analyze GEPs over unsized objects.
452     if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
453           ->getElementType()->isSized())
454       return V;
455
456     // If we are lacking TargetData information, we can't compute the offets of
457     // elements computed by GEPs.  However, we can handle bitcast equivalent
458     // GEPs.
459     if (!TD) {
460       if (!GEPOp->hasAllZeroIndices())
461         return V;
462       V = GEPOp->getOperand(0);
463       continue;
464     }
465     
466     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
467     gep_type_iterator GTI = gep_type_begin(GEPOp);
468     for (User::const_op_iterator I = next(GEPOp->op_begin()),
469          E = GEPOp->op_end(); I != E; ++I) {
470       Value *Index = *I;
471       // Compute the (potentially symbolic) offset in bytes for this index.
472       if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
473         // For a struct, add the member offset.
474         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
475         if (FieldNo == 0) continue;
476         
477         BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
478         continue;
479       }
480       
481       // For an array/pointer, add the element offset, explicitly scaled.
482       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
483         if (CIdx->isZero()) continue;
484         BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
485         continue;
486       }
487       
488       // TODO: Could handle linear expressions here like A[X+1], also A[X*4|1].
489       uint64_t Scale = TD->getTypeAllocSize(*GTI);
490       
491       unsigned Width = cast<IntegerType>(Index->getType())->getBitWidth();
492       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
493       Index = GetLinearExpression(Index, IndexScale, IndexOffset, TD);
494       
495       Scale *= IndexScale.getZExtValue();
496       BaseOffs += IndexOffset.getZExtValue()*Scale;
497       
498       
499       // If we already had an occurrance of this index variable, merge this
500       // scale into it.  For example, we want to handle:
501       //   A[x][x] -> x*16 + x*4 -> x*20
502       // This also ensures that 'x' only appears in the index list once.
503       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
504         if (VarIndices[i].first == Index) {
505           Scale += VarIndices[i].second;
506           VarIndices.erase(VarIndices.begin()+i);
507           break;
508         }
509       }
510       
511       // Make sure that we have a scale that makes sense for this target's
512       // pointer size.
513       if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
514         Scale <<= ShiftBits;
515         Scale >>= ShiftBits;
516       }
517       
518       if (Scale)
519         VarIndices.push_back(std::make_pair(Index, Scale));
520     }
521     
522     // Analyze the base pointer next.
523     V = GEPOp->getOperand(0);
524   }
525 }
526
527 /// GetIndiceDifference - Dest and Src are the variable indices from two
528 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
529 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
530 /// difference between the two pointers. 
531 static void GetIndiceDifference(
532                       SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
533                 const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
534   if (Src.empty()) return;
535
536   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
537     const Value *V = Src[i].first;
538     int64_t Scale = Src[i].second;
539     
540     // Find V in Dest.  This is N^2, but pointer indices almost never have more
541     // than a few variable indexes.
542     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
543       if (Dest[j].first != V) continue;
544       
545       // If we found it, subtract off Scale V's from the entry in Dest.  If it
546       // goes to zero, remove the entry.
547       if (Dest[j].second != Scale)
548         Dest[j].second -= Scale;
549       else
550         Dest.erase(Dest.begin()+j);
551       Scale = 0;
552       break;
553     }
554     
555     // If we didn't consume this entry, add it to the end of the Dest list.
556     if (Scale)
557       Dest.push_back(std::make_pair(V, -Scale));
558   }
559 }
560
561 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
562 /// against another pointer.  We know that V1 is a GEP, but we don't know
563 /// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
564 /// UnderlyingV2 is the same for V2.
565 ///
566 AliasAnalysis::AliasResult
567 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
568                              const Value *V2, unsigned V2Size,
569                              const Value *UnderlyingV1,
570                              const Value *UnderlyingV2) {
571   int64_t GEP1BaseOffset;
572   SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
573
574   // If we have two gep instructions with must-alias'ing base pointers, figure
575   // out if the indexes to the GEP tell us anything about the derived pointer.
576   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
577     // Do the base pointers alias?
578     AliasResult BaseAlias = aliasCheck(UnderlyingV1, ~0U, UnderlyingV2, ~0U);
579     
580     // If we get a No or May, then return it immediately, no amount of analysis
581     // will improve this situation.
582     if (BaseAlias != MustAlias) return BaseAlias;
583     
584     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
585     // exactly, see if the computed offset from the common pointer tells us
586     // about the relation of the resulting pointer.
587     const Value *GEP1BasePtr =
588       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
589     
590     int64_t GEP2BaseOffset;
591     SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
592     const Value *GEP2BasePtr =
593       DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
594     
595     // If DecomposeGEPExpression isn't able to look all the way through the
596     // addressing operation, we must not have TD and this is too complex for us
597     // to handle without it.
598     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
599       assert(TD == 0 &&
600              "DecomposeGEPExpression and getUnderlyingObject disagree!");
601       return MayAlias;
602     }
603     
604     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
605     // symbolic difference.
606     GEP1BaseOffset -= GEP2BaseOffset;
607     GetIndiceDifference(GEP1VariableIndices, GEP2VariableIndices);
608     
609   } else {
610     // Check to see if these two pointers are related by the getelementptr
611     // instruction.  If one pointer is a GEP with a non-zero index of the other
612     // pointer, we know they cannot alias.
613
614     // If both accesses are unknown size, we can't do anything useful here.
615     if (V1Size == ~0U && V2Size == ~0U)
616       return MayAlias;
617
618     AliasResult R = aliasCheck(UnderlyingV1, ~0U, V2, V2Size);
619     if (R != MustAlias)
620       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
621       // If V2 is known not to alias GEP base pointer, then the two values
622       // cannot alias per GEP semantics: "A pointer value formed from a
623       // getelementptr instruction is associated with the addresses associated
624       // with the first operand of the getelementptr".
625       return R;
626
627     const Value *GEP1BasePtr =
628       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
629     
630     // If DecomposeGEPExpression isn't able to look all the way through the
631     // addressing operation, we must not have TD and this is too complex for us
632     // to handle without it.
633     if (GEP1BasePtr != UnderlyingV1) {
634       assert(TD == 0 &&
635              "DecomposeGEPExpression and getUnderlyingObject disagree!");
636       return MayAlias;
637     }
638   }
639   
640   // In the two GEP Case, if there is no difference in the offsets of the
641   // computed pointers, the resultant pointers are a must alias.  This
642   // hapens when we have two lexically identical GEP's (for example).
643   //
644   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
645   // must aliases the GEP, the end result is a must alias also.
646   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
647     return MustAlias;
648
649   // If we have a known constant offset, see if this offset is larger than the
650   // access size being queried.  If so, and if no variable indices can remove
651   // pieces of this constant, then we know we have a no-alias.  For example,
652   //   &A[100] != &A.
653   
654   // In order to handle cases like &A[100][i] where i is an out of range
655   // subscript, we have to ignore all constant offset pieces that are a multiple
656   // of a scaled index.  Do this by removing constant offsets that are a
657   // multiple of any of our variable indices.  This allows us to transform
658   // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
659   // provides an offset of 4 bytes (assuming a <= 4 byte access).
660   for (unsigned i = 0, e = GEP1VariableIndices.size();
661        i != e && GEP1BaseOffset;++i)
662     if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
663       GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
664   
665   // If our known offset is bigger than the access size, we know we don't have
666   // an alias.
667   if (GEP1BaseOffset) {
668     if (GEP1BaseOffset >= (int64_t)V2Size ||
669         GEP1BaseOffset <= -(int64_t)V1Size)
670       return NoAlias;
671   }
672   
673   return MayAlias;
674 }
675
676 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
677 /// instruction against another.
678 AliasAnalysis::AliasResult
679 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
680                                 const Value *V2, unsigned V2Size) {
681   // If the values are Selects with the same condition, we can do a more precise
682   // check: just check for aliases between the values on corresponding arms.
683   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
684     if (SI->getCondition() == SI2->getCondition()) {
685       AliasResult Alias =
686         aliasCheck(SI->getTrueValue(), SISize,
687                    SI2->getTrueValue(), V2Size);
688       if (Alias == MayAlias)
689         return MayAlias;
690       AliasResult ThisAlias =
691         aliasCheck(SI->getFalseValue(), SISize,
692                    SI2->getFalseValue(), V2Size);
693       if (ThisAlias != Alias)
694         return MayAlias;
695       return Alias;
696     }
697
698   // If both arms of the Select node NoAlias or MustAlias V2, then returns
699   // NoAlias / MustAlias. Otherwise, returns MayAlias.
700   AliasResult Alias =
701     aliasCheck(SI->getTrueValue(), SISize, V2, V2Size);
702   if (Alias == MayAlias)
703     return MayAlias;
704   AliasResult ThisAlias =
705     aliasCheck(SI->getFalseValue(), SISize, V2, V2Size);
706   if (ThisAlias != Alias)
707     return MayAlias;
708   return Alias;
709 }
710
711 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
712 // against another.
713 AliasAnalysis::AliasResult
714 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
715                              const Value *V2, unsigned V2Size) {
716   // The PHI node has already been visited, avoid recursion any further.
717   if (!VisitedPHIs.insert(PN))
718     return MayAlias;
719
720   // If the values are PHIs in the same block, we can do a more precise
721   // as well as efficient check: just check for aliases between the values
722   // on corresponding edges.
723   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
724     if (PN2->getParent() == PN->getParent()) {
725       AliasResult Alias =
726         aliasCheck(PN->getIncomingValue(0), PNSize,
727                    PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
728                    V2Size);
729       if (Alias == MayAlias)
730         return MayAlias;
731       for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
732         AliasResult ThisAlias =
733           aliasCheck(PN->getIncomingValue(i), PNSize,
734                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
735                      V2Size);
736         if (ThisAlias != Alias)
737           return MayAlias;
738       }
739       return Alias;
740     }
741
742   SmallPtrSet<Value*, 4> UniqueSrc;
743   SmallVector<Value*, 4> V1Srcs;
744   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
745     Value *PV1 = PN->getIncomingValue(i);
746     if (isa<PHINode>(PV1))
747       // If any of the source itself is a PHI, return MayAlias conservatively
748       // to avoid compile time explosion. The worst possible case is if both
749       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
750       // and 'n' are the number of PHI sources.
751       return MayAlias;
752     if (UniqueSrc.insert(PV1))
753       V1Srcs.push_back(PV1);
754   }
755
756   AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
757   // Early exit if the check of the first PHI source against V2 is MayAlias.
758   // Other results are not possible.
759   if (Alias == MayAlias)
760     return MayAlias;
761
762   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
763   // NoAlias / MustAlias. Otherwise, returns MayAlias.
764   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
765     Value *V = V1Srcs[i];
766
767     // If V2 is a PHI, the recursive case will have been caught in the
768     // above aliasCheck call, so these subsequent calls to aliasCheck
769     // don't need to assume that V2 is being visited recursively.
770     VisitedPHIs.erase(V2);
771
772     AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
773     if (ThisAlias != Alias || ThisAlias == MayAlias)
774       return MayAlias;
775   }
776
777   return Alias;
778 }
779
780 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
781 // such as array references.
782 //
783 AliasAnalysis::AliasResult
784 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
785                                const Value *V2, unsigned V2Size) {
786   // Strip off any casts if they exist.
787   V1 = V1->stripPointerCasts();
788   V2 = V2->stripPointerCasts();
789
790   // Are we checking for alias of the same value?
791   if (V1 == V2) return MustAlias;
792
793   if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
794     return NoAlias;  // Scalars cannot alias each other
795
796   // Figure out what objects these things are pointing to if we can.
797   const Value *O1 = V1->getUnderlyingObject();
798   const Value *O2 = V2->getUnderlyingObject();
799
800   // Null values in the default address space don't point to any object, so they
801   // don't alias any other pointer.
802   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
803     if (CPN->getType()->getAddressSpace() == 0)
804       return NoAlias;
805   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
806     if (CPN->getType()->getAddressSpace() == 0)
807       return NoAlias;
808
809   if (O1 != O2) {
810     // If V1/V2 point to two different objects we know that we have no alias.
811     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
812       return NoAlias;
813
814     // Constant pointers can't alias with non-const isIdentifiedObject objects.
815     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
816         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
817       return NoAlias;
818
819     // Arguments can't alias with local allocations or noalias calls.
820     if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
821         (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
822       return NoAlias;
823
824     // Most objects can't alias null.
825     if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
826         (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
827       return NoAlias;
828   }
829   
830   // If the size of one access is larger than the entire object on the other
831   // side, then we know such behavior is undefined and can assume no alias.
832   if (TD)
833     if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
834         (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
835       return NoAlias;
836   
837   // If one pointer is the result of a call/invoke or load and the other is a
838   // non-escaping local object, then we know the object couldn't escape to a
839   // point where the call could return it. The load case works because
840   // isNonEscapingLocalObject considers all stores to be escapes (it
841   // passes true for the StoreCaptures argument to PointerMayBeCaptured).
842   if (O1 != O2) {
843     if ((isa<CallInst>(O1) || isa<InvokeInst>(O1) || isa<LoadInst>(O1) ||
844          isa<Argument>(O1)) &&
845         isNonEscapingLocalObject(O2))
846       return NoAlias;
847     if ((isa<CallInst>(O2) || isa<InvokeInst>(O2) || isa<LoadInst>(O2) ||
848          isa<Argument>(O2)) &&
849         isNonEscapingLocalObject(O1))
850       return NoAlias;
851   }
852
853   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
854   // GEP can't simplify, we don't even look at the PHI cases.
855   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
856     std::swap(V1, V2);
857     std::swap(V1Size, V2Size);
858     std::swap(O1, O2);
859   }
860   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
861     return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
862
863   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
864     std::swap(V1, V2);
865     std::swap(V1Size, V2Size);
866   }
867   if (const PHINode *PN = dyn_cast<PHINode>(V1))
868     return aliasPHI(PN, V1Size, V2, V2Size);
869
870   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
871     std::swap(V1, V2);
872     std::swap(V1Size, V2Size);
873   }
874   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
875     return aliasSelect(S1, V1Size, V2, V2Size);
876
877   return MayAlias;
878 }
879
880 // Make sure that anything that uses AliasAnalysis pulls in this file.
881 DEFINING_FILE_FOR(BasicAliasAnalysis)