Use a more obvious way to avoid compiling functions which are only used when XDEBUG...
[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/GlobalVariable.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Operator.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Analysis/CaptureTracking.h"
27 #include "llvm/Analysis/MemoryBuiltins.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include <algorithm>
34 using namespace llvm;
35
36 //===----------------------------------------------------------------------===//
37 // Useful predicates
38 //===----------------------------------------------------------------------===//
39
40 /// isKnownNonNull - Return true if we know that the specified value is never
41 /// null.
42 static bool isKnownNonNull(const Value *V) {
43   // Alloca never returns null, malloc might.
44   if (isa<AllocaInst>(V)) return true;
45   
46   // A byval argument is never null.
47   if (const Argument *A = dyn_cast<Argument>(V))
48     return A->hasByValAttr();
49
50   // Global values are not null unless extern weak.
51   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
52     return !GV->hasExternalWeakLinkage();
53   return false;
54 }
55
56 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
57 /// object that never escapes from the function.
58 static bool isNonEscapingLocalObject(const Value *V, bool Interprocedural) {
59   // If this is a local allocation, check to see if it escapes.
60   if (isa<AllocaInst>(V) ||
61       (!Interprocedural && isNoAliasCall(V)))
62     // Set StoreCaptures to True so that we can assume in our callers that the
63     // pointer is not the result of a load instruction. Currently
64     // PointerMayBeCaptured doesn't have any special analysis for the
65     // StoreCaptures=false case; if it did, our callers could be refined to be
66     // more precise.
67     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
68
69   // If this is an argument that corresponds to a byval or noalias argument,
70   // then it has not escaped before entering the function.  Check if it escapes
71   // inside the function.
72   if (!Interprocedural)
73     if (const Argument *A = dyn_cast<Argument>(V))
74       if (A->hasByValAttr() || A->hasNoAliasAttr()) {
75         // Don't bother analyzing arguments already known not to escape.
76         if (A->hasNoCaptureAttr())
77           return true;
78         return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
79       }
80   return false;
81 }
82
83 /// isEscapeSource - Return true if the pointer is one which would have
84 /// been considered an escape by isNonEscapingLocalObject.
85 static bool isEscapeSource(const Value *V, bool Interprocedural) {
86   if (!Interprocedural)
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, unsigned 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 // NoAA Pass
133 //===----------------------------------------------------------------------===//
134
135 namespace {
136   /// NoAA - This class implements the -no-aa pass, which always returns "I
137   /// don't know" for alias queries.  NoAA is unlike other alias analysis
138   /// implementations, in that it does not chain to a previous analysis.  As
139   /// such it doesn't follow many of the rules that other alias analyses must.
140   ///
141   struct NoAA : public ImmutablePass, public AliasAnalysis {
142     static char ID; // Class identification, replacement for typeinfo
143     NoAA() : ImmutablePass(&ID) {}
144     explicit NoAA(void *PID) : ImmutablePass(PID) { }
145
146     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
147     }
148
149     virtual void initializePass() {
150       TD = getAnalysisIfAvailable<TargetData>();
151     }
152
153     virtual AliasResult alias(const Value *V1, unsigned V1Size,
154                               const Value *V2, unsigned V2Size) {
155       return MayAlias;
156     }
157
158     virtual void getArgumentAccesses(Function *F, CallSite CS,
159                                      std::vector<PointerAccessInfo> &Info) {
160       llvm_unreachable("This method may not be called on this function!");
161     }
162
163     virtual bool pointsToConstantMemory(const Value *P) { return false; }
164     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
165       return ModRef;
166     }
167     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
168       return ModRef;
169     }
170
171     virtual void deleteValue(Value *V) {}
172     virtual void copyValue(Value *From, Value *To) {}
173     
174     /// getAdjustedAnalysisPointer - This method is used when a pass implements
175     /// an analysis interface through multiple inheritance.  If needed, it should
176     /// override this to adjust the this pointer as needed for the specified pass
177     /// info.
178     virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
179       if (PI->isPassID(&AliasAnalysis::ID))
180         return (AliasAnalysis*)this;
181       return this;
182     }
183   };
184 }  // End of anonymous namespace
185
186 // Register this pass...
187 char NoAA::ID = 0;
188 static RegisterPass<NoAA>
189 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
190
191 // Declare that we implement the AliasAnalysis interface
192 static RegisterAnalysisGroup<AliasAnalysis> V(U);
193
194 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
195
196 //===----------------------------------------------------------------------===//
197 // BasicAliasAnalysis Pass
198 //===----------------------------------------------------------------------===//
199
200 #ifdef XDEBUG
201 static const Function *getParent(const Value *V) {
202   if(const Instruction *inst = dyn_cast<Instruction>(V))
203     return inst->getParent()->getParent();
204
205   if(const Argument *arg = dyn_cast<Argument>(V))
206     return arg->getParent();
207
208   return NULL;
209 }
210
211 static bool sameParent(const Value *O1, const Value *O2) {
212
213   const Function *F1 = getParent(O1);
214   const Function *F2 = getParent(O2);
215
216   return !F1 || !F2 || F1 == F2;
217 }
218 #endif
219
220 namespace {
221   /// BasicAliasAnalysis - This is the default alias analysis implementation.
222   /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
223   /// derives from the NoAA class.
224   struct BasicAliasAnalysis : public NoAA {
225     /// Interprocedural - Flag for "interprocedural" mode, where we must
226     /// support queries of values which live in different functions.
227     bool Interprocedural;
228
229     static char ID; // Class identification, replacement for typeinfo
230     BasicAliasAnalysis()
231       : NoAA(&ID), Interprocedural(false) {}
232     BasicAliasAnalysis(void *PID, bool interprocedural)
233       : NoAA(PID), Interprocedural(interprocedural) {}
234
235     AliasResult alias(const Value *V1, unsigned V1Size,
236                       const Value *V2, unsigned V2Size) {
237       assert(Visited.empty() && "Visited must be cleared after use!");
238 #ifdef XDEBUG
239       assert((Interprocedural || sameParent(V1, V2)) &&
240              "BasicAliasAnalysis (-basicaa) doesn't support interprocedural "
241              "queries; use InterproceduralAliasAnalysis "
242              "(-interprocedural-basic-aa) instead.");
243 #endif
244       AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
245       Visited.clear();
246       return Alias;
247     }
248
249     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
250     ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
251
252     /// pointsToConstantMemory - Chase pointers until we find a (constant
253     /// global) or not.
254     bool pointsToConstantMemory(const Value *P);
255
256     /// getAdjustedAnalysisPointer - This method is used when a pass implements
257     /// an analysis interface through multiple inheritance.  If needed, it should
258     /// override this to adjust the this pointer as needed for the specified pass
259     /// info.
260     virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
261       if (PI->isPassID(&AliasAnalysis::ID))
262         return (AliasAnalysis*)this;
263       return this;
264     }
265     
266   private:
267     // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
268     SmallPtrSet<const Value*, 16> Visited;
269
270     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
271     // instruction against another.
272     AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
273                          const Value *V2, unsigned V2Size,
274                          const Value *UnderlyingV1, const Value *UnderlyingV2);
275
276     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
277     // instruction against another.
278     AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
279                          const Value *V2, unsigned V2Size);
280
281     /// aliasSelect - Disambiguate a Select instruction against another value.
282     AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
283                             const Value *V2, unsigned V2Size);
284
285     AliasResult aliasCheck(const Value *V1, unsigned V1Size,
286                            const Value *V2, unsigned V2Size);
287   };
288 }  // End of anonymous namespace
289
290 // Register this pass...
291 char BasicAliasAnalysis::ID = 0;
292 static RegisterPass<BasicAliasAnalysis>
293 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
294
295 // Declare that we implement the AliasAnalysis interface
296 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
297
298 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
299   return new BasicAliasAnalysis();
300 }
301
302
303 /// pointsToConstantMemory - Chase pointers until we find a (constant
304 /// global) or not.
305 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
306   if (const GlobalVariable *GV = 
307         dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
308     // Note: this doesn't require GV to be "ODR" because it isn't legal for a
309     // global to be marked constant in some modules and non-constant in others.
310     // GV may even be a declaration, not a definition.
311     return GV->isConstant();
312   return false;
313 }
314
315
316 /// getModRefInfo - Check to see if the specified callsite can clobber the
317 /// specified memory object.  Since we only look at local properties of this
318 /// function, we really can't say much about this query.  We do, however, use
319 /// simple "address taken" analysis on local objects.
320 AliasAnalysis::ModRefResult
321 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
322   const Value *Object = P->getUnderlyingObject();
323   
324   // If this is a tail call and P points to a stack location, we know that
325   // the tail call cannot access or modify the local stack.
326   // We cannot exclude byval arguments here; these belong to the caller of
327   // the current function not to the current function, and a tail callee
328   // may reference them.
329   if (isa<AllocaInst>(Object))
330     if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
331       if (CI->isTailCall())
332         return NoModRef;
333   
334   // If the pointer is to a locally allocated object that does not escape,
335   // then the call can not mod/ref the pointer unless the call takes the pointer
336   // as an argument, and itself doesn't capture it.
337   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
338       isNonEscapingLocalObject(Object, Interprocedural)) {
339     bool PassedAsArg = false;
340     unsigned ArgNo = 0;
341     for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
342          CI != CE; ++CI, ++ArgNo) {
343       // Only look at the no-capture pointer arguments.
344       if (!(*CI)->getType()->isPointerTy() ||
345           !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
346         continue;
347       
348       // If  this is a no-capture pointer argument, see if we can tell that it
349       // is impossible to alias the pointer we're checking.  If not, we have to
350       // assume that the call could touch the pointer, even though it doesn't
351       // escape.
352       if (!isNoAlias(cast<Value>(CI), ~0U, P, ~0U)) {
353         PassedAsArg = true;
354         break;
355       }
356     }
357     
358     if (!PassedAsArg)
359       return NoModRef;
360   }
361
362   // Finally, handle specific knowledge of intrinsics.
363   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
364   if (II == 0)
365     return AliasAnalysis::getModRefInfo(CS, P, Size);
366
367   switch (II->getIntrinsicID()) {
368   default: break;
369   case Intrinsic::memcpy:
370   case Intrinsic::memmove: {
371     unsigned Len = ~0U;
372     if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
373       Len = LenCI->getZExtValue();
374     Value *Dest = II->getArgOperand(0);
375     Value *Src = II->getArgOperand(1);
376     if (isNoAlias(Dest, Len, P, Size)) {
377       if (isNoAlias(Src, Len, P, Size))
378         return NoModRef;
379       return Ref;
380     }
381     break;
382   }
383   case Intrinsic::memset:
384     // Since memset is 'accesses arguments' only, the AliasAnalysis base class
385     // will handle it for the variable length case.
386     if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
387       unsigned Len = LenCI->getZExtValue();
388       Value *Dest = II->getArgOperand(0);
389       if (isNoAlias(Dest, Len, P, Size))
390         return NoModRef;
391     }
392     break;
393   case Intrinsic::atomic_cmp_swap:
394   case Intrinsic::atomic_swap:
395   case Intrinsic::atomic_load_add:
396   case Intrinsic::atomic_load_sub:
397   case Intrinsic::atomic_load_and:
398   case Intrinsic::atomic_load_nand:
399   case Intrinsic::atomic_load_or:
400   case Intrinsic::atomic_load_xor:
401   case Intrinsic::atomic_load_max:
402   case Intrinsic::atomic_load_min:
403   case Intrinsic::atomic_load_umax:
404   case Intrinsic::atomic_load_umin:
405     if (TD) {
406       Value *Op1 = II->getArgOperand(0);
407       unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
408       if (isNoAlias(Op1, Op1Size, P, Size))
409         return NoModRef;
410     }
411     break;
412   case Intrinsic::lifetime_start:
413   case Intrinsic::lifetime_end:
414   case Intrinsic::invariant_start: {
415     unsigned PtrSize = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
416     if (isNoAlias(II->getArgOperand(1), PtrSize, P, Size))
417       return NoModRef;
418     break;
419   }
420   case Intrinsic::invariant_end: {
421     unsigned PtrSize = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
422     if (isNoAlias(II->getArgOperand(2), PtrSize, P, Size))
423       return NoModRef;
424     break;
425   }
426   }
427
428   // The AliasAnalysis base class has some smarts, lets use them.
429   return AliasAnalysis::getModRefInfo(CS, P, Size);
430 }
431
432
433 AliasAnalysis::ModRefResult 
434 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
435   // If CS1 or CS2 are readnone, they don't interact.
436   ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
437   if (CS1B == DoesNotAccessMemory) return NoModRef;
438   
439   ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
440   if (CS2B == DoesNotAccessMemory) return NoModRef;
441   
442   // If they both only read from memory, just return ref.
443   if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
444     return Ref;
445   
446   // Otherwise, fall back to NoAA (mod+ref).
447   return NoAA::getModRefInfo(CS1, CS2);
448 }
449
450 /// GetIndiceDifference - Dest and Src are the variable indices from two
451 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
452 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
453 /// difference between the two pointers. 
454 static void GetIndiceDifference(
455                       SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
456                 const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
457   if (Src.empty()) return;
458
459   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
460     const Value *V = Src[i].first;
461     int64_t Scale = Src[i].second;
462     
463     // Find V in Dest.  This is N^2, but pointer indices almost never have more
464     // than a few variable indexes.
465     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
466       if (Dest[j].first != V) continue;
467       
468       // If we found it, subtract off Scale V's from the entry in Dest.  If it
469       // goes to zero, remove the entry.
470       if (Dest[j].second != Scale)
471         Dest[j].second -= Scale;
472       else
473         Dest.erase(Dest.begin()+j);
474       Scale = 0;
475       break;
476     }
477     
478     // If we didn't consume this entry, add it to the end of the Dest list.
479     if (Scale)
480       Dest.push_back(std::make_pair(V, -Scale));
481   }
482 }
483
484 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
485 /// against another pointer.  We know that V1 is a GEP, but we don't know
486 /// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
487 /// UnderlyingV2 is the same for V2.
488 ///
489 AliasAnalysis::AliasResult
490 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
491                              const Value *V2, unsigned V2Size,
492                              const Value *UnderlyingV1,
493                              const Value *UnderlyingV2) {
494   // If this GEP has been visited before, we're on a use-def cycle.
495   // Such cycles are only valid when PHI nodes are involved or in unreachable
496   // code. The visitPHI function catches cycles containing PHIs, but there
497   // could still be a cycle without PHIs in unreachable code.
498   if (!Visited.insert(GEP1))
499     return MayAlias;
500
501   int64_t GEP1BaseOffset;
502   SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
503
504   // If we have two gep instructions with must-alias'ing base pointers, figure
505   // out if the indexes to the GEP tell us anything about the derived pointer.
506   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
507     // Do the base pointers alias?
508     AliasResult BaseAlias = aliasCheck(UnderlyingV1, ~0U, UnderlyingV2, ~0U);
509     
510     // If we get a No or May, then return it immediately, no amount of analysis
511     // will improve this situation.
512     if (BaseAlias != MustAlias) return BaseAlias;
513     
514     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
515     // exactly, see if the computed offset from the common pointer tells us
516     // about the relation of the resulting pointer.
517     const Value *GEP1BasePtr =
518       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
519     
520     int64_t GEP2BaseOffset;
521     SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
522     const Value *GEP2BasePtr =
523       DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
524     
525     // If DecomposeGEPExpression isn't able to look all the way through the
526     // addressing operation, we must not have TD and this is too complex for us
527     // to handle without it.
528     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
529       assert(TD == 0 &&
530              "DecomposeGEPExpression and getUnderlyingObject disagree!");
531       return MayAlias;
532     }
533     
534     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
535     // symbolic difference.
536     GEP1BaseOffset -= GEP2BaseOffset;
537     GetIndiceDifference(GEP1VariableIndices, GEP2VariableIndices);
538     
539   } else {
540     // Check to see if these two pointers are related by the getelementptr
541     // instruction.  If one pointer is a GEP with a non-zero index of the other
542     // pointer, we know they cannot alias.
543
544     // If both accesses are unknown size, we can't do anything useful here.
545     if (V1Size == ~0U && V2Size == ~0U)
546       return MayAlias;
547
548     AliasResult R = aliasCheck(UnderlyingV1, ~0U, V2, V2Size);
549     if (R != MustAlias)
550       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
551       // If V2 is known not to alias GEP base pointer, then the two values
552       // cannot alias per GEP semantics: "A pointer value formed from a
553       // getelementptr instruction is associated with the addresses associated
554       // with the first operand of the getelementptr".
555       return R;
556
557     const Value *GEP1BasePtr =
558       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
559     
560     // If DecomposeGEPExpression isn't able to look all the way through the
561     // addressing operation, we must not have TD and this is too complex for us
562     // to handle without it.
563     if (GEP1BasePtr != UnderlyingV1) {
564       assert(TD == 0 &&
565              "DecomposeGEPExpression and getUnderlyingObject disagree!");
566       return MayAlias;
567     }
568   }
569   
570   // In the two GEP Case, if there is no difference in the offsets of the
571   // computed pointers, the resultant pointers are a must alias.  This
572   // hapens when we have two lexically identical GEP's (for example).
573   //
574   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
575   // must aliases the GEP, the end result is a must alias also.
576   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
577     return MustAlias;
578
579   // If we have a known constant offset, see if this offset is larger than the
580   // access size being queried.  If so, and if no variable indices can remove
581   // pieces of this constant, then we know we have a no-alias.  For example,
582   //   &A[100] != &A.
583   
584   // In order to handle cases like &A[100][i] where i is an out of range
585   // subscript, we have to ignore all constant offset pieces that are a multiple
586   // of a scaled index.  Do this by removing constant offsets that are a
587   // multiple of any of our variable indices.  This allows us to transform
588   // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
589   // provides an offset of 4 bytes (assuming a <= 4 byte access).
590   for (unsigned i = 0, e = GEP1VariableIndices.size();
591        i != e && GEP1BaseOffset;++i)
592     if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
593       GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
594   
595   // If our known offset is bigger than the access size, we know we don't have
596   // an alias.
597   if (GEP1BaseOffset) {
598     if (GEP1BaseOffset >= (int64_t)V2Size ||
599         GEP1BaseOffset <= -(int64_t)V1Size)
600       return NoAlias;
601   }
602   
603   return MayAlias;
604 }
605
606 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
607 /// instruction against another.
608 AliasAnalysis::AliasResult
609 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
610                                 const Value *V2, unsigned V2Size) {
611   // If this select has been visited before, we're on a use-def cycle.
612   // Such cycles are only valid when PHI nodes are involved or in unreachable
613   // code. The visitPHI function catches cycles containing PHIs, but there
614   // could still be a cycle without PHIs in unreachable code.
615   if (!Visited.insert(SI))
616     return MayAlias;
617
618   // If the values are Selects with the same condition, we can do a more precise
619   // check: just check for aliases between the values on corresponding arms.
620   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
621     if (SI->getCondition() == SI2->getCondition()) {
622       AliasResult Alias =
623         aliasCheck(SI->getTrueValue(), SISize,
624                    SI2->getTrueValue(), V2Size);
625       if (Alias == MayAlias)
626         return MayAlias;
627       AliasResult ThisAlias =
628         aliasCheck(SI->getFalseValue(), SISize,
629                    SI2->getFalseValue(), V2Size);
630       if (ThisAlias != Alias)
631         return MayAlias;
632       return Alias;
633     }
634
635   // If both arms of the Select node NoAlias or MustAlias V2, then returns
636   // NoAlias / MustAlias. Otherwise, returns MayAlias.
637   AliasResult Alias =
638     aliasCheck(V2, V2Size, SI->getTrueValue(), SISize);
639   if (Alias == MayAlias)
640     return MayAlias;
641
642   // If V2 is visited, the recursive case will have been caught in the
643   // above aliasCheck call, so these subsequent calls to aliasCheck
644   // don't need to assume that V2 is being visited recursively.
645   Visited.erase(V2);
646
647   AliasResult ThisAlias =
648     aliasCheck(V2, V2Size, SI->getFalseValue(), SISize);
649   if (ThisAlias != Alias)
650     return MayAlias;
651   return Alias;
652 }
653
654 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
655 // against another.
656 AliasAnalysis::AliasResult
657 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
658                              const Value *V2, unsigned V2Size) {
659   // The PHI node has already been visited, avoid recursion any further.
660   if (!Visited.insert(PN))
661     return MayAlias;
662
663   // If the values are PHIs in the same block, we can do a more precise
664   // as well as efficient check: just check for aliases between the values
665   // on corresponding edges.
666   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
667     if (PN2->getParent() == PN->getParent()) {
668       AliasResult Alias =
669         aliasCheck(PN->getIncomingValue(0), PNSize,
670                    PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
671                    V2Size);
672       if (Alias == MayAlias)
673         return MayAlias;
674       for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
675         AliasResult ThisAlias =
676           aliasCheck(PN->getIncomingValue(i), PNSize,
677                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
678                      V2Size);
679         if (ThisAlias != Alias)
680           return MayAlias;
681       }
682       return Alias;
683     }
684
685   SmallPtrSet<Value*, 4> UniqueSrc;
686   SmallVector<Value*, 4> V1Srcs;
687   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
688     Value *PV1 = PN->getIncomingValue(i);
689     if (isa<PHINode>(PV1))
690       // If any of the source itself is a PHI, return MayAlias conservatively
691       // to avoid compile time explosion. The worst possible case is if both
692       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
693       // and 'n' are the number of PHI sources.
694       return MayAlias;
695     if (UniqueSrc.insert(PV1))
696       V1Srcs.push_back(PV1);
697   }
698
699   AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
700   // Early exit if the check of the first PHI source against V2 is MayAlias.
701   // Other results are not possible.
702   if (Alias == MayAlias)
703     return MayAlias;
704
705   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
706   // NoAlias / MustAlias. Otherwise, returns MayAlias.
707   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
708     Value *V = V1Srcs[i];
709
710     // If V2 is visited, the recursive case will have been caught in the
711     // above aliasCheck call, so these subsequent calls to aliasCheck
712     // don't need to assume that V2 is being visited recursively.
713     Visited.erase(V2);
714
715     AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
716     if (ThisAlias != Alias || ThisAlias == MayAlias)
717       return MayAlias;
718   }
719
720   return Alias;
721 }
722
723 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
724 // such as array references.
725 //
726 AliasAnalysis::AliasResult
727 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
728                                const Value *V2, unsigned V2Size) {
729   // If either of the memory references is empty, it doesn't matter what the
730   // pointer values are.
731   if (V1Size == 0 || V2Size == 0)
732     return NoAlias;
733
734   // Strip off any casts if they exist.
735   V1 = V1->stripPointerCasts();
736   V2 = V2->stripPointerCasts();
737
738   // Are we checking for alias of the same value?
739   if (V1 == V2) return MustAlias;
740
741   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
742     return NoAlias;  // Scalars cannot alias each other
743
744   // Figure out what objects these things are pointing to if we can.
745   const Value *O1 = V1->getUnderlyingObject();
746   const Value *O2 = V2->getUnderlyingObject();
747
748   // Null values in the default address space don't point to any object, so they
749   // don't alias any other pointer.
750   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
751     if (CPN->getType()->getAddressSpace() == 0)
752       return NoAlias;
753   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
754     if (CPN->getType()->getAddressSpace() == 0)
755       return NoAlias;
756
757   if (O1 != O2) {
758     // If V1/V2 point to two different objects we know that we have no alias.
759     if (isIdentifiedObject(O1, Interprocedural) &&
760         isIdentifiedObject(O2, Interprocedural))
761       return NoAlias;
762
763     // Constant pointers can't alias with non-const isIdentifiedObject objects.
764     if ((isa<Constant>(O1) &&
765          isIdentifiedObject(O2, Interprocedural) &&
766          !isa<Constant>(O2)) ||
767         (isa<Constant>(O2) &&
768          isIdentifiedObject(O1, Interprocedural) &&
769          !isa<Constant>(O1)))
770       return NoAlias;
771
772     // Arguments can't alias with local allocations or noalias calls, unless
773     // we have to consider interprocedural aliasing.
774     if (!Interprocedural)
775       if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
776           (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
777         return NoAlias;
778
779     // Most objects can't alias null.
780     if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
781         (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
782       return NoAlias;
783   }
784   
785   // If the size of one access is larger than the entire object on the other
786   // side, then we know such behavior is undefined and can assume no alias.
787   if (TD)
788     if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
789         (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
790       return NoAlias;
791   
792   // If one pointer is the result of a call/invoke or load and the other is a
793   // non-escaping local object, then we know the object couldn't escape to a
794   // point where the call could return it.
795   if (O1 != O2) {
796     if (isEscapeSource(O1, Interprocedural) &&
797         isNonEscapingLocalObject(O2, Interprocedural))
798       return NoAlias;
799     if (isEscapeSource(O2, Interprocedural) &&
800         isNonEscapingLocalObject(O1, Interprocedural))
801       return NoAlias;
802   }
803
804   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
805   // GEP can't simplify, we don't even look at the PHI cases.
806   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
807     std::swap(V1, V2);
808     std::swap(V1Size, V2Size);
809     std::swap(O1, O2);
810   }
811   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
812     return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
813
814   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
815     std::swap(V1, V2);
816     std::swap(V1Size, V2Size);
817   }
818   if (const PHINode *PN = dyn_cast<PHINode>(V1))
819     return aliasPHI(PN, V1Size, V2, V2Size);
820
821   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
822     std::swap(V1, V2);
823     std::swap(V1Size, V2Size);
824   }
825   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
826     return aliasSelect(S1, V1Size, V2, V2Size);
827
828   return MayAlias;
829 }
830
831 // Make sure that anything that uses AliasAnalysis pulls in this file.
832 DEFINING_FILE_FOR(BasicAliasAnalysis)
833
834 //===----------------------------------------------------------------------===//
835 // InterproceduralBasicAliasAnalysis Pass
836 //===----------------------------------------------------------------------===//
837
838 namespace {
839   /// InterproceduralBasicAliasAnalysis - This is similar to basicaa, except
840   /// that it properly supports queries to values which live in different
841   /// functions.
842   ///
843   /// Note that we don't currently take this to the extreme, analyzing all
844   /// call sites of a function to answer a query about an Argument.
845   ///
846   struct InterproceduralBasicAliasAnalysis : public BasicAliasAnalysis {
847     static char ID; // Class identification, replacement for typeinfo
848     InterproceduralBasicAliasAnalysis() : BasicAliasAnalysis(&ID, true) {}
849   };
850 }
851
852 // Register this pass...
853 char InterproceduralBasicAliasAnalysis::ID = 0;
854 static RegisterPass<InterproceduralBasicAliasAnalysis>
855 W("interprocedural-basic-aa", "Interprocedural Basic Alias Analysis", false, true);
856
857 // Declare that we implement the AliasAnalysis interface
858 static RegisterAnalysisGroup<AliasAnalysis> Z(W);
859
860 ImmutablePass *llvm::createInterproceduralBasicAliasAnalysisPass() {
861   return new InterproceduralBasicAliasAnalysis();
862 }