When checking if an Argument escapes, check if
[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/Pass.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include <algorithm>
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 // Useful predicates
36 //===----------------------------------------------------------------------===//
37
38 // Determine if a value escapes from the function it is contained in (being
39 // returned by the function does not count as escaping here).  If a value local
40 // to the function does not escape, there is no way another function can mod/ref
41 // it.  We do this by looking at its uses and determining if they can escape
42 // (recursively).
43 static bool AddressMightEscape(const Value *V) {
44   for (Value::use_const_iterator UI = V->use_begin(), E = V->use_end();
45        UI != E; ++UI) {
46     const Instruction *I = cast<Instruction>(*UI);
47     switch (I->getOpcode()) {
48     case Instruction::Load: 
49       break; //next use.
50     case Instruction::Store:
51       if (I->getOperand(0) == V)
52         return true; // Escapes if the pointer is stored.
53       break; // next use.
54     case Instruction::GetElementPtr:
55       if (AddressMightEscape(I))
56         return true;
57       break; // next use.
58     case Instruction::BitCast:
59       if (AddressMightEscape(I))
60         return true;
61       break; // next use
62     case Instruction::Ret:
63       // If returned, the address will escape to calling functions, but no
64       // callees could modify it.
65       break; // next use
66     case Instruction::Call:
67       // If the argument to the call has the nocapture attribute, then the call
68       // may store or load to the pointer, but it cannot escape.
69       if (cast<CallInst>(I)->paramHasAttr(UI.getOperandNo(), 
70                                           Attribute::NoCapture))
71         continue;
72
73       // FIXME: MemIntrinsics should have their operands marked nocapture!
74       if (isa<MemIntrinsic>(I))
75         continue;  // next use
76       return true;
77     case Instruction::Invoke:
78       // If the argument to the call has the nocapture attribute, then the call
79       // may store or load to the pointer, but it cannot escape.
80       if (cast<InvokeInst>(I)->paramHasAttr(UI.getOperandNo()-2,
81                                             Attribute::NoCapture))
82         continue;
83       return true;
84     default:
85       return true;
86     }
87   }
88   return false;
89 }
90
91 static const User *isGEP(const Value *V) {
92   if (isa<GetElementPtrInst>(V) ||
93       (isa<ConstantExpr>(V) &&
94        cast<ConstantExpr>(V)->getOpcode() == Instruction::GetElementPtr))
95     return cast<User>(V);
96   return 0;
97 }
98
99 static const Value *GetGEPOperands(const Value *V, 
100                                    SmallVector<Value*, 16> &GEPOps) {
101   assert(GEPOps.empty() && "Expect empty list to populate!");
102   GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1,
103                 cast<User>(V)->op_end());
104
105   // Accumulate all of the chained indexes into the operand array
106   V = cast<User>(V)->getOperand(0);
107
108   while (const User *G = isGEP(V)) {
109     if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) ||
110         !cast<Constant>(GEPOps[0])->isNullValue())
111       break;  // Don't handle folding arbitrary pointer offsets yet...
112     GEPOps.erase(GEPOps.begin());   // Drop the zero index
113     GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end());
114     V = G->getOperand(0);
115   }
116   return V;
117 }
118
119 /// isNoAliasCall - Return true if this pointer is returned by a noalias
120 /// function.
121 static bool isNoAliasCall(const Value *V) {
122   if (isa<CallInst>(V) || isa<InvokeInst>(V))
123     return CallSite(const_cast<Instruction*>(cast<Instruction>(V)))
124       .paramHasAttr(0, Attribute::NoAlias);
125   return false;
126 }
127
128 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
129 /// identifiable object.  This returns true for:
130 ///    Global Variables and Functions
131 ///    Allocas and Mallocs
132 ///    ByVal and NoAlias Arguments
133 ///    NoAlias returns
134 ///
135 static bool isIdentifiedObject(const Value *V) {
136   if (isa<GlobalValue>(V) || isa<AllocationInst>(V) || isNoAliasCall(V))
137     return true;
138   if (const Argument *A = dyn_cast<Argument>(V))
139     return A->hasNoAliasAttr() || A->hasByValAttr();
140   return false;
141 }
142
143 /// isKnownNonNull - Return true if we know that the specified value is never
144 /// null.
145 static bool isKnownNonNull(const Value *V) {
146   // Alloca never returns null, malloc might.
147   if (isa<AllocaInst>(V)) return true;
148   
149   // A byval argument is never null.
150   if (const Argument *A = dyn_cast<Argument>(V))
151     return A->hasByValAttr();
152
153   // Global values are not null unless extern weak.
154   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
155     return !GV->hasExternalWeakLinkage();
156   return false;
157 }
158
159 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
160 /// object that never escapes from the function.
161 static bool isNonEscapingLocalObject(const Value *V) {
162   // If this is a local allocation, check to see if it escapes.
163   if (isa<AllocationInst>(V) || isNoAliasCall(V))
164     return !AddressMightEscape(V);
165
166   // If this is an argument that corresponds to a byval or noalias argument,
167   // then it has not escaped before entering the function.  Check if it escapes
168   // inside the function.
169   if (const Argument *A = dyn_cast<Argument>(V))
170     if (A->hasByValAttr() || A->hasNoAliasAttr()) {
171       // Don't bother analyzing arguments already known not to escape.
172       if (A->hasNoCaptureAttr())
173         return true;
174       return !AddressMightEscape(V);
175     }
176   return false;
177 }
178
179
180 /// isObjectSmallerThan - Return true if we can prove that the object specified
181 /// by V is smaller than Size.
182 static bool isObjectSmallerThan(const Value *V, unsigned Size,
183                                 const TargetData &TD) {
184   const Type *AccessTy;
185   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
186     AccessTy = GV->getType()->getElementType();
187   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
188     if (!AI->isArrayAllocation())
189       AccessTy = AI->getType()->getElementType();
190     else
191       return false;
192   } else if (const Argument *A = dyn_cast<Argument>(V)) {
193     if (A->hasByValAttr())
194       AccessTy = cast<PointerType>(A->getType())->getElementType();
195     else
196       return false;
197   } else {
198     return false;
199   }
200   
201   if (AccessTy->isSized())
202     return TD.getABITypeSize(AccessTy) < Size;
203   return false;
204 }
205
206 //===----------------------------------------------------------------------===//
207 // NoAA Pass
208 //===----------------------------------------------------------------------===//
209
210 namespace {
211   /// NoAA - This class implements the -no-aa pass, which always returns "I
212   /// don't know" for alias queries.  NoAA is unlike other alias analysis
213   /// implementations, in that it does not chain to a previous analysis.  As
214   /// such it doesn't follow many of the rules that other alias analyses must.
215   ///
216   struct VISIBILITY_HIDDEN NoAA : public ImmutablePass, public AliasAnalysis {
217     static char ID; // Class identification, replacement for typeinfo
218     NoAA() : ImmutablePass(&ID) {}
219     explicit NoAA(void *PID) : ImmutablePass(PID) { }
220
221     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
222       AU.addRequired<TargetData>();
223     }
224
225     virtual void initializePass() {
226       TD = &getAnalysis<TargetData>();
227     }
228
229     virtual AliasResult alias(const Value *V1, unsigned V1Size,
230                               const Value *V2, unsigned V2Size) {
231       return MayAlias;
232     }
233
234     virtual ModRefBehavior getModRefBehavior(Function *F, CallSite CS,
235                                          std::vector<PointerAccessInfo> *Info) {
236       return UnknownModRefBehavior;
237     }
238
239     virtual void getArgumentAccesses(Function *F, CallSite CS,
240                                      std::vector<PointerAccessInfo> &Info) {
241       assert(0 && "This method may not be called on this function!");
242     }
243
244     virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { }
245     virtual bool pointsToConstantMemory(const Value *P) { return false; }
246     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
247       return ModRef;
248     }
249     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
250       return ModRef;
251     }
252     virtual bool hasNoModRefInfoForCalls() const { return true; }
253
254     virtual void deleteValue(Value *V) {}
255     virtual void copyValue(Value *From, Value *To) {}
256   };
257 }  // End of anonymous namespace
258
259 // Register this pass...
260 char NoAA::ID = 0;
261 static RegisterPass<NoAA>
262 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
263
264 // Declare that we implement the AliasAnalysis interface
265 static RegisterAnalysisGroup<AliasAnalysis> V(U);
266
267 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
268
269 //===----------------------------------------------------------------------===//
270 // BasicAA Pass
271 //===----------------------------------------------------------------------===//
272
273 namespace {
274   /// BasicAliasAnalysis - This is the default alias analysis implementation.
275   /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
276   /// derives from the NoAA class.
277   struct VISIBILITY_HIDDEN BasicAliasAnalysis : public NoAA {
278     static char ID; // Class identification, replacement for typeinfo
279     BasicAliasAnalysis() : NoAA(&ID) {}
280     AliasResult alias(const Value *V1, unsigned V1Size,
281                       const Value *V2, unsigned V2Size);
282
283     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
284     ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
285     
286     /// hasNoModRefInfoForCalls - We can provide mod/ref information against
287     /// non-escaping allocations.
288     virtual bool hasNoModRefInfoForCalls() const { return false; }
289
290     /// pointsToConstantMemory - Chase pointers until we find a (constant
291     /// global) or not.
292     bool pointsToConstantMemory(const Value *P);
293
294   private:
295     // CheckGEPInstructions - Check two GEP instructions with known
296     // must-aliasing base pointers.  This checks to see if the index expressions
297     // preclude the pointers from aliasing...
298     AliasResult
299     CheckGEPInstructions(const Type* BasePtr1Ty,
300                          Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
301                          const Type *BasePtr2Ty,
302                          Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
303   };
304 }  // End of anonymous namespace
305
306 // Register this pass...
307 char BasicAliasAnalysis::ID = 0;
308 static RegisterPass<BasicAliasAnalysis>
309 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
310
311 // Declare that we implement the AliasAnalysis interface
312 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
313
314 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
315   return new BasicAliasAnalysis();
316 }
317
318
319 /// pointsToConstantMemory - Chase pointers until we find a (constant
320 /// global) or not.
321 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
322   if (const GlobalVariable *GV = 
323         dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
324     return GV->isConstant();
325   return false;
326 }
327
328 // getModRefInfo - Check to see if the specified callsite can clobber the
329 // specified memory object.  Since we only look at local properties of this
330 // function, we really can't say much about this query.  We do, however, use
331 // simple "address taken" analysis on local objects.
332 //
333 AliasAnalysis::ModRefResult
334 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
335   if (!isa<Constant>(P)) {
336     const Value *Object = P->getUnderlyingObject();
337     
338     // If this is a tail call and P points to a stack location, we know that
339     // the tail call cannot access or modify the local stack.
340     // We cannot exclude byval arguments here; these belong to the caller of
341     // the current function not to the current function, and a tail callee
342     // may reference them.
343     if (isa<AllocaInst>(Object))
344       if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
345         if (CI->isTailCall())
346           return NoModRef;
347     
348     // If the pointer is to a locally allocated object that does not escape,
349     // then the call can not mod/ref the pointer unless the call takes the
350     // argument without capturing it.
351     if (isNonEscapingLocalObject(Object)) {
352       bool passedAsArg = false;
353       // TODO: Eventually only check 'nocapture' arguments.
354       for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
355            CI != CE; ++CI)
356         if (isa<PointerType>((*CI)->getType()) &&
357             alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias)
358           passedAsArg = true;
359       
360       if (!passedAsArg)
361         return NoModRef;
362     }
363   }
364
365   // The AliasAnalysis base class has some smarts, lets use them.
366   return AliasAnalysis::getModRefInfo(CS, P, Size);
367 }
368
369
370 AliasAnalysis::ModRefResult 
371 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
372   // If CS1 or CS2 are readnone, they don't interact.
373   ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
374   if (CS1B == DoesNotAccessMemory) return NoModRef;
375   
376   ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
377   if (CS2B == DoesNotAccessMemory) return NoModRef;
378   
379   // If they both only read from memory, just return ref.
380   if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
381     return Ref;
382   
383   // Otherwise, fall back to NoAA (mod+ref).
384   return NoAA::getModRefInfo(CS1, CS2);
385 }
386
387
388 // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such
389 // as array references.
390 //
391 AliasAnalysis::AliasResult
392 BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size,
393                           const Value *V2, unsigned V2Size) {
394   // Strip off any constant expression casts if they exist
395   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V1))
396     if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
397       V1 = CE->getOperand(0);
398   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V2))
399     if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
400       V2 = CE->getOperand(0);
401
402   // Are we checking for alias of the same value?
403   if (V1 == V2) return MustAlias;
404
405   if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
406     return NoAlias;  // Scalars cannot alias each other
407
408   // Strip off cast instructions.   Since V1 and V2 are pointers, they must be
409   // pointer<->pointer bitcasts.
410   if (const BitCastInst *I = dyn_cast<BitCastInst>(V1))
411     return alias(I->getOperand(0), V1Size, V2, V2Size);
412   if (const BitCastInst *I = dyn_cast<BitCastInst>(V2))
413     return alias(V1, V1Size, I->getOperand(0), V2Size);
414
415   // Figure out what objects these things are pointing to if we can.
416   const Value *O1 = V1->getUnderlyingObject();
417   const Value *O2 = V2->getUnderlyingObject();
418
419   if (O1 != O2) {
420     // If V1/V2 point to two different objects we know that we have no alias.
421     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
422       return NoAlias;
423   
424     // Arguments can't alias with local allocations or noalias calls.
425     if ((isa<Argument>(O1) && (isa<AllocationInst>(O2) || isNoAliasCall(O2))) ||
426         (isa<Argument>(O2) && (isa<AllocationInst>(O1) || isNoAliasCall(O1))))
427       return NoAlias;
428
429     // Most objects can't alias null.
430     if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
431         (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
432       return NoAlias;
433   }
434   
435   // If the size of one access is larger than the entire object on the other
436   // side, then we know such behavior is undefined and can assume no alias.
437   const TargetData &TD = getTargetData();
438   if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, TD)) ||
439       (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, TD)))
440     return NoAlias;
441   
442   // If one pointer is the result of a call/invoke and the other is a
443   // non-escaping local object, then we know the object couldn't escape to a
444   // point where the call could return it.
445   if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) &&
446       isNonEscapingLocalObject(O2))
447     return NoAlias;
448   if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) &&
449       isNonEscapingLocalObject(O1))
450     return NoAlias;
451   
452   // If we have two gep instructions with must-alias'ing base pointers, figure
453   // out if the indexes to the GEP tell us anything about the derived pointer.
454   // Note that we also handle chains of getelementptr instructions as well as
455   // constant expression getelementptrs here.
456   //
457   if (isGEP(V1) && isGEP(V2)) {
458     const User *GEP1 = cast<User>(V1);
459     const User *GEP2 = cast<User>(V2);
460     
461     // If V1 and V2 are identical GEPs, just recurse down on both of them.
462     // This allows us to analyze things like:
463     //   P = gep A, 0, i, 1
464     //   Q = gep B, 0, i, 1
465     // by just analyzing A and B.  This is even safe for variable indices.
466     if (GEP1->getType() == GEP2->getType() &&
467         GEP1->getNumOperands() == GEP2->getNumOperands() &&
468         GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
469         // All operands are the same, ignoring the base.
470         std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
471       return alias(GEP1->getOperand(0), V1Size, GEP2->getOperand(0), V2Size);
472     
473     
474     // Drill down into the first non-gep value, to test for must-aliasing of
475     // the base pointers.
476     while (isGEP(GEP1->getOperand(0)) &&
477            GEP1->getOperand(1) ==
478            Constant::getNullValue(GEP1->getOperand(1)->getType()))
479       GEP1 = cast<User>(GEP1->getOperand(0));
480     const Value *BasePtr1 = GEP1->getOperand(0);
481
482     while (isGEP(GEP2->getOperand(0)) &&
483            GEP2->getOperand(1) ==
484            Constant::getNullValue(GEP2->getOperand(1)->getType()))
485       GEP2 = cast<User>(GEP2->getOperand(0));
486     const Value *BasePtr2 = GEP2->getOperand(0);
487
488     // Do the base pointers alias?
489     AliasResult BaseAlias = alias(BasePtr1, ~0U, BasePtr2, ~0U);
490     if (BaseAlias == NoAlias) return NoAlias;
491     if (BaseAlias == MustAlias) {
492       // If the base pointers alias each other exactly, check to see if we can
493       // figure out anything about the resultant pointers, to try to prove
494       // non-aliasing.
495
496       // Collect all of the chained GEP operands together into one simple place
497       SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
498       BasePtr1 = GetGEPOperands(V1, GEP1Ops);
499       BasePtr2 = GetGEPOperands(V2, GEP2Ops);
500
501       // If GetGEPOperands were able to fold to the same must-aliased pointer,
502       // do the comparison.
503       if (BasePtr1 == BasePtr2) {
504         AliasResult GAlias =
505           CheckGEPInstructions(BasePtr1->getType(),
506                                &GEP1Ops[0], GEP1Ops.size(), V1Size,
507                                BasePtr2->getType(),
508                                &GEP2Ops[0], GEP2Ops.size(), V2Size);
509         if (GAlias != MayAlias)
510           return GAlias;
511       }
512     }
513   }
514
515   // Check to see if these two pointers are related by a getelementptr
516   // instruction.  If one pointer is a GEP with a non-zero index of the other
517   // pointer, we know they cannot alias.
518   //
519   if (isGEP(V2)) {
520     std::swap(V1, V2);
521     std::swap(V1Size, V2Size);
522   }
523
524   if (V1Size != ~0U && V2Size != ~0U)
525     if (isGEP(V1)) {
526       SmallVector<Value*, 16> GEPOperands;
527       const Value *BasePtr = GetGEPOperands(V1, GEPOperands);
528
529       AliasResult R = alias(BasePtr, V1Size, V2, V2Size);
530       if (R == MustAlias) {
531         // If there is at least one non-zero constant index, we know they cannot
532         // alias.
533         bool ConstantFound = false;
534         bool AllZerosFound = true;
535         for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i)
536           if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) {
537             if (!C->isNullValue()) {
538               ConstantFound = true;
539               AllZerosFound = false;
540               break;
541             }
542           } else {
543             AllZerosFound = false;
544           }
545
546         // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
547         // the ptr, the end result is a must alias also.
548         if (AllZerosFound)
549           return MustAlias;
550
551         if (ConstantFound) {
552           if (V2Size <= 1 && V1Size <= 1)  // Just pointer check?
553             return NoAlias;
554
555           // Otherwise we have to check to see that the distance is more than
556           // the size of the argument... build an index vector that is equal to
557           // the arguments provided, except substitute 0's for any variable
558           // indexes we find...
559           if (cast<PointerType>(
560                 BasePtr->getType())->getElementType()->isSized()) {
561             for (unsigned i = 0; i != GEPOperands.size(); ++i)
562               if (!isa<ConstantInt>(GEPOperands[i]))
563                 GEPOperands[i] =
564                   Constant::getNullValue(GEPOperands[i]->getType());
565             int64_t Offset =
566               getTargetData().getIndexedOffset(BasePtr->getType(),
567                                                &GEPOperands[0],
568                                                GEPOperands.size());
569
570             if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size)
571               return NoAlias;
572           }
573         }
574       }
575     }
576
577   return MayAlias;
578 }
579
580 // This function is used to determine if the indices of two GEP instructions are
581 // equal. V1 and V2 are the indices.
582 static bool IndexOperandsEqual(Value *V1, Value *V2) {
583   if (V1->getType() == V2->getType())
584     return V1 == V2;
585   if (Constant *C1 = dyn_cast<Constant>(V1))
586     if (Constant *C2 = dyn_cast<Constant>(V2)) {
587       // Sign extend the constants to long types, if necessary
588       if (C1->getType() != Type::Int64Ty)
589         C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
590       if (C2->getType() != Type::Int64Ty) 
591         C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
592       return C1 == C2;
593     }
594   return false;
595 }
596
597 /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
598 /// base pointers.  This checks to see if the index expressions preclude the
599 /// pointers from aliasing...
600 AliasAnalysis::AliasResult 
601 BasicAliasAnalysis::CheckGEPInstructions(
602   const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
603   const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
604   // We currently can't handle the case when the base pointers have different
605   // primitive types.  Since this is uncommon anyway, we are happy being
606   // extremely conservative.
607   if (BasePtr1Ty != BasePtr2Ty)
608     return MayAlias;
609
610   const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
611
612   // Find the (possibly empty) initial sequence of equal values... which are not
613   // necessarily constants.
614   unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
615   unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
616   unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
617   unsigned UnequalOper = 0;
618   while (UnequalOper != MinOperands &&
619          IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) {
620     // Advance through the type as we go...
621     ++UnequalOper;
622     if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
623       BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
624     else {
625       // If all operands equal each other, then the derived pointers must
626       // alias each other...
627       BasePtr1Ty = 0;
628       assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
629              "Ran out of type nesting, but not out of operands?");
630       return MustAlias;
631     }
632   }
633
634   // If we have seen all constant operands, and run out of indexes on one of the
635   // getelementptrs, check to see if the tail of the leftover one is all zeros.
636   // If so, return mustalias.
637   if (UnequalOper == MinOperands) {
638     if (NumGEP1Ops < NumGEP2Ops) {
639       std::swap(GEP1Ops, GEP2Ops);
640       std::swap(NumGEP1Ops, NumGEP2Ops);
641     }
642
643     bool AllAreZeros = true;
644     for (unsigned i = UnequalOper; i != MaxOperands; ++i)
645       if (!isa<Constant>(GEP1Ops[i]) ||
646           !cast<Constant>(GEP1Ops[i])->isNullValue()) {
647         AllAreZeros = false;
648         break;
649       }
650     if (AllAreZeros) return MustAlias;
651   }
652
653
654   // So now we know that the indexes derived from the base pointers,
655   // which are known to alias, are different.  We can still determine a
656   // no-alias result if there are differing constant pairs in the index
657   // chain.  For example:
658   //        A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
659   //
660   // We have to be careful here about array accesses.  In particular, consider:
661   //        A[1][0] vs A[0][i]
662   // In this case, we don't *know* that the array will be accessed in bounds:
663   // the index could even be negative.  Because of this, we have to
664   // conservatively *give up* and return may alias.  We disregard differing
665   // array subscripts that are followed by a variable index without going
666   // through a struct.
667   //
668   unsigned SizeMax = std::max(G1S, G2S);
669   if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
670
671   // Scan for the first operand that is constant and unequal in the
672   // two getelementptrs...
673   unsigned FirstConstantOper = UnequalOper;
674   for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
675     const Value *G1Oper = GEP1Ops[FirstConstantOper];
676     const Value *G2Oper = GEP2Ops[FirstConstantOper];
677
678     if (G1Oper != G2Oper)   // Found non-equal constant indexes...
679       if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
680         if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
681           if (G1OC->getType() != G2OC->getType()) {
682             // Sign extend both operands to long.
683             if (G1OC->getType() != Type::Int64Ty)
684               G1OC = ConstantExpr::getSExt(G1OC, Type::Int64Ty);
685             if (G2OC->getType() != Type::Int64Ty) 
686               G2OC = ConstantExpr::getSExt(G2OC, Type::Int64Ty);
687             GEP1Ops[FirstConstantOper] = G1OC;
688             GEP2Ops[FirstConstantOper] = G2OC;
689           }
690           
691           if (G1OC != G2OC) {
692             // Handle the "be careful" case above: if this is an array/vector
693             // subscript, scan for a subsequent variable array index.
694             if (isa<SequentialType>(BasePtr1Ty))  {
695               const Type *NextTy =
696                 cast<SequentialType>(BasePtr1Ty)->getElementType();
697               bool isBadCase = false;
698               
699               for (unsigned Idx = FirstConstantOper+1;
700                    Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
701                 const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
702                 if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
703                   isBadCase = true;
704                   break;
705                 }
706                 NextTy = cast<SequentialType>(NextTy)->getElementType();
707               }
708               
709               if (isBadCase) G1OC = 0;
710             }
711
712             // Make sure they are comparable (ie, not constant expressions), and
713             // make sure the GEP with the smaller leading constant is GEP1.
714             if (G1OC) {
715               Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT, 
716                                                         G1OC, G2OC);
717               if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
718                 if (CV->getZExtValue()) {  // If they are comparable and G2 > G1
719                   std::swap(GEP1Ops, GEP2Ops);  // Make GEP1 < GEP2
720                   std::swap(NumGEP1Ops, NumGEP2Ops);
721                 }
722                 break;
723               }
724             }
725           }
726         }
727     BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
728   }
729
730   // No shared constant operands, and we ran out of common operands.  At this
731   // point, the GEP instructions have run through all of their operands, and we
732   // haven't found evidence that there are any deltas between the GEP's.
733   // However, one GEP may have more operands than the other.  If this is the
734   // case, there may still be hope.  Check this now.
735   if (FirstConstantOper == MinOperands) {
736     // Make GEP1Ops be the longer one if there is a longer one.
737     if (NumGEP1Ops < NumGEP2Ops) {
738       std::swap(GEP1Ops, GEP2Ops);
739       std::swap(NumGEP1Ops, NumGEP2Ops);
740     }
741
742     // Is there anything to check?
743     if (NumGEP1Ops > MinOperands) {
744       for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
745         if (isa<ConstantInt>(GEP1Ops[i]) && 
746             !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
747           // Yup, there's a constant in the tail.  Set all variables to
748           // constants in the GEP instruction to make it suitable for
749           // TargetData::getIndexedOffset.
750           for (i = 0; i != MaxOperands; ++i)
751             if (!isa<ConstantInt>(GEP1Ops[i]))
752               GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
753           // Okay, now get the offset.  This is the relative offset for the full
754           // instruction.
755           const TargetData &TD = getTargetData();
756           int64_t Offset1 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops,
757                                                 NumGEP1Ops);
758
759           // Now check without any constants at the end.
760           int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops,
761                                                 MinOperands);
762
763           // Make sure we compare the absolute difference.
764           if (Offset1 > Offset2)
765             std::swap(Offset1, Offset2);
766
767           // If the tail provided a bit enough offset, return noalias!
768           if ((uint64_t)(Offset2-Offset1) >= SizeMax)
769             return NoAlias;
770           // Otherwise break - we don't look for another constant in the tail.
771           break;
772         }
773     }
774
775     // Couldn't find anything useful.
776     return MayAlias;
777   }
778
779   // If there are non-equal constants arguments, then we can figure
780   // out a minimum known delta between the two index expressions... at
781   // this point we know that the first constant index of GEP1 is less
782   // than the first constant index of GEP2.
783
784   // Advance BasePtr[12]Ty over this first differing constant operand.
785   BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
786       getTypeAtIndex(GEP2Ops[FirstConstantOper]);
787   BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
788       getTypeAtIndex(GEP1Ops[FirstConstantOper]);
789
790   // We are going to be using TargetData::getIndexedOffset to determine the
791   // offset that each of the GEP's is reaching.  To do this, we have to convert
792   // all variable references to constant references.  To do this, we convert the
793   // initial sequence of array subscripts into constant zeros to start with.
794   const Type *ZeroIdxTy = GEPPointerTy;
795   for (unsigned i = 0; i != FirstConstantOper; ++i) {
796     if (!isa<StructType>(ZeroIdxTy))
797       GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Type::Int32Ty);
798
799     if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
800       ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
801   }
802
803   // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
804
805   // Loop over the rest of the operands...
806   for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
807     const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
808     const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
809     // If they are equal, use a zero index...
810     if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
811       if (!isa<ConstantInt>(Op1))
812         GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
813       // Otherwise, just keep the constants we have.
814     } else {
815       if (Op1) {
816         if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
817           // If this is an array index, make sure the array element is in range.
818           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
819             if (Op1C->getZExtValue() >= AT->getNumElements())
820               return MayAlias;  // Be conservative with out-of-range accesses
821           } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
822             if (Op1C->getZExtValue() >= VT->getNumElements())
823               return MayAlias;  // Be conservative with out-of-range accesses
824           }
825           
826         } else {
827           // GEP1 is known to produce a value less than GEP2.  To be
828           // conservatively correct, we must assume the largest possible
829           // constant is used in this position.  This cannot be the initial
830           // index to the GEP instructions (because we know we have at least one
831           // element before this one with the different constant arguments), so
832           // we know that the current index must be into either a struct or
833           // array.  Because we know it's not constant, this cannot be a
834           // structure index.  Because of this, we can calculate the maximum
835           // value possible.
836           //
837           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
838             GEP1Ops[i] = ConstantInt::get(Type::Int64Ty,AT->getNumElements()-1);
839           else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
840             GEP1Ops[i] = ConstantInt::get(Type::Int64Ty,VT->getNumElements()-1);
841         }
842       }
843
844       if (Op2) {
845         if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
846           // If this is an array index, make sure the array element is in range.
847           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
848             if (Op2C->getZExtValue() >= AT->getNumElements())
849               return MayAlias;  // Be conservative with out-of-range accesses
850           } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
851             if (Op2C->getZExtValue() >= VT->getNumElements())
852               return MayAlias;  // Be conservative with out-of-range accesses
853           }
854         } else {  // Conservatively assume the minimum value for this index
855           GEP2Ops[i] = Constant::getNullValue(Op2->getType());
856         }
857       }
858     }
859
860     if (BasePtr1Ty && Op1) {
861       if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
862         BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
863       else
864         BasePtr1Ty = 0;
865     }
866
867     if (BasePtr2Ty && Op2) {
868       if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
869         BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
870       else
871         BasePtr2Ty = 0;
872     }
873   }
874
875   if (GEPPointerTy->getElementType()->isSized()) {
876     int64_t Offset1 =
877       getTargetData().getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
878     int64_t Offset2 = 
879       getTargetData().getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
880     assert(Offset1 != Offset2 &&
881            "There is at least one different constant here!");
882     
883     // Make sure we compare the absolute difference.
884     if (Offset1 > Offset2)
885       std::swap(Offset1, Offset2);
886     
887     if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
888       //cerr << "Determined that these two GEP's don't alias ["
889       //     << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
890       return NoAlias;
891     }
892   }
893   return MayAlias;
894 }
895
896 // Make sure that anything that uses AliasAnalysis pulls in this file...
897 DEFINING_FILE_FOR(BasicAliasAnalysis)