Generalize DecomposeGEPExpression to exactly handle what Value::getUnderlyingObject...
[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/CaptureTracking.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include <algorithm>
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 // Useful predicates
40 //===----------------------------------------------------------------------===//
41
42 static const Value *GetGEPOperands(const GEPOperator *V, 
43                                    SmallVector<Value*, 16> &GEPOps) {
44   assert(GEPOps.empty() && "Expect empty list to populate!");
45   GEPOps.insert(GEPOps.end(), V->op_begin()+1, V->op_end());
46
47   // Accumulate all of the chained indexes into the operand array.
48   Value *BasePtr = V->getOperand(0);
49   while (1) {
50     V = dyn_cast<GEPOperator>(BasePtr);
51     if (V == 0) return BasePtr;
52     
53     // Don't handle folding arbitrary pointer offsets yet.
54     if (!isa<Constant>(GEPOps[0]) || !cast<Constant>(GEPOps[0])->isNullValue())
55       return BasePtr;
56     
57     GEPOps.erase(GEPOps.begin());   // Drop the zero index
58     GEPOps.insert(GEPOps.begin(), V->op_begin()+1, V->op_end());
59   }
60 }
61
62 /// isKnownNonNull - Return true if we know that the specified value is never
63 /// null.
64 static bool isKnownNonNull(const Value *V) {
65   // Alloca never returns null, malloc might.
66   if (isa<AllocaInst>(V)) return true;
67   
68   // A byval argument is never null.
69   if (const Argument *A = dyn_cast<Argument>(V))
70     return A->hasByValAttr();
71
72   // Global values are not null unless extern weak.
73   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
74     return !GV->hasExternalWeakLinkage();
75   return false;
76 }
77
78 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
79 /// object that never escapes from the function.
80 static bool isNonEscapingLocalObject(const Value *V) {
81   // If this is a local allocation, check to see if it escapes.
82   if (isa<AllocaInst>(V) || isNoAliasCall(V))
83     // Set StoreCaptures to True so that we can assume in our callers that the
84     // pointer is not the result of a load instruction. Currently
85     // PointerMayBeCaptured doesn't have any special analysis for the
86     // StoreCaptures=false case; if it did, our callers could be refined to be
87     // more precise.
88     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
89
90   // If this is an argument that corresponds to a byval or noalias argument,
91   // then it has not escaped before entering the function.  Check if it escapes
92   // inside the function.
93   if (const Argument *A = dyn_cast<Argument>(V))
94     if (A->hasByValAttr() || A->hasNoAliasAttr()) {
95       // Don't bother analyzing arguments already known not to escape.
96       if (A->hasNoCaptureAttr())
97         return true;
98       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
99     }
100   return false;
101 }
102
103
104 /// isObjectSmallerThan - Return true if we can prove that the object specified
105 /// by V is smaller than Size.
106 static bool isObjectSmallerThan(const Value *V, unsigned Size,
107                                 const TargetData &TD) {
108   const Type *AccessTy;
109   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
110     AccessTy = GV->getType()->getElementType();
111   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
112     if (!AI->isArrayAllocation())
113       AccessTy = AI->getType()->getElementType();
114     else
115       return false;
116   } else if (const CallInst* CI = extractMallocCall(V)) {
117     if (!isArrayMalloc(V, &TD))
118       // The size is the argument to the malloc call.
119       if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
120         return (C->getZExtValue() < Size);
121     return false;
122   } else if (const Argument *A = dyn_cast<Argument>(V)) {
123     if (A->hasByValAttr())
124       AccessTy = cast<PointerType>(A->getType())->getElementType();
125     else
126       return false;
127   } else {
128     return false;
129   }
130   
131   if (AccessTy->isSized())
132     return TD.getTypeAllocSize(AccessTy) < Size;
133   return false;
134 }
135
136 //===----------------------------------------------------------------------===//
137 // NoAA Pass
138 //===----------------------------------------------------------------------===//
139
140 namespace {
141   /// NoAA - This class implements the -no-aa pass, which always returns "I
142   /// don't know" for alias queries.  NoAA is unlike other alias analysis
143   /// implementations, in that it does not chain to a previous analysis.  As
144   /// such it doesn't follow many of the rules that other alias analyses must.
145   ///
146   struct NoAA : public ImmutablePass, public AliasAnalysis {
147     static char ID; // Class identification, replacement for typeinfo
148     NoAA() : ImmutablePass(&ID) {}
149     explicit NoAA(void *PID) : ImmutablePass(PID) { }
150
151     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152     }
153
154     virtual void initializePass() {
155       TD = getAnalysisIfAvailable<TargetData>();
156     }
157
158     virtual AliasResult alias(const Value *V1, unsigned V1Size,
159                               const Value *V2, unsigned V2Size) {
160       return MayAlias;
161     }
162
163     virtual void getArgumentAccesses(Function *F, CallSite CS,
164                                      std::vector<PointerAccessInfo> &Info) {
165       llvm_unreachable("This method may not be called on this function!");
166     }
167
168     virtual bool pointsToConstantMemory(const Value *P) { return false; }
169     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
170       return ModRef;
171     }
172     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
173       return ModRef;
174     }
175
176     virtual void deleteValue(Value *V) {}
177     virtual void copyValue(Value *From, Value *To) {}
178   };
179 }  // End of anonymous namespace
180
181 // Register this pass...
182 char NoAA::ID = 0;
183 static RegisterPass<NoAA>
184 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
185
186 // Declare that we implement the AliasAnalysis interface
187 static RegisterAnalysisGroup<AliasAnalysis> V(U);
188
189 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
190
191 //===----------------------------------------------------------------------===//
192 // BasicAA Pass
193 //===----------------------------------------------------------------------===//
194
195 namespace {
196   /// BasicAliasAnalysis - This is the default alias analysis implementation.
197   /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
198   /// derives from the NoAA class.
199   struct BasicAliasAnalysis : public NoAA {
200     static char ID; // Class identification, replacement for typeinfo
201     BasicAliasAnalysis() : NoAA(&ID) {}
202     AliasResult alias(const Value *V1, unsigned V1Size,
203                       const Value *V2, unsigned V2Size) {
204       assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
205       AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
206       VisitedPHIs.clear();
207       return Alias;
208     }
209
210     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
211     ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
212
213     /// pointsToConstantMemory - Chase pointers until we find a (constant
214     /// global) or not.
215     bool pointsToConstantMemory(const Value *P);
216
217   private:
218     // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
219     SmallPtrSet<const Value*, 16> VisitedPHIs;
220
221     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
222     // instruction against another.
223     AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
224                          const Value *V2, unsigned V2Size,
225                          const Value *UnderlyingV1, const Value *UnderlyingV2);
226
227     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
228     // instruction against another.
229     AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
230                          const Value *V2, unsigned V2Size);
231
232     /// aliasSelect - Disambiguate a Select instruction against another value.
233     AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
234                             const Value *V2, unsigned V2Size);
235
236     AliasResult aliasCheck(const Value *V1, unsigned V1Size,
237                            const Value *V2, unsigned V2Size);
238
239     // CheckGEPInstructions - Check two GEP instructions with known
240     // must-aliasing base pointers.  This checks to see if the index expressions
241     // preclude the pointers from aliasing.
242     AliasResult
243     CheckGEPInstructions(const Type* BasePtr1Ty,
244                          Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
245                          const Type *BasePtr2Ty,
246                          Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
247   };
248 }  // End of anonymous namespace
249
250 // Register this pass...
251 char BasicAliasAnalysis::ID = 0;
252 static RegisterPass<BasicAliasAnalysis>
253 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
254
255 // Declare that we implement the AliasAnalysis interface
256 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
257
258 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
259   return new BasicAliasAnalysis();
260 }
261
262
263 /// pointsToConstantMemory - Chase pointers until we find a (constant
264 /// global) or not.
265 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
266   if (const GlobalVariable *GV = 
267         dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
268     // Note: this doesn't require GV to be "ODR" because it isn't legal for a
269     // global to be marked constant in some modules and non-constant in others.
270     // GV may even be a declaration, not a definition.
271     return GV->isConstant();
272   return false;
273 }
274
275
276 /// getModRefInfo - Check to see if the specified callsite can clobber the
277 /// specified memory object.  Since we only look at local properties of this
278 /// function, we really can't say much about this query.  We do, however, use
279 /// simple "address taken" analysis on local objects.
280 AliasAnalysis::ModRefResult
281 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
282   const Value *Object = P->getUnderlyingObject();
283   
284   // If this is a tail call and P points to a stack location, we know that
285   // the tail call cannot access or modify the local stack.
286   // We cannot exclude byval arguments here; these belong to the caller of
287   // the current function not to the current function, and a tail callee
288   // may reference them.
289   if (isa<AllocaInst>(Object))
290     if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
291       if (CI->isTailCall())
292         return NoModRef;
293   
294   // If the pointer is to a locally allocated object that does not escape,
295   // then the call can not mod/ref the pointer unless the call takes the pointer
296   // as an argument, and itself doesn't capture it.
297   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
298       isNonEscapingLocalObject(Object)) {
299     bool PassedAsArg = false;
300     unsigned ArgNo = 0;
301     for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
302          CI != CE; ++CI, ++ArgNo) {
303       // Only look at the no-capture pointer arguments.
304       if (!isa<PointerType>((*CI)->getType()) ||
305           !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
306         continue;
307       
308       // If  this is a no-capture pointer argument, see if we can tell that it
309       // is impossible to alias the pointer we're checking.  If not, we have to
310       // assume that the call could touch the pointer, even though it doesn't
311       // escape.
312       if (!isNoAlias(cast<Value>(CI), ~0U, P, ~0U)) {
313         PassedAsArg = true;
314         break;
315       }
316     }
317     
318     if (!PassedAsArg)
319       return NoModRef;
320   }
321
322   // Finally, handle specific knowledge of intrinsics.
323   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
324   if (II == 0)
325     return AliasAnalysis::getModRefInfo(CS, P, Size);
326
327   switch (II->getIntrinsicID()) {
328   default: break;
329   case Intrinsic::memcpy:
330   case Intrinsic::memmove: {
331     unsigned Len = ~0U;
332     if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
333       Len = LenCI->getZExtValue();
334     Value *Dest = II->getOperand(1);
335     Value *Src = II->getOperand(2);
336     if (isNoAlias(Dest, Len, P, Size)) {
337       if (isNoAlias(Src, Len, P, Size))
338         return NoModRef;
339       return Ref;
340     }
341     break;
342   }
343   case Intrinsic::memset:
344     // Since memset is 'accesses arguments' only, the AliasAnalysis base class
345     // will handle it for the variable length case.
346     if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
347       unsigned Len = LenCI->getZExtValue();
348       Value *Dest = II->getOperand(1);
349       if (isNoAlias(Dest, Len, P, Size))
350         return NoModRef;
351     }
352     break;
353   case Intrinsic::atomic_cmp_swap:
354   case Intrinsic::atomic_swap:
355   case Intrinsic::atomic_load_add:
356   case Intrinsic::atomic_load_sub:
357   case Intrinsic::atomic_load_and:
358   case Intrinsic::atomic_load_nand:
359   case Intrinsic::atomic_load_or:
360   case Intrinsic::atomic_load_xor:
361   case Intrinsic::atomic_load_max:
362   case Intrinsic::atomic_load_min:
363   case Intrinsic::atomic_load_umax:
364   case Intrinsic::atomic_load_umin:
365     if (TD) {
366       Value *Op1 = II->getOperand(1);
367       unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
368       if (isNoAlias(Op1, Op1Size, P, Size))
369         return NoModRef;
370     }
371     break;
372   case Intrinsic::lifetime_start:
373   case Intrinsic::lifetime_end:
374   case Intrinsic::invariant_start: {
375     unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
376     if (isNoAlias(II->getOperand(2), PtrSize, P, Size))
377       return NoModRef;
378     break;
379   }
380   case Intrinsic::invariant_end: {
381     unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
382     if (isNoAlias(II->getOperand(3), PtrSize, P, Size))
383       return NoModRef;
384     break;
385   }
386   }
387
388   // The AliasAnalysis base class has some smarts, lets use them.
389   return AliasAnalysis::getModRefInfo(CS, P, Size);
390 }
391
392
393 AliasAnalysis::ModRefResult 
394 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
395   // If CS1 or CS2 are readnone, they don't interact.
396   ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
397   if (CS1B == DoesNotAccessMemory) return NoModRef;
398   
399   ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
400   if (CS2B == DoesNotAccessMemory) return NoModRef;
401   
402   // If they both only read from memory, just return ref.
403   if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
404     return Ref;
405   
406   // Otherwise, fall back to NoAA (mod+ref).
407   return NoAA::getModRefInfo(CS1, CS2);
408 }
409
410 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
411 /// into a base pointer with a constant offset and a number of scaled symbolic
412 /// offsets.
413 ///
414 /// When TargetData is around, this function is capable of analyzing everything
415 /// that Value::getUnderlyingObject() can look through.  When not, it just looks
416 /// through pointer casts.
417 ///
418 /// FIXME: Move this out to ValueTracking.cpp
419 ///
420 static const Value *DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
421                SmallVectorImpl<std::pair<const Value*, uint64_t> > &VarIndices,
422                                            const TargetData *TD) {
423   // FIXME: Should limit depth like getUnderlyingObject?
424   BaseOffs = 0;
425   while (1) {
426     // See if this is a bitcast or GEP.
427     const Operator *Op = dyn_cast<Operator>(V);
428     if (Op == 0) {
429       // The only non-operator case we can handle are GlobalAliases.
430       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
431         if (!GA->mayBeOverridden()) {
432           V = GA->getAliasee();
433           continue;
434         }
435       }
436       return V;
437     }
438     
439     if (Op->getOpcode() == Instruction::BitCast) {
440       V = Op->getOperand(0);
441       continue;
442     }
443     
444     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
445     if (GEPOp == 0)
446       return V;
447     
448     // Don't attempt to analyze GEPs over unsized objects.
449     if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
450           ->getElementType()->isSized())
451       return V;
452
453     // If we are lacking TargetData information, we can't compute the offets of
454     // elements computed by GEPs.  However, we can handle bitcast equivalent
455     // GEPs.
456     if (!TD) {
457       if (!GEPOp->hasAllZeroIndices())
458         return V;
459       V = GEPOp->getOperand(0);
460       continue;
461     }
462     
463     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
464     gep_type_iterator GTI = gep_type_begin(GEPOp);
465     for (User::const_op_iterator I = next(GEPOp->op_begin()),
466          E = GEPOp->op_end(); I != E; ++I) {
467       Value *Index = *I;
468       // Compute the (potentially symbolic) offset in bytes for this index.
469       if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
470         // For a struct, add the member offset.
471         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
472         if (FieldNo == 0) continue;
473         
474         BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
475         continue;
476       }
477       
478       // For an array/pointer, add the element offset, explicitly scaled.
479       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
480         if (CIdx->isZero()) continue;
481         BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
482         continue;
483       }
484       
485       // TODO: Could handle linear expressions here like A[X+1], also A[X*4|1].
486       uint64_t Scale = TD->getTypeAllocSize(*GTI);
487       
488       // If we already had an occurrance of this index variable, merge this
489       // scale into it.  For example, we want to handle:
490       //   A[x][x] -> x*16 + x*4 -> x*20
491       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
492         if (VarIndices[i].first == Index) {
493           Scale += VarIndices[i].second;
494           VarIndices.erase(VarIndices.begin()+i);
495           break;
496         }
497       }
498       
499       // Make sure that we have a scale that makes sense for this target's
500       // pointer size.
501       if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
502         Scale <<= ShiftBits;
503         Scale >>= ShiftBits;
504       }
505       
506       if (Scale)
507         VarIndices.push_back(std::make_pair(Index, Scale));
508     }
509     
510     // Analyze the base pointer next.
511     V = GEPOp->getOperand(0);
512   }
513 }
514
515
516 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
517 /// against another pointer.  We know that V1 is a GEP, but we don't know
518 /// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
519 /// UnderlyingV2 is the same for V2.
520 ///
521 AliasAnalysis::AliasResult
522 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
523                              const Value *V2, unsigned V2Size,
524                              const Value *UnderlyingV1,
525                              const Value *UnderlyingV2) {
526   // If we have two gep instructions with must-alias'ing base pointers, figure
527   // out if the indexes to the GEP tell us anything about the derived pointer.
528   // Note that we also handle chains of getelementptr instructions as well as
529   // constant expression getelementptrs here.
530   //
531   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
532     // If V1 and V2 are identical GEPs, just recurse down on both of them.
533     // This allows us to analyze things like:
534     //   P = gep A, 0, i, 1
535     //   Q = gep B, 0, i, 1
536     // by just analyzing A and B.  This is even safe for variable indices.
537     if (GEP1->getType() == GEP2->getType() &&
538         GEP1->getNumOperands() == GEP2->getNumOperands() &&
539         GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
540         // All operands are the same, ignoring the base.
541         std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
542       return aliasCheck(GEP1->getOperand(0), V1Size,
543                         GEP2->getOperand(0), V2Size);
544     
545     // Drill down into the first non-gep value, to test for must-aliasing of
546     // the base pointers.
547     while (isa<GEPOperator>(GEP1->getOperand(0)) &&
548            GEP1->getOperand(1) ==
549            Constant::getNullValue(GEP1->getOperand(1)->getType()))
550       GEP1 = cast<GEPOperator>(GEP1->getOperand(0));
551     const Value *BasePtr1 = GEP1->getOperand(0);
552
553     while (isa<GEPOperator>(GEP2->getOperand(0)) &&
554            GEP2->getOperand(1) ==
555            Constant::getNullValue(GEP2->getOperand(1)->getType()))
556       GEP2 = cast<GEPOperator>(GEP2->getOperand(0));
557     const Value *BasePtr2 = GEP2->getOperand(0);
558
559     // Do the base pointers alias?
560     AliasResult BaseAlias = aliasCheck(BasePtr1, ~0U, BasePtr2, ~0U);
561     if (BaseAlias == NoAlias) return NoAlias;
562     if (BaseAlias == MustAlias) {
563       // If the base pointers alias each other exactly, check to see if we can
564       // figure out anything about the resultant pointers, to try to prove
565       // non-aliasing.
566
567       // Collect all of the chained GEP operands together into one simple place
568       SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
569       BasePtr1 = GetGEPOperands(GEP1, GEP1Ops);
570       BasePtr2 = GetGEPOperands(GEP2, GEP2Ops);
571
572       // If GetGEPOperands were able to fold to the same must-aliased pointer,
573       // do the comparison.
574       if (BasePtr1 == BasePtr2) {
575         AliasResult GAlias =
576           CheckGEPInstructions(BasePtr1->getType(),
577                                &GEP1Ops[0], GEP1Ops.size(), V1Size,
578                                BasePtr2->getType(),
579                                &GEP2Ops[0], GEP2Ops.size(), V2Size);
580         if (GAlias != MayAlias)
581           return GAlias;
582       }
583     }
584   }
585
586   // Check to see if these two pointers are related by a getelementptr
587   // instruction.  If one pointer is a GEP with a non-zero index of the other
588   // pointer, we know they cannot alias.
589   //
590   // FIXME: The check below only looks at the size of one of the pointers, not
591   // both, this may cause us to miss things.
592   if (V1Size == ~0U || V2Size == ~0U)
593     return MayAlias;
594
595   AliasResult R = aliasCheck(UnderlyingV1, ~0U, V2, V2Size);
596   if (R != MustAlias)
597     // If V2 may alias GEP base pointer, conservatively returns MayAlias.
598     // If V2 is known not to alias GEP base pointer, then the two values
599     // cannot alias per GEP semantics: "A pointer value formed from a
600     // getelementptr instruction is associated with the addresses associated
601     // with the first operand of the getelementptr".
602     return R;
603
604   int64_t GEP1BaseOffset;
605   SmallVector<std::pair<const Value*, uint64_t>, 4> VariableIndices;
606   const Value *GEP1BasePtr =
607     DecomposeGEPExpression(GEP1, GEP1BaseOffset, VariableIndices, TD);
608   
609   // If DecomposeGEPExpression isn't able to look all the way through the
610   // addressing operation, we must not have TD and this is too complex for us
611   // to handle without it.
612   if (GEP1BasePtr != UnderlyingV1) {
613     assert(TD == 0 &&
614            "DecomposeGEPExpression and getUnderlyingObject disagree!");
615     return MayAlias;
616   }
617   
618   // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
619   // the ptr, the end result is a must alias also.
620   if (GEP1BaseOffset == 0 && VariableIndices.empty())
621     return MustAlias;
622
623   // If we have a known constant offset, see if this offset is larger than the
624   // access size being queried.  If so, and if no variable indices can remove
625   // pieces of this constant, then we know we have a no-alias.  For example,
626   //   &A[100] != &A.
627   
628   // In order to handle cases like &A[100][i] where i is an out of range
629   // subscript, we have to ignore all constant offset pieces that are a multiple
630   // of a scaled index.  Do this by removing constant offsets that are a
631   // multiple of any of our variable indices.  This allows us to transform
632   // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
633   // provides an offset of 4 bytes (assuming a <= 4 byte access).
634   for (unsigned i = 0, e = VariableIndices.size(); i != e && GEP1BaseOffset;++i)
635     if (int64_t RemovedOffset = GEP1BaseOffset/VariableIndices[i].second)
636       GEP1BaseOffset -= RemovedOffset*VariableIndices[i].second;
637   
638   // If our known offset is bigger than the access size, we know we don't have
639   // an alias.
640   if (GEP1BaseOffset) {
641     if (GEP1BaseOffset >= (int64_t)V2Size ||
642         GEP1BaseOffset <= -(int64_t)V1Size)
643       return NoAlias;
644   }
645   
646   return MayAlias;
647 }
648
649 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
650 /// instruction against another.
651 AliasAnalysis::AliasResult
652 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
653                                 const Value *V2, unsigned V2Size) {
654   // If the values are Selects with the same condition, we can do a more precise
655   // check: just check for aliases between the values on corresponding arms.
656   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
657     if (SI->getCondition() == SI2->getCondition()) {
658       AliasResult Alias =
659         aliasCheck(SI->getTrueValue(), SISize,
660                    SI2->getTrueValue(), V2Size);
661       if (Alias == MayAlias)
662         return MayAlias;
663       AliasResult ThisAlias =
664         aliasCheck(SI->getFalseValue(), SISize,
665                    SI2->getFalseValue(), V2Size);
666       if (ThisAlias != Alias)
667         return MayAlias;
668       return Alias;
669     }
670
671   // If both arms of the Select node NoAlias or MustAlias V2, then returns
672   // NoAlias / MustAlias. Otherwise, returns MayAlias.
673   AliasResult Alias =
674     aliasCheck(SI->getTrueValue(), SISize, V2, V2Size);
675   if (Alias == MayAlias)
676     return MayAlias;
677   AliasResult ThisAlias =
678     aliasCheck(SI->getFalseValue(), SISize, V2, V2Size);
679   if (ThisAlias != Alias)
680     return MayAlias;
681   return Alias;
682 }
683
684 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
685 // against another.
686 AliasAnalysis::AliasResult
687 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
688                              const Value *V2, unsigned V2Size) {
689   // The PHI node has already been visited, avoid recursion any further.
690   if (!VisitedPHIs.insert(PN))
691     return MayAlias;
692
693   // If the values are PHIs in the same block, we can do a more precise
694   // as well as efficient check: just check for aliases between the values
695   // on corresponding edges.
696   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
697     if (PN2->getParent() == PN->getParent()) {
698       AliasResult Alias =
699         aliasCheck(PN->getIncomingValue(0), PNSize,
700                    PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
701                    V2Size);
702       if (Alias == MayAlias)
703         return MayAlias;
704       for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
705         AliasResult ThisAlias =
706           aliasCheck(PN->getIncomingValue(i), PNSize,
707                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
708                      V2Size);
709         if (ThisAlias != Alias)
710           return MayAlias;
711       }
712       return Alias;
713     }
714
715   SmallPtrSet<Value*, 4> UniqueSrc;
716   SmallVector<Value*, 4> V1Srcs;
717   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
718     Value *PV1 = PN->getIncomingValue(i);
719     if (isa<PHINode>(PV1))
720       // If any of the source itself is a PHI, return MayAlias conservatively
721       // to avoid compile time explosion. The worst possible case is if both
722       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
723       // and 'n' are the number of PHI sources.
724       return MayAlias;
725     if (UniqueSrc.insert(PV1))
726       V1Srcs.push_back(PV1);
727   }
728
729   AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
730   // Early exit if the check of the first PHI source against V2 is MayAlias.
731   // Other results are not possible.
732   if (Alias == MayAlias)
733     return MayAlias;
734
735   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
736   // NoAlias / MustAlias. Otherwise, returns MayAlias.
737   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
738     Value *V = V1Srcs[i];
739
740     // If V2 is a PHI, the recursive case will have been caught in the
741     // above aliasCheck call, so these subsequent calls to aliasCheck
742     // don't need to assume that V2 is being visited recursively.
743     VisitedPHIs.erase(V2);
744
745     AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
746     if (ThisAlias != Alias || ThisAlias == MayAlias)
747       return MayAlias;
748   }
749
750   return Alias;
751 }
752
753 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
754 // such as array references.
755 //
756 AliasAnalysis::AliasResult
757 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
758                                const Value *V2, unsigned V2Size) {
759   // Strip off any casts if they exist.
760   V1 = V1->stripPointerCasts();
761   V2 = V2->stripPointerCasts();
762
763   // Are we checking for alias of the same value?
764   if (V1 == V2) return MustAlias;
765
766   if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
767     return NoAlias;  // Scalars cannot alias each other
768
769   // Figure out what objects these things are pointing to if we can.
770   const Value *O1 = V1->getUnderlyingObject();
771   const Value *O2 = V2->getUnderlyingObject();
772
773   // Null values in the default address space don't point to any object, so they
774   // don't alias any other pointer.
775   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
776     if (CPN->getType()->getAddressSpace() == 0)
777       return NoAlias;
778   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
779     if (CPN->getType()->getAddressSpace() == 0)
780       return NoAlias;
781
782   if (O1 != O2) {
783     // If V1/V2 point to two different objects we know that we have no alias.
784     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
785       return NoAlias;
786
787     // Constant pointers can't alias with non-const isIdentifiedObject objects.
788     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
789         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
790       return NoAlias;
791
792     // Arguments can't alias with local allocations or noalias calls.
793     if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
794         (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
795       return NoAlias;
796
797     // Most objects can't alias null.
798     if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
799         (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
800       return NoAlias;
801   }
802   
803   // If the size of one access is larger than the entire object on the other
804   // side, then we know such behavior is undefined and can assume no alias.
805   if (TD)
806     if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
807         (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
808       return NoAlias;
809   
810   // If one pointer is the result of a call/invoke or load and the other is a
811   // non-escaping local object, then we know the object couldn't escape to a
812   // point where the call could return it. The load case works because
813   // isNonEscapingLocalObject considers all stores to be escapes (it
814   // passes true for the StoreCaptures argument to PointerMayBeCaptured).
815   if (O1 != O2) {
816     if ((isa<CallInst>(O1) || isa<InvokeInst>(O1) || isa<LoadInst>(O1) ||
817          isa<Argument>(O1)) &&
818         isNonEscapingLocalObject(O2))
819       return NoAlias;
820     if ((isa<CallInst>(O2) || isa<InvokeInst>(O2) || isa<LoadInst>(O2) ||
821          isa<Argument>(O2)) &&
822         isNonEscapingLocalObject(O1))
823       return NoAlias;
824   }
825
826   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
827   // GEP can't simplify, we don't even look at the PHI cases.
828   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
829     std::swap(V1, V2);
830     std::swap(V1Size, V2Size);
831     std::swap(O1, O2);
832   }
833   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
834     return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
835
836   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
837     std::swap(V1, V2);
838     std::swap(V1Size, V2Size);
839   }
840   if (const PHINode *PN = dyn_cast<PHINode>(V1))
841     return aliasPHI(PN, V1Size, V2, V2Size);
842
843   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
844     std::swap(V1, V2);
845     std::swap(V1Size, V2Size);
846   }
847   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
848     return aliasSelect(S1, V1Size, V2, V2Size);
849
850   return MayAlias;
851 }
852
853 // This function is used to determine if the indices of two GEP instructions are
854 // equal. V1 and V2 are the indices.
855 static bool IndexOperandsEqual(Value *V1, Value *V2) {
856   if (V1->getType() == V2->getType())
857     return V1 == V2;
858   if (Constant *C1 = dyn_cast<Constant>(V1))
859     if (Constant *C2 = dyn_cast<Constant>(V2)) {
860       // Sign extend the constants to long types, if necessary
861       if (C1->getType() != Type::getInt64Ty(C1->getContext()))
862         C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
863       if (C2->getType() != Type::getInt64Ty(C1->getContext())) 
864         C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
865       return C1 == C2;
866     }
867   return false;
868 }
869
870 /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
871 /// base pointers.  This checks to see if the index expressions preclude the
872 /// pointers from aliasing.
873 AliasAnalysis::AliasResult 
874 BasicAliasAnalysis::CheckGEPInstructions(
875   const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
876   const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
877   // We currently can't handle the case when the base pointers have different
878   // primitive types.  Since this is uncommon anyway, we are happy being
879   // extremely conservative.
880   if (BasePtr1Ty != BasePtr2Ty)
881     return MayAlias;
882
883   const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
884
885   // Find the (possibly empty) initial sequence of equal values... which are not
886   // necessarily constants.
887   unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
888   unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
889   unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
890   unsigned UnequalOper = 0;
891   while (UnequalOper != MinOperands &&
892          IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) {
893     // Advance through the type as we go...
894     ++UnequalOper;
895     if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
896       BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
897     else {
898       // If all operands equal each other, then the derived pointers must
899       // alias each other...
900       BasePtr1Ty = 0;
901       assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
902              "Ran out of type nesting, but not out of operands?");
903       return MustAlias;
904     }
905   }
906
907   // If we have seen all constant operands, and run out of indexes on one of the
908   // getelementptrs, check to see if the tail of the leftover one is all zeros.
909   // If so, return mustalias.
910   if (UnequalOper == MinOperands) {
911     if (NumGEP1Ops < NumGEP2Ops) {
912       std::swap(GEP1Ops, GEP2Ops);
913       std::swap(NumGEP1Ops, NumGEP2Ops);
914     }
915
916     bool AllAreZeros = true;
917     for (unsigned i = UnequalOper; i != MaxOperands; ++i)
918       if (!isa<Constant>(GEP1Ops[i]) ||
919           !cast<Constant>(GEP1Ops[i])->isNullValue()) {
920         AllAreZeros = false;
921         break;
922       }
923     if (AllAreZeros) return MustAlias;
924   }
925
926
927   // So now we know that the indexes derived from the base pointers,
928   // which are known to alias, are different.  We can still determine a
929   // no-alias result if there are differing constant pairs in the index
930   // chain.  For example:
931   //        A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
932   //
933   // We have to be careful here about array accesses.  In particular, consider:
934   //        A[1][0] vs A[0][i]
935   // In this case, we don't *know* that the array will be accessed in bounds:
936   // the index could even be negative.  Because of this, we have to
937   // conservatively *give up* and return may alias.  We disregard differing
938   // array subscripts that are followed by a variable index without going
939   // through a struct.
940   //
941   unsigned SizeMax = std::max(G1S, G2S);
942   if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
943
944   // Scan for the first operand that is constant and unequal in the
945   // two getelementptrs...
946   unsigned FirstConstantOper = UnequalOper;
947   for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
948     const Value *G1Oper = GEP1Ops[FirstConstantOper];
949     const Value *G2Oper = GEP2Ops[FirstConstantOper];
950
951     if (G1Oper != G2Oper)   // Found non-equal constant indexes...
952       if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
953         if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
954           if (G1OC->getType() != G2OC->getType()) {
955             // Sign extend both operands to long.
956             const Type *Int64Ty = Type::getInt64Ty(G1OC->getContext());
957             if (G1OC->getType() != Int64Ty)
958               G1OC = ConstantExpr::getSExt(G1OC, Int64Ty);
959             if (G2OC->getType() != Int64Ty) 
960               G2OC = ConstantExpr::getSExt(G2OC, Int64Ty);
961             GEP1Ops[FirstConstantOper] = G1OC;
962             GEP2Ops[FirstConstantOper] = G2OC;
963           }
964           
965           if (G1OC != G2OC) {
966             // Handle the "be careful" case above: if this is an array/vector
967             // subscript, scan for a subsequent variable array index.
968             if (const SequentialType *STy =
969                   dyn_cast<SequentialType>(BasePtr1Ty)) {
970               const Type *NextTy = STy;
971               bool isBadCase = false;
972               
973               for (unsigned Idx = FirstConstantOper;
974                    Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
975                 const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
976                 if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
977                   isBadCase = true;
978                   break;
979                 }
980                 // If the array is indexed beyond the bounds of the static type
981                 // at this level, it will also fall into the "be careful" case.
982                 // It would theoretically be possible to analyze these cases,
983                 // but for now just be conservatively correct.
984                 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
985                   if (cast<ConstantInt>(G1OC)->getZExtValue() >=
986                         ATy->getNumElements() ||
987                       cast<ConstantInt>(G2OC)->getZExtValue() >=
988                         ATy->getNumElements()) {
989                     isBadCase = true;
990                     break;
991                   }
992                 if (const VectorType *VTy = dyn_cast<VectorType>(STy))
993                   if (cast<ConstantInt>(G1OC)->getZExtValue() >=
994                         VTy->getNumElements() ||
995                       cast<ConstantInt>(G2OC)->getZExtValue() >=
996                         VTy->getNumElements()) {
997                     isBadCase = true;
998                     break;
999                   }
1000                 STy = cast<SequentialType>(NextTy);
1001                 NextTy = cast<SequentialType>(NextTy)->getElementType();
1002               }
1003               
1004               if (isBadCase) G1OC = 0;
1005             }
1006
1007             // Make sure they are comparable (ie, not constant expressions), and
1008             // make sure the GEP with the smaller leading constant is GEP1.
1009             if (G1OC) {
1010               Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT, 
1011                                                         G1OC, G2OC);
1012               if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
1013                 if (CV->getZExtValue()) {  // If they are comparable and G2 > G1
1014                   std::swap(GEP1Ops, GEP2Ops);  // Make GEP1 < GEP2
1015                   std::swap(NumGEP1Ops, NumGEP2Ops);
1016                 }
1017                 break;
1018               }
1019             }
1020           }
1021         }
1022     BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
1023   }
1024
1025   // No shared constant operands, and we ran out of common operands.  At this
1026   // point, the GEP instructions have run through all of their operands, and we
1027   // haven't found evidence that there are any deltas between the GEP's.
1028   // However, one GEP may have more operands than the other.  If this is the
1029   // case, there may still be hope.  Check this now.
1030   if (FirstConstantOper == MinOperands) {
1031     // Without TargetData, we won't know what the offsets are.
1032     if (!TD)
1033       return MayAlias;
1034
1035     // Make GEP1Ops be the longer one if there is a longer one.
1036     if (NumGEP1Ops < NumGEP2Ops) {
1037       std::swap(GEP1Ops, GEP2Ops);
1038       std::swap(NumGEP1Ops, NumGEP2Ops);
1039     }
1040
1041     // Is there anything to check?
1042     if (NumGEP1Ops > MinOperands) {
1043       for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
1044         if (isa<ConstantInt>(GEP1Ops[i]) && 
1045             !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
1046           // Yup, there's a constant in the tail.  Set all variables to
1047           // constants in the GEP instruction to make it suitable for
1048           // TargetData::getIndexedOffset.
1049           for (i = 0; i != MaxOperands; ++i)
1050             if (!isa<ConstantInt>(GEP1Ops[i]))
1051               GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
1052           // Okay, now get the offset.  This is the relative offset for the full
1053           // instruction.
1054           int64_t Offset1 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
1055                                                  NumGEP1Ops);
1056
1057           // Now check without any constants at the end.
1058           int64_t Offset2 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
1059                                                  MinOperands);
1060
1061           // Make sure we compare the absolute difference.
1062           if (Offset1 > Offset2)
1063             std::swap(Offset1, Offset2);
1064
1065           // If the tail provided a bit enough offset, return noalias!
1066           if ((uint64_t)(Offset2-Offset1) >= SizeMax)
1067             return NoAlias;
1068           // Otherwise break - we don't look for another constant in the tail.
1069           break;
1070         }
1071     }
1072
1073     // Couldn't find anything useful.
1074     return MayAlias;
1075   }
1076
1077   // If there are non-equal constants arguments, then we can figure
1078   // out a minimum known delta between the two index expressions... at
1079   // this point we know that the first constant index of GEP1 is less
1080   // than the first constant index of GEP2.
1081
1082   // Advance BasePtr[12]Ty over this first differing constant operand.
1083   BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
1084       getTypeAtIndex(GEP2Ops[FirstConstantOper]);
1085   BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
1086       getTypeAtIndex(GEP1Ops[FirstConstantOper]);
1087
1088   // We are going to be using TargetData::getIndexedOffset to determine the
1089   // offset that each of the GEP's is reaching.  To do this, we have to convert
1090   // all variable references to constant references.  To do this, we convert the
1091   // initial sequence of array subscripts into constant zeros to start with.
1092   const Type *ZeroIdxTy = GEPPointerTy;
1093   for (unsigned i = 0; i != FirstConstantOper; ++i) {
1094     if (!isa<StructType>(ZeroIdxTy))
1095       GEP1Ops[i] = GEP2Ops[i] = 
1096               Constant::getNullValue(Type::getInt32Ty(ZeroIdxTy->getContext()));
1097
1098     if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
1099       ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
1100   }
1101
1102   // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
1103
1104   // Loop over the rest of the operands...
1105   for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
1106     const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
1107     const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
1108     // If they are equal, use a zero index...
1109     if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
1110       if (!isa<ConstantInt>(Op1))
1111         GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
1112       // Otherwise, just keep the constants we have.
1113     } else {
1114       if (Op1) {
1115         if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1116           // If this is an array index, make sure the array element is in range.
1117           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
1118             if (Op1C->getZExtValue() >= AT->getNumElements())
1119               return MayAlias;  // Be conservative with out-of-range accesses
1120           } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
1121             if (Op1C->getZExtValue() >= VT->getNumElements())
1122               return MayAlias;  // Be conservative with out-of-range accesses
1123           }
1124           
1125         } else {
1126           // GEP1 is known to produce a value less than GEP2.  To be
1127           // conservatively correct, we must assume the largest possible
1128           // constant is used in this position.  This cannot be the initial
1129           // index to the GEP instructions (because we know we have at least one
1130           // element before this one with the different constant arguments), so
1131           // we know that the current index must be into either a struct or
1132           // array.  Because we know it's not constant, this cannot be a
1133           // structure index.  Because of this, we can calculate the maximum
1134           // value possible.
1135           //
1136           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
1137             GEP1Ops[i] =
1138                   ConstantInt::get(Type::getInt64Ty(AT->getContext()), 
1139                                    AT->getNumElements()-1);
1140           else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
1141             GEP1Ops[i] = 
1142                   ConstantInt::get(Type::getInt64Ty(VT->getContext()),
1143                                    VT->getNumElements()-1);
1144         }
1145       }
1146
1147       if (Op2) {
1148         if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
1149           // If this is an array index, make sure the array element is in range.
1150           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
1151             if (Op2C->getZExtValue() >= AT->getNumElements())
1152               return MayAlias;  // Be conservative with out-of-range accesses
1153           } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
1154             if (Op2C->getZExtValue() >= VT->getNumElements())
1155               return MayAlias;  // Be conservative with out-of-range accesses
1156           }
1157         } else {  // Conservatively assume the minimum value for this index
1158           GEP2Ops[i] = Constant::getNullValue(Op2->getType());
1159         }
1160       }
1161     }
1162
1163     if (BasePtr1Ty && Op1) {
1164       if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
1165         BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
1166       else
1167         BasePtr1Ty = 0;
1168     }
1169
1170     if (BasePtr2Ty && Op2) {
1171       if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
1172         BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
1173       else
1174         BasePtr2Ty = 0;
1175     }
1176   }
1177
1178   if (TD && GEPPointerTy->getElementType()->isSized()) {
1179     int64_t Offset1 =
1180       TD->getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
1181     int64_t Offset2 = 
1182       TD->getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
1183     assert(Offset1 != Offset2 &&
1184            "There is at least one different constant here!");
1185     
1186     // Make sure we compare the absolute difference.
1187     if (Offset1 > Offset2)
1188       std::swap(Offset1, Offset2);
1189     
1190     if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
1191       //cerr << "Determined that these two GEP's don't alias ["
1192       //     << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
1193       return NoAlias;
1194     }
1195   }
1196   return MayAlias;
1197 }
1198
1199 // Make sure that anything that uses AliasAnalysis pulls in this file.
1200 DEFINING_FILE_FOR(BasicAliasAnalysis)