BasicAliasAnalysis.cpp revision 198113
1193323Sed//===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file defines the default implementation of the Alias Analysis interface
11193323Sed// that simply implements a few identities (two different globals cannot alias,
12193323Sed// etc), but otherwise does no analysis.
13193323Sed//
14193323Sed//===----------------------------------------------------------------------===//
15193323Sed
16193323Sed#include "llvm/Analysis/AliasAnalysis.h"
17193323Sed#include "llvm/Analysis/CaptureTracking.h"
18198090Srdivacky#include "llvm/Analysis/MallocHelper.h"
19193323Sed#include "llvm/Analysis/Passes.h"
20193323Sed#include "llvm/Constants.h"
21193323Sed#include "llvm/DerivedTypes.h"
22193323Sed#include "llvm/Function.h"
23193323Sed#include "llvm/GlobalVariable.h"
24193323Sed#include "llvm/Instructions.h"
25193323Sed#include "llvm/IntrinsicInst.h"
26198090Srdivacky#include "llvm/LLVMContext.h"
27198090Srdivacky#include "llvm/Operator.h"
28193323Sed#include "llvm/Pass.h"
29193323Sed#include "llvm/Target/TargetData.h"
30198090Srdivacky#include "llvm/ADT/SmallSet.h"
31193323Sed#include "llvm/ADT/SmallVector.h"
32193323Sed#include "llvm/ADT/STLExtras.h"
33193323Sed#include "llvm/Support/Compiler.h"
34198090Srdivacky#include "llvm/Support/ErrorHandling.h"
35193323Sed#include "llvm/Support/GetElementPtrTypeIterator.h"
36193323Sed#include <algorithm>
37193323Sedusing namespace llvm;
38193323Sed
39193323Sed//===----------------------------------------------------------------------===//
40193323Sed// Useful predicates
41193323Sed//===----------------------------------------------------------------------===//
42193323Sed
43198090Srdivackystatic const GEPOperator *isGEP(const Value *V) {
44198090Srdivacky  return dyn_cast<GEPOperator>(V);
45193323Sed}
46193323Sed
47193323Sedstatic const Value *GetGEPOperands(const Value *V,
48193323Sed                                   SmallVector<Value*, 16> &GEPOps) {
49193323Sed  assert(GEPOps.empty() && "Expect empty list to populate!");
50193323Sed  GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1,
51193323Sed                cast<User>(V)->op_end());
52193323Sed
53193323Sed  // Accumulate all of the chained indexes into the operand array
54193323Sed  V = cast<User>(V)->getOperand(0);
55193323Sed
56193323Sed  while (const User *G = isGEP(V)) {
57193323Sed    if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) ||
58193323Sed        !cast<Constant>(GEPOps[0])->isNullValue())
59193323Sed      break;  // Don't handle folding arbitrary pointer offsets yet...
60193323Sed    GEPOps.erase(GEPOps.begin());   // Drop the zero index
61193323Sed    GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end());
62193323Sed    V = G->getOperand(0);
63193323Sed  }
64193323Sed  return V;
65193323Sed}
66193323Sed
67193323Sed/// isKnownNonNull - Return true if we know that the specified value is never
68193323Sed/// null.
69193323Sedstatic bool isKnownNonNull(const Value *V) {
70193323Sed  // Alloca never returns null, malloc might.
71193323Sed  if (isa<AllocaInst>(V)) return true;
72193323Sed
73193323Sed  // A byval argument is never null.
74193323Sed  if (const Argument *A = dyn_cast<Argument>(V))
75193323Sed    return A->hasByValAttr();
76193323Sed
77193323Sed  // Global values are not null unless extern weak.
78193323Sed  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
79193323Sed    return !GV->hasExternalWeakLinkage();
80193323Sed  return false;
81193323Sed}
82193323Sed
83193323Sed/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
84193323Sed/// object that never escapes from the function.
85193323Sedstatic bool isNonEscapingLocalObject(const Value *V) {
86193323Sed  // If this is a local allocation, check to see if it escapes.
87193323Sed  if (isa<AllocationInst>(V) || isNoAliasCall(V))
88193323Sed    return !PointerMayBeCaptured(V, false);
89193323Sed
90193323Sed  // If this is an argument that corresponds to a byval or noalias argument,
91193323Sed  // then it has not escaped before entering the function.  Check if it escapes
92193323Sed  // inside the function.
93193323Sed  if (const Argument *A = dyn_cast<Argument>(V))
94193323Sed    if (A->hasByValAttr() || A->hasNoAliasAttr()) {
95193323Sed      // Don't bother analyzing arguments already known not to escape.
96193323Sed      if (A->hasNoCaptureAttr())
97193323Sed        return true;
98193323Sed      return !PointerMayBeCaptured(V, false);
99193323Sed    }
100193323Sed  return false;
101193323Sed}
102193323Sed
103193323Sed
104193323Sed/// isObjectSmallerThan - Return true if we can prove that the object specified
105193323Sed/// by V is smaller than Size.
106193323Sedstatic bool isObjectSmallerThan(const Value *V, unsigned Size,
107198090Srdivacky                                LLVMContext &Context, const TargetData &TD) {
108193323Sed  const Type *AccessTy;
109193323Sed  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
110193323Sed    AccessTy = GV->getType()->getElementType();
111193323Sed  } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
112193323Sed    if (!AI->isArrayAllocation())
113193323Sed      AccessTy = AI->getType()->getElementType();
114193323Sed    else
115193323Sed      return false;
116198090Srdivacky  } else if (const CallInst* CI = extractMallocCall(V)) {
117198090Srdivacky    if (!isArrayMalloc(V, Context, &TD))
118198090Srdivacky      // The size is the argument to the malloc call.
119198090Srdivacky      if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
120198090Srdivacky        return (C->getZExtValue() < Size);
121198090Srdivacky    return false;
122193323Sed  } else if (const Argument *A = dyn_cast<Argument>(V)) {
123193323Sed    if (A->hasByValAttr())
124193323Sed      AccessTy = cast<PointerType>(A->getType())->getElementType();
125193323Sed    else
126193323Sed      return false;
127193323Sed  } else {
128193323Sed    return false;
129193323Sed  }
130193323Sed
131193323Sed  if (AccessTy->isSized())
132193323Sed    return TD.getTypeAllocSize(AccessTy) < Size;
133193323Sed  return false;
134193323Sed}
135193323Sed
136193323Sed//===----------------------------------------------------------------------===//
137193323Sed// NoAA Pass
138193323Sed//===----------------------------------------------------------------------===//
139193323Sed
140193323Sednamespace {
141193323Sed  /// NoAA - This class implements the -no-aa pass, which always returns "I
142193323Sed  /// don't know" for alias queries.  NoAA is unlike other alias analysis
143193323Sed  /// implementations, in that it does not chain to a previous analysis.  As
144193323Sed  /// such it doesn't follow many of the rules that other alias analyses must.
145193323Sed  ///
146193323Sed  struct VISIBILITY_HIDDEN NoAA : public ImmutablePass, public AliasAnalysis {
147193323Sed    static char ID; // Class identification, replacement for typeinfo
148193323Sed    NoAA() : ImmutablePass(&ID) {}
149193323Sed    explicit NoAA(void *PID) : ImmutablePass(PID) { }
150193323Sed
151193323Sed    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152193323Sed    }
153193323Sed
154193323Sed    virtual void initializePass() {
155198090Srdivacky      TD = getAnalysisIfAvailable<TargetData>();
156193323Sed    }
157193323Sed
158193323Sed    virtual AliasResult alias(const Value *V1, unsigned V1Size,
159193323Sed                              const Value *V2, unsigned V2Size) {
160193323Sed      return MayAlias;
161193323Sed    }
162193323Sed
163193323Sed    virtual void getArgumentAccesses(Function *F, CallSite CS,
164193323Sed                                     std::vector<PointerAccessInfo> &Info) {
165198090Srdivacky      llvm_unreachable("This method may not be called on this function!");
166193323Sed    }
167193323Sed
168193323Sed    virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { }
169193323Sed    virtual bool pointsToConstantMemory(const Value *P) { return false; }
170193323Sed    virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
171193323Sed      return ModRef;
172193323Sed    }
173193323Sed    virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
174193323Sed      return ModRef;
175193323Sed    }
176193323Sed    virtual bool hasNoModRefInfoForCalls() const { return true; }
177193323Sed
178193323Sed    virtual void deleteValue(Value *V) {}
179193323Sed    virtual void copyValue(Value *From, Value *To) {}
180193323Sed  };
181193323Sed}  // End of anonymous namespace
182193323Sed
183193323Sed// Register this pass...
184193323Sedchar NoAA::ID = 0;
185193323Sedstatic RegisterPass<NoAA>
186193323SedU("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
187193323Sed
188193323Sed// Declare that we implement the AliasAnalysis interface
189193323Sedstatic RegisterAnalysisGroup<AliasAnalysis> V(U);
190193323Sed
191193323SedImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
192193323Sed
193193323Sed//===----------------------------------------------------------------------===//
194193323Sed// BasicAA Pass
195193323Sed//===----------------------------------------------------------------------===//
196193323Sed
197193323Sednamespace {
198193323Sed  /// BasicAliasAnalysis - This is the default alias analysis implementation.
199193323Sed  /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
200193323Sed  /// derives from the NoAA class.
201193323Sed  struct VISIBILITY_HIDDEN BasicAliasAnalysis : public NoAA {
202193323Sed    static char ID; // Class identification, replacement for typeinfo
203193323Sed    BasicAliasAnalysis() : NoAA(&ID) {}
204193323Sed    AliasResult alias(const Value *V1, unsigned V1Size,
205198090Srdivacky                      const Value *V2, unsigned V2Size) {
206198090Srdivacky      assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
207198090Srdivacky      AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
208198090Srdivacky      VisitedPHIs.clear();
209198090Srdivacky      return Alias;
210198090Srdivacky    }
211193323Sed
212193323Sed    ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
213193323Sed    ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
214193323Sed
215193323Sed    /// hasNoModRefInfoForCalls - We can provide mod/ref information against
216193323Sed    /// non-escaping allocations.
217193323Sed    virtual bool hasNoModRefInfoForCalls() const { return false; }
218193323Sed
219193323Sed    /// pointsToConstantMemory - Chase pointers until we find a (constant
220193323Sed    /// global) or not.
221193323Sed    bool pointsToConstantMemory(const Value *P);
222193323Sed
223193323Sed  private:
224198090Srdivacky    // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
225198090Srdivacky    SmallSet<const PHINode*, 16> VisitedPHIs;
226198090Srdivacky
227198090Srdivacky    // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
228198090Srdivacky    // against another.
229198090Srdivacky    AliasResult aliasGEP(const Value *V1, unsigned V1Size,
230198090Srdivacky                         const Value *V2, unsigned V2Size);
231198090Srdivacky
232198090Srdivacky    // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
233198090Srdivacky    // against another.
234198090Srdivacky    AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
235198090Srdivacky                         const Value *V2, unsigned V2Size);
236198090Srdivacky
237198090Srdivacky    AliasResult aliasCheck(const Value *V1, unsigned V1Size,
238198090Srdivacky                           const Value *V2, unsigned V2Size);
239198090Srdivacky
240193323Sed    // CheckGEPInstructions - Check two GEP instructions with known
241193323Sed    // must-aliasing base pointers.  This checks to see if the index expressions
242193323Sed    // preclude the pointers from aliasing...
243193323Sed    AliasResult
244193323Sed    CheckGEPInstructions(const Type* BasePtr1Ty,
245193323Sed                         Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
246193323Sed                         const Type *BasePtr2Ty,
247193323Sed                         Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
248193323Sed  };
249193323Sed}  // End of anonymous namespace
250193323Sed
251193323Sed// Register this pass...
252193323Sedchar BasicAliasAnalysis::ID = 0;
253193323Sedstatic RegisterPass<BasicAliasAnalysis>
254193323SedX("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
255193323Sed
256193323Sed// Declare that we implement the AliasAnalysis interface
257193323Sedstatic RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
258193323Sed
259193323SedImmutablePass *llvm::createBasicAliasAnalysisPass() {
260193323Sed  return new BasicAliasAnalysis();
261193323Sed}
262193323Sed
263193323Sed
264193323Sed/// pointsToConstantMemory - Chase pointers until we find a (constant
265193323Sed/// global) or not.
266193323Sedbool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
267193323Sed  if (const GlobalVariable *GV =
268193323Sed        dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
269193323Sed    return GV->isConstant();
270193323Sed  return false;
271193323Sed}
272193323Sed
273193323Sed
274193323Sed// getModRefInfo - Check to see if the specified callsite can clobber the
275193323Sed// specified memory object.  Since we only look at local properties of this
276193323Sed// function, we really can't say much about this query.  We do, however, use
277193323Sed// simple "address taken" analysis on local objects.
278193323Sed//
279193323SedAliasAnalysis::ModRefResult
280193323SedBasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
281193323Sed  if (!isa<Constant>(P)) {
282193323Sed    const Value *Object = P->getUnderlyingObject();
283193323Sed
284193323Sed    // If this is a tail call and P points to a stack location, we know that
285193323Sed    // the tail call cannot access or modify the local stack.
286193323Sed    // We cannot exclude byval arguments here; these belong to the caller of
287193323Sed    // the current function not to the current function, and a tail callee
288193323Sed    // may reference them.
289193323Sed    if (isa<AllocaInst>(Object))
290193323Sed      if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
291193323Sed        if (CI->isTailCall())
292193323Sed          return NoModRef;
293193323Sed
294193323Sed    // If the pointer is to a locally allocated object that does not escape,
295193323Sed    // then the call can not mod/ref the pointer unless the call takes the
296193323Sed    // argument without capturing it.
297193323Sed    if (isNonEscapingLocalObject(Object) && CS.getInstruction() != Object) {
298193323Sed      bool passedAsArg = false;
299193323Sed      // TODO: Eventually only check 'nocapture' arguments.
300193323Sed      for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
301193323Sed           CI != CE; ++CI)
302193323Sed        if (isa<PointerType>((*CI)->getType()) &&
303193323Sed            alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias)
304193323Sed          passedAsArg = true;
305193323Sed
306193323Sed      if (!passedAsArg)
307193323Sed        return NoModRef;
308193323Sed    }
309198090Srdivacky
310198090Srdivacky    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
311198090Srdivacky      switch (II->getIntrinsicID()) {
312198090Srdivacky      default: break;
313198113Srdivacky      case Intrinsic::memcpy:
314198113Srdivacky      case Intrinsic::memmove: {
315198113Srdivacky        unsigned Len = ~0U;
316198113Srdivacky        if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
317198113Srdivacky          Len = LenCI->getZExtValue();
318198113Srdivacky        Value *Dest = II->getOperand(1);
319198113Srdivacky        Value *Src = II->getOperand(2);
320198113Srdivacky        if (alias(Dest, Len, P, Size) == NoAlias) {
321198113Srdivacky          if (alias(Src, Len, P, Size) == NoAlias)
322198113Srdivacky            return NoModRef;
323198113Srdivacky          return Ref;
324198113Srdivacky        }
325198113Srdivacky        }
326198113Srdivacky        break;
327198113Srdivacky      case Intrinsic::memset:
328198113Srdivacky        if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
329198113Srdivacky          unsigned Len = LenCI->getZExtValue();
330198113Srdivacky          Value *Dest = II->getOperand(1);
331198113Srdivacky          if (alias(Dest, Len, P, Size) == NoAlias)
332198113Srdivacky            return NoModRef;
333198113Srdivacky        }
334198113Srdivacky        break;
335198090Srdivacky      case Intrinsic::atomic_cmp_swap:
336198090Srdivacky      case Intrinsic::atomic_swap:
337198090Srdivacky      case Intrinsic::atomic_load_add:
338198090Srdivacky      case Intrinsic::atomic_load_sub:
339198090Srdivacky      case Intrinsic::atomic_load_and:
340198090Srdivacky      case Intrinsic::atomic_load_nand:
341198090Srdivacky      case Intrinsic::atomic_load_or:
342198090Srdivacky      case Intrinsic::atomic_load_xor:
343198090Srdivacky      case Intrinsic::atomic_load_max:
344198090Srdivacky      case Intrinsic::atomic_load_min:
345198090Srdivacky      case Intrinsic::atomic_load_umax:
346198090Srdivacky      case Intrinsic::atomic_load_umin:
347198113Srdivacky        if (TD) {
348198113Srdivacky          Value *Op1 = II->getOperand(1);
349198113Srdivacky          unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
350198113Srdivacky          if (alias(Op1, Op1Size, P, Size) == NoAlias)
351198113Srdivacky            return NoModRef;
352198113Srdivacky        }
353198113Srdivacky        break;
354198113Srdivacky      case Intrinsic::lifetime_start:
355198113Srdivacky      case Intrinsic::lifetime_end:
356198113Srdivacky      case Intrinsic::invariant_start: {
357198113Srdivacky        unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
358198113Srdivacky        if (alias(II->getOperand(2), PtrSize, P, Size) == NoAlias)
359198090Srdivacky          return NoModRef;
360198090Srdivacky      }
361198113Srdivacky      case Intrinsic::invariant_end: {
362198113Srdivacky        unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
363198113Srdivacky        if (alias(II->getOperand(3), PtrSize, P, Size) == NoAlias)
364198113Srdivacky          return NoModRef;
365198113Srdivacky      }
366198113Srdivacky      }
367198090Srdivacky    }
368193323Sed  }
369193323Sed
370193323Sed  // The AliasAnalysis base class has some smarts, lets use them.
371193323Sed  return AliasAnalysis::getModRefInfo(CS, P, Size);
372193323Sed}
373193323Sed
374193323Sed
375193323SedAliasAnalysis::ModRefResult
376193323SedBasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
377193323Sed  // If CS1 or CS2 are readnone, they don't interact.
378193323Sed  ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
379193323Sed  if (CS1B == DoesNotAccessMemory) return NoModRef;
380193323Sed
381193323Sed  ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
382193323Sed  if (CS2B == DoesNotAccessMemory) return NoModRef;
383193323Sed
384193323Sed  // If they both only read from memory, just return ref.
385193323Sed  if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
386193323Sed    return Ref;
387193323Sed
388193323Sed  // Otherwise, fall back to NoAA (mod+ref).
389193323Sed  return NoAA::getModRefInfo(CS1, CS2);
390193323Sed}
391193323Sed
392198090Srdivacky// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
393198090Srdivacky// against another.
394193323Sed//
395193323SedAliasAnalysis::AliasResult
396198090SrdivackyBasicAliasAnalysis::aliasGEP(const Value *V1, unsigned V1Size,
397198090Srdivacky                             const Value *V2, unsigned V2Size) {
398193323Sed  // If we have two gep instructions with must-alias'ing base pointers, figure
399193323Sed  // out if the indexes to the GEP tell us anything about the derived pointer.
400193323Sed  // Note that we also handle chains of getelementptr instructions as well as
401193323Sed  // constant expression getelementptrs here.
402193323Sed  //
403193323Sed  if (isGEP(V1) && isGEP(V2)) {
404193323Sed    const User *GEP1 = cast<User>(V1);
405193323Sed    const User *GEP2 = cast<User>(V2);
406193323Sed
407193323Sed    // If V1 and V2 are identical GEPs, just recurse down on both of them.
408193323Sed    // This allows us to analyze things like:
409193323Sed    //   P = gep A, 0, i, 1
410193323Sed    //   Q = gep B, 0, i, 1
411193323Sed    // by just analyzing A and B.  This is even safe for variable indices.
412193323Sed    if (GEP1->getType() == GEP2->getType() &&
413193323Sed        GEP1->getNumOperands() == GEP2->getNumOperands() &&
414193323Sed        GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
415193323Sed        // All operands are the same, ignoring the base.
416193323Sed        std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
417198090Srdivacky      return aliasCheck(GEP1->getOperand(0), V1Size,
418198090Srdivacky                        GEP2->getOperand(0), V2Size);
419193323Sed
420193323Sed    // Drill down into the first non-gep value, to test for must-aliasing of
421193323Sed    // the base pointers.
422193323Sed    while (isGEP(GEP1->getOperand(0)) &&
423193323Sed           GEP1->getOperand(1) ==
424193323Sed           Constant::getNullValue(GEP1->getOperand(1)->getType()))
425193323Sed      GEP1 = cast<User>(GEP1->getOperand(0));
426193323Sed    const Value *BasePtr1 = GEP1->getOperand(0);
427193323Sed
428193323Sed    while (isGEP(GEP2->getOperand(0)) &&
429193323Sed           GEP2->getOperand(1) ==
430193323Sed           Constant::getNullValue(GEP2->getOperand(1)->getType()))
431193323Sed      GEP2 = cast<User>(GEP2->getOperand(0));
432193323Sed    const Value *BasePtr2 = GEP2->getOperand(0);
433193323Sed
434193323Sed    // Do the base pointers alias?
435198090Srdivacky    AliasResult BaseAlias = aliasCheck(BasePtr1, ~0U, BasePtr2, ~0U);
436193323Sed    if (BaseAlias == NoAlias) return NoAlias;
437193323Sed    if (BaseAlias == MustAlias) {
438193323Sed      // If the base pointers alias each other exactly, check to see if we can
439193323Sed      // figure out anything about the resultant pointers, to try to prove
440193323Sed      // non-aliasing.
441193323Sed
442193323Sed      // Collect all of the chained GEP operands together into one simple place
443193323Sed      SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
444193323Sed      BasePtr1 = GetGEPOperands(V1, GEP1Ops);
445193323Sed      BasePtr2 = GetGEPOperands(V2, GEP2Ops);
446193323Sed
447193323Sed      // If GetGEPOperands were able to fold to the same must-aliased pointer,
448193323Sed      // do the comparison.
449193323Sed      if (BasePtr1 == BasePtr2) {
450193323Sed        AliasResult GAlias =
451193323Sed          CheckGEPInstructions(BasePtr1->getType(),
452193323Sed                               &GEP1Ops[0], GEP1Ops.size(), V1Size,
453193323Sed                               BasePtr2->getType(),
454193323Sed                               &GEP2Ops[0], GEP2Ops.size(), V2Size);
455193323Sed        if (GAlias != MayAlias)
456193323Sed          return GAlias;
457193323Sed      }
458193323Sed    }
459193323Sed  }
460193323Sed
461193323Sed  // Check to see if these two pointers are related by a getelementptr
462193323Sed  // instruction.  If one pointer is a GEP with a non-zero index of the other
463193323Sed  // pointer, we know they cannot alias.
464193323Sed  //
465198090Srdivacky  if (V1Size == ~0U || V2Size == ~0U)
466198090Srdivacky    return MayAlias;
467193323Sed
468198090Srdivacky  SmallVector<Value*, 16> GEPOperands;
469198090Srdivacky  const Value *BasePtr = GetGEPOperands(V1, GEPOperands);
470193323Sed
471198090Srdivacky  AliasResult R = aliasCheck(BasePtr, ~0U, V2, V2Size);
472198090Srdivacky  if (R != MustAlias)
473198090Srdivacky    // If V2 may alias GEP base pointer, conservatively returns MayAlias.
474198090Srdivacky    // If V2 is known not to alias GEP base pointer, then the two values
475198090Srdivacky    // cannot alias per GEP semantics: "A pointer value formed from a
476198090Srdivacky    // getelementptr instruction is associated with the addresses associated
477198090Srdivacky    // with the first operand of the getelementptr".
478198090Srdivacky    return R;
479193323Sed
480198090Srdivacky  // If there is at least one non-zero constant index, we know they cannot
481198090Srdivacky  // alias.
482198090Srdivacky  bool ConstantFound = false;
483198090Srdivacky  bool AllZerosFound = true;
484198090Srdivacky  for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i)
485198090Srdivacky    if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) {
486198090Srdivacky      if (!C->isNullValue()) {
487198090Srdivacky        ConstantFound = true;
488198090Srdivacky        AllZerosFound = false;
489198090Srdivacky        break;
490198090Srdivacky      }
491198090Srdivacky    } else {
492198090Srdivacky      AllZerosFound = false;
493198090Srdivacky    }
494193323Sed
495198090Srdivacky  // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
496198090Srdivacky  // the ptr, the end result is a must alias also.
497198090Srdivacky  if (AllZerosFound)
498198090Srdivacky    return MustAlias;
499193323Sed
500198090Srdivacky  if (ConstantFound) {
501198090Srdivacky    if (V2Size <= 1 && V1Size <= 1)  // Just pointer check?
502198090Srdivacky      return NoAlias;
503193323Sed
504198090Srdivacky    // Otherwise we have to check to see that the distance is more than
505198090Srdivacky    // the size of the argument... build an index vector that is equal to
506198090Srdivacky    // the arguments provided, except substitute 0's for any variable
507198090Srdivacky    // indexes we find...
508198090Srdivacky    if (TD &&
509198090Srdivacky        cast<PointerType>(BasePtr->getType())->getElementType()->isSized()) {
510198090Srdivacky      for (unsigned i = 0; i != GEPOperands.size(); ++i)
511198090Srdivacky        if (!isa<ConstantInt>(GEPOperands[i]))
512198090Srdivacky          GEPOperands[i] = Constant::getNullValue(GEPOperands[i]->getType());
513198090Srdivacky      int64_t Offset = TD->getIndexedOffset(BasePtr->getType(),
514198090Srdivacky                                            &GEPOperands[0],
515198090Srdivacky                                            GEPOperands.size());
516198090Srdivacky
517198090Srdivacky      if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size)
518198090Srdivacky        return NoAlias;
519193323Sed    }
520198090Srdivacky  }
521193323Sed
522193323Sed  return MayAlias;
523193323Sed}
524193323Sed
525198090Srdivacky// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
526198090Srdivacky// against another.
527198090SrdivackyAliasAnalysis::AliasResult
528198090SrdivackyBasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
529198090Srdivacky                             const Value *V2, unsigned V2Size) {
530198090Srdivacky  // The PHI node has already been visited, avoid recursion any further.
531198090Srdivacky  if (!VisitedPHIs.insert(PN))
532198090Srdivacky    return MayAlias;
533198090Srdivacky
534198090Srdivacky  SmallSet<Value*, 4> UniqueSrc;
535198090Srdivacky  SmallVector<Value*, 4> V1Srcs;
536198090Srdivacky  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
537198090Srdivacky    Value *PV1 = PN->getIncomingValue(i);
538198090Srdivacky    if (isa<PHINode>(PV1))
539198090Srdivacky      // If any of the source itself is a PHI, return MayAlias conservatively
540198090Srdivacky      // to avoid compile time explosion. The worst possible case is if both
541198090Srdivacky      // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
542198090Srdivacky      // and 'n' are the number of PHI sources.
543198090Srdivacky      return MayAlias;
544198090Srdivacky    if (UniqueSrc.insert(PV1))
545198090Srdivacky      V1Srcs.push_back(PV1);
546198090Srdivacky  }
547198090Srdivacky
548198090Srdivacky  AliasResult Alias = aliasCheck(V1Srcs[0], PNSize, V2, V2Size);
549198090Srdivacky  // Early exit if the check of the first PHI source against V2 is MayAlias.
550198090Srdivacky  // Other results are not possible.
551198090Srdivacky  if (Alias == MayAlias)
552198090Srdivacky    return MayAlias;
553198090Srdivacky
554198090Srdivacky  // If all sources of the PHI node NoAlias or MustAlias V2, then returns
555198090Srdivacky  // NoAlias / MustAlias. Otherwise, returns MayAlias.
556198090Srdivacky  for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
557198090Srdivacky    Value *V = V1Srcs[i];
558198090Srdivacky    AliasResult ThisAlias = aliasCheck(V, PNSize, V2, V2Size);
559198090Srdivacky    if (ThisAlias != Alias || ThisAlias == MayAlias)
560198090Srdivacky      return MayAlias;
561198090Srdivacky  }
562198090Srdivacky
563198090Srdivacky  return Alias;
564198090Srdivacky}
565198090Srdivacky
566198090Srdivacky// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
567198090Srdivacky// such as array references.
568198090Srdivacky//
569198090SrdivackyAliasAnalysis::AliasResult
570198090SrdivackyBasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
571198090Srdivacky                               const Value *V2, unsigned V2Size) {
572198090Srdivacky  // Strip off any casts if they exist.
573198090Srdivacky  V1 = V1->stripPointerCasts();
574198090Srdivacky  V2 = V2->stripPointerCasts();
575198090Srdivacky
576198090Srdivacky  // Are we checking for alias of the same value?
577198090Srdivacky  if (V1 == V2) return MustAlias;
578198090Srdivacky
579198090Srdivacky  if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
580198090Srdivacky    return NoAlias;  // Scalars cannot alias each other
581198090Srdivacky
582198090Srdivacky  // Figure out what objects these things are pointing to if we can.
583198090Srdivacky  const Value *O1 = V1->getUnderlyingObject();
584198090Srdivacky  const Value *O2 = V2->getUnderlyingObject();
585198090Srdivacky
586198090Srdivacky  if (O1 != O2) {
587198090Srdivacky    // If V1/V2 point to two different objects we know that we have no alias.
588198090Srdivacky    if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
589198090Srdivacky      return NoAlias;
590198090Srdivacky
591198090Srdivacky    // Arguments can't alias with local allocations or noalias calls.
592198090Srdivacky    if ((isa<Argument>(O1) && (isa<AllocationInst>(O2) || isNoAliasCall(O2))) ||
593198090Srdivacky        (isa<Argument>(O2) && (isa<AllocationInst>(O1) || isNoAliasCall(O1))))
594198090Srdivacky      return NoAlias;
595198090Srdivacky
596198090Srdivacky    // Most objects can't alias null.
597198090Srdivacky    if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
598198090Srdivacky        (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
599198090Srdivacky      return NoAlias;
600198090Srdivacky  }
601198090Srdivacky
602198090Srdivacky  // If the size of one access is larger than the entire object on the other
603198090Srdivacky  // side, then we know such behavior is undefined and can assume no alias.
604198090Srdivacky  LLVMContext &Context = V1->getContext();
605198090Srdivacky  if (TD)
606198090Srdivacky    if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, Context, *TD)) ||
607198090Srdivacky        (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, Context, *TD)))
608198090Srdivacky      return NoAlias;
609198090Srdivacky
610198090Srdivacky  // If one pointer is the result of a call/invoke and the other is a
611198090Srdivacky  // non-escaping local object, then we know the object couldn't escape to a
612198090Srdivacky  // point where the call could return it.
613198090Srdivacky  if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) &&
614198090Srdivacky      isNonEscapingLocalObject(O2) && O1 != O2)
615198090Srdivacky    return NoAlias;
616198090Srdivacky  if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) &&
617198090Srdivacky      isNonEscapingLocalObject(O1) && O1 != O2)
618198090Srdivacky    return NoAlias;
619198090Srdivacky
620198090Srdivacky  if (!isGEP(V1) && isGEP(V2)) {
621198090Srdivacky    std::swap(V1, V2);
622198090Srdivacky    std::swap(V1Size, V2Size);
623198090Srdivacky  }
624198090Srdivacky  if (isGEP(V1))
625198090Srdivacky    return aliasGEP(V1, V1Size, V2, V2Size);
626198090Srdivacky
627198090Srdivacky  if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
628198090Srdivacky    std::swap(V1, V2);
629198090Srdivacky    std::swap(V1Size, V2Size);
630198090Srdivacky  }
631198090Srdivacky  if (const PHINode *PN = dyn_cast<PHINode>(V1))
632198090Srdivacky    return aliasPHI(PN, V1Size, V2, V2Size);
633198090Srdivacky
634198090Srdivacky  return MayAlias;
635198090Srdivacky}
636198090Srdivacky
637193323Sed// This function is used to determine if the indices of two GEP instructions are
638193323Sed// equal. V1 and V2 are the indices.
639198090Srdivackystatic bool IndexOperandsEqual(Value *V1, Value *V2, LLVMContext &Context) {
640193323Sed  if (V1->getType() == V2->getType())
641193323Sed    return V1 == V2;
642193323Sed  if (Constant *C1 = dyn_cast<Constant>(V1))
643193323Sed    if (Constant *C2 = dyn_cast<Constant>(V2)) {
644193323Sed      // Sign extend the constants to long types, if necessary
645198090Srdivacky      if (C1->getType() != Type::getInt64Ty(Context))
646198090Srdivacky        C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(Context));
647198090Srdivacky      if (C2->getType() != Type::getInt64Ty(Context))
648198090Srdivacky        C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(Context));
649193323Sed      return C1 == C2;
650193323Sed    }
651193323Sed  return false;
652193323Sed}
653193323Sed
654193323Sed/// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
655193323Sed/// base pointers.  This checks to see if the index expressions preclude the
656193323Sed/// pointers from aliasing...
657193323SedAliasAnalysis::AliasResult
658193323SedBasicAliasAnalysis::CheckGEPInstructions(
659193323Sed  const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
660193323Sed  const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
661193323Sed  // We currently can't handle the case when the base pointers have different
662193323Sed  // primitive types.  Since this is uncommon anyway, we are happy being
663193323Sed  // extremely conservative.
664193323Sed  if (BasePtr1Ty != BasePtr2Ty)
665193323Sed    return MayAlias;
666193323Sed
667193323Sed  const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
668193323Sed
669198090Srdivacky  LLVMContext &Context = GEPPointerTy->getContext();
670198090Srdivacky
671193323Sed  // Find the (possibly empty) initial sequence of equal values... which are not
672193323Sed  // necessarily constants.
673193323Sed  unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
674193323Sed  unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
675193323Sed  unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
676193323Sed  unsigned UnequalOper = 0;
677193323Sed  while (UnequalOper != MinOperands &&
678198090Srdivacky         IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper],
679198090Srdivacky         Context)) {
680193323Sed    // Advance through the type as we go...
681193323Sed    ++UnequalOper;
682193323Sed    if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
683193323Sed      BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
684193323Sed    else {
685193323Sed      // If all operands equal each other, then the derived pointers must
686193323Sed      // alias each other...
687193323Sed      BasePtr1Ty = 0;
688193323Sed      assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
689193323Sed             "Ran out of type nesting, but not out of operands?");
690193323Sed      return MustAlias;
691193323Sed    }
692193323Sed  }
693193323Sed
694193323Sed  // If we have seen all constant operands, and run out of indexes on one of the
695193323Sed  // getelementptrs, check to see if the tail of the leftover one is all zeros.
696193323Sed  // If so, return mustalias.
697193323Sed  if (UnequalOper == MinOperands) {
698193323Sed    if (NumGEP1Ops < NumGEP2Ops) {
699193323Sed      std::swap(GEP1Ops, GEP2Ops);
700193323Sed      std::swap(NumGEP1Ops, NumGEP2Ops);
701193323Sed    }
702193323Sed
703193323Sed    bool AllAreZeros = true;
704193323Sed    for (unsigned i = UnequalOper; i != MaxOperands; ++i)
705193323Sed      if (!isa<Constant>(GEP1Ops[i]) ||
706193323Sed          !cast<Constant>(GEP1Ops[i])->isNullValue()) {
707193323Sed        AllAreZeros = false;
708193323Sed        break;
709193323Sed      }
710193323Sed    if (AllAreZeros) return MustAlias;
711193323Sed  }
712193323Sed
713193323Sed
714193323Sed  // So now we know that the indexes derived from the base pointers,
715193323Sed  // which are known to alias, are different.  We can still determine a
716193323Sed  // no-alias result if there are differing constant pairs in the index
717193323Sed  // chain.  For example:
718193323Sed  //        A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
719193323Sed  //
720193323Sed  // We have to be careful here about array accesses.  In particular, consider:
721193323Sed  //        A[1][0] vs A[0][i]
722193323Sed  // In this case, we don't *know* that the array will be accessed in bounds:
723193323Sed  // the index could even be negative.  Because of this, we have to
724193323Sed  // conservatively *give up* and return may alias.  We disregard differing
725193323Sed  // array subscripts that are followed by a variable index without going
726193323Sed  // through a struct.
727193323Sed  //
728193323Sed  unsigned SizeMax = std::max(G1S, G2S);
729193323Sed  if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
730193323Sed
731193323Sed  // Scan for the first operand that is constant and unequal in the
732193323Sed  // two getelementptrs...
733193323Sed  unsigned FirstConstantOper = UnequalOper;
734193323Sed  for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
735193323Sed    const Value *G1Oper = GEP1Ops[FirstConstantOper];
736193323Sed    const Value *G2Oper = GEP2Ops[FirstConstantOper];
737193323Sed
738193323Sed    if (G1Oper != G2Oper)   // Found non-equal constant indexes...
739193323Sed      if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
740193323Sed        if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
741193323Sed          if (G1OC->getType() != G2OC->getType()) {
742193323Sed            // Sign extend both operands to long.
743198090Srdivacky            if (G1OC->getType() != Type::getInt64Ty(Context))
744198090Srdivacky              G1OC = ConstantExpr::getSExt(G1OC, Type::getInt64Ty(Context));
745198090Srdivacky            if (G2OC->getType() != Type::getInt64Ty(Context))
746198090Srdivacky              G2OC = ConstantExpr::getSExt(G2OC, Type::getInt64Ty(Context));
747193323Sed            GEP1Ops[FirstConstantOper] = G1OC;
748193323Sed            GEP2Ops[FirstConstantOper] = G2OC;
749193323Sed          }
750193323Sed
751193323Sed          if (G1OC != G2OC) {
752193323Sed            // Handle the "be careful" case above: if this is an array/vector
753193323Sed            // subscript, scan for a subsequent variable array index.
754193323Sed            if (const SequentialType *STy =
755193323Sed                  dyn_cast<SequentialType>(BasePtr1Ty)) {
756193323Sed              const Type *NextTy = STy;
757193323Sed              bool isBadCase = false;
758193323Sed
759193323Sed              for (unsigned Idx = FirstConstantOper;
760193323Sed                   Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
761193323Sed                const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
762193323Sed                if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
763193323Sed                  isBadCase = true;
764193323Sed                  break;
765193323Sed                }
766193323Sed                // If the array is indexed beyond the bounds of the static type
767193323Sed                // at this level, it will also fall into the "be careful" case.
768193323Sed                // It would theoretically be possible to analyze these cases,
769193323Sed                // but for now just be conservatively correct.
770193323Sed                if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
771193323Sed                  if (cast<ConstantInt>(G1OC)->getZExtValue() >=
772193323Sed                        ATy->getNumElements() ||
773193323Sed                      cast<ConstantInt>(G2OC)->getZExtValue() >=
774193323Sed                        ATy->getNumElements()) {
775193323Sed                    isBadCase = true;
776193323Sed                    break;
777193323Sed                  }
778193323Sed                if (const VectorType *VTy = dyn_cast<VectorType>(STy))
779193323Sed                  if (cast<ConstantInt>(G1OC)->getZExtValue() >=
780193323Sed                        VTy->getNumElements() ||
781193323Sed                      cast<ConstantInt>(G2OC)->getZExtValue() >=
782193323Sed                        VTy->getNumElements()) {
783193323Sed                    isBadCase = true;
784193323Sed                    break;
785193323Sed                  }
786193323Sed                STy = cast<SequentialType>(NextTy);
787193323Sed                NextTy = cast<SequentialType>(NextTy)->getElementType();
788193323Sed              }
789193323Sed
790193323Sed              if (isBadCase) G1OC = 0;
791193323Sed            }
792193323Sed
793193323Sed            // Make sure they are comparable (ie, not constant expressions), and
794193323Sed            // make sure the GEP with the smaller leading constant is GEP1.
795193323Sed            if (G1OC) {
796193323Sed              Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT,
797193323Sed                                                        G1OC, G2OC);
798193323Sed              if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
799193323Sed                if (CV->getZExtValue()) {  // If they are comparable and G2 > G1
800193323Sed                  std::swap(GEP1Ops, GEP2Ops);  // Make GEP1 < GEP2
801193323Sed                  std::swap(NumGEP1Ops, NumGEP2Ops);
802193323Sed                }
803193323Sed                break;
804193323Sed              }
805193323Sed            }
806193323Sed          }
807193323Sed        }
808193323Sed    BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
809193323Sed  }
810193323Sed
811193323Sed  // No shared constant operands, and we ran out of common operands.  At this
812193323Sed  // point, the GEP instructions have run through all of their operands, and we
813193323Sed  // haven't found evidence that there are any deltas between the GEP's.
814193323Sed  // However, one GEP may have more operands than the other.  If this is the
815193323Sed  // case, there may still be hope.  Check this now.
816193323Sed  if (FirstConstantOper == MinOperands) {
817198090Srdivacky    // Without TargetData, we won't know what the offsets are.
818198090Srdivacky    if (!TD)
819198090Srdivacky      return MayAlias;
820198090Srdivacky
821193323Sed    // Make GEP1Ops be the longer one if there is a longer one.
822193323Sed    if (NumGEP1Ops < NumGEP2Ops) {
823193323Sed      std::swap(GEP1Ops, GEP2Ops);
824193323Sed      std::swap(NumGEP1Ops, NumGEP2Ops);
825193323Sed    }
826193323Sed
827193323Sed    // Is there anything to check?
828193323Sed    if (NumGEP1Ops > MinOperands) {
829193323Sed      for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
830193323Sed        if (isa<ConstantInt>(GEP1Ops[i]) &&
831193323Sed            !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
832193323Sed          // Yup, there's a constant in the tail.  Set all variables to
833193323Sed          // constants in the GEP instruction to make it suitable for
834193323Sed          // TargetData::getIndexedOffset.
835193323Sed          for (i = 0; i != MaxOperands; ++i)
836193323Sed            if (!isa<ConstantInt>(GEP1Ops[i]))
837193323Sed              GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
838193323Sed          // Okay, now get the offset.  This is the relative offset for the full
839193323Sed          // instruction.
840198090Srdivacky          int64_t Offset1 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
841198090Srdivacky                                                 NumGEP1Ops);
842193323Sed
843193323Sed          // Now check without any constants at the end.
844198090Srdivacky          int64_t Offset2 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
845198090Srdivacky                                                 MinOperands);
846193323Sed
847193323Sed          // Make sure we compare the absolute difference.
848193323Sed          if (Offset1 > Offset2)
849193323Sed            std::swap(Offset1, Offset2);
850193323Sed
851193323Sed          // If the tail provided a bit enough offset, return noalias!
852193323Sed          if ((uint64_t)(Offset2-Offset1) >= SizeMax)
853193323Sed            return NoAlias;
854193323Sed          // Otherwise break - we don't look for another constant in the tail.
855193323Sed          break;
856193323Sed        }
857193323Sed    }
858193323Sed
859193323Sed    // Couldn't find anything useful.
860193323Sed    return MayAlias;
861193323Sed  }
862193323Sed
863193323Sed  // If there are non-equal constants arguments, then we can figure
864193323Sed  // out a minimum known delta between the two index expressions... at
865193323Sed  // this point we know that the first constant index of GEP1 is less
866193323Sed  // than the first constant index of GEP2.
867193323Sed
868193323Sed  // Advance BasePtr[12]Ty over this first differing constant operand.
869193323Sed  BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
870193323Sed      getTypeAtIndex(GEP2Ops[FirstConstantOper]);
871193323Sed  BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
872193323Sed      getTypeAtIndex(GEP1Ops[FirstConstantOper]);
873193323Sed
874193323Sed  // We are going to be using TargetData::getIndexedOffset to determine the
875193323Sed  // offset that each of the GEP's is reaching.  To do this, we have to convert
876193323Sed  // all variable references to constant references.  To do this, we convert the
877193323Sed  // initial sequence of array subscripts into constant zeros to start with.
878193323Sed  const Type *ZeroIdxTy = GEPPointerTy;
879193323Sed  for (unsigned i = 0; i != FirstConstantOper; ++i) {
880193323Sed    if (!isa<StructType>(ZeroIdxTy))
881198090Srdivacky      GEP1Ops[i] = GEP2Ops[i] =
882198090Srdivacky                              Constant::getNullValue(Type::getInt32Ty(Context));
883193323Sed
884193323Sed    if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
885193323Sed      ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
886193323Sed  }
887193323Sed
888193323Sed  // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
889193323Sed
890193323Sed  // Loop over the rest of the operands...
891193323Sed  for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
892193323Sed    const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
893193323Sed    const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
894193323Sed    // If they are equal, use a zero index...
895193323Sed    if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
896193323Sed      if (!isa<ConstantInt>(Op1))
897193323Sed        GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
898193323Sed      // Otherwise, just keep the constants we have.
899193323Sed    } else {
900193323Sed      if (Op1) {
901193323Sed        if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
902193323Sed          // If this is an array index, make sure the array element is in range.
903193323Sed          if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
904193323Sed            if (Op1C->getZExtValue() >= AT->getNumElements())
905193323Sed              return MayAlias;  // Be conservative with out-of-range accesses
906193323Sed          } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
907193323Sed            if (Op1C->getZExtValue() >= VT->getNumElements())
908193323Sed              return MayAlias;  // Be conservative with out-of-range accesses
909193323Sed          }
910193323Sed
911193323Sed        } else {
912193323Sed          // GEP1 is known to produce a value less than GEP2.  To be
913193323Sed          // conservatively correct, we must assume the largest possible
914193323Sed          // constant is used in this position.  This cannot be the initial
915193323Sed          // index to the GEP instructions (because we know we have at least one
916193323Sed          // element before this one with the different constant arguments), so
917193323Sed          // we know that the current index must be into either a struct or
918193323Sed          // array.  Because we know it's not constant, this cannot be a
919193323Sed          // structure index.  Because of this, we can calculate the maximum
920193323Sed          // value possible.
921193323Sed          //
922193323Sed          if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
923198090Srdivacky            GEP1Ops[i] =
924198090Srdivacky                  ConstantInt::get(Type::getInt64Ty(Context),
925198090Srdivacky                                   AT->getNumElements()-1);
926193323Sed          else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
927198090Srdivacky            GEP1Ops[i] =
928198090Srdivacky                  ConstantInt::get(Type::getInt64Ty(Context),
929198090Srdivacky                                   VT->getNumElements()-1);
930193323Sed        }
931193323Sed      }
932193323Sed
933193323Sed      if (Op2) {
934193323Sed        if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
935193323Sed          // If this is an array index, make sure the array element is in range.
936193323Sed          if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
937193323Sed            if (Op2C->getZExtValue() >= AT->getNumElements())
938193323Sed              return MayAlias;  // Be conservative with out-of-range accesses
939193323Sed          } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
940193323Sed            if (Op2C->getZExtValue() >= VT->getNumElements())
941193323Sed              return MayAlias;  // Be conservative with out-of-range accesses
942193323Sed          }
943193323Sed        } else {  // Conservatively assume the minimum value for this index
944193323Sed          GEP2Ops[i] = Constant::getNullValue(Op2->getType());
945193323Sed        }
946193323Sed      }
947193323Sed    }
948193323Sed
949193323Sed    if (BasePtr1Ty && Op1) {
950193323Sed      if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
951193323Sed        BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
952193323Sed      else
953193323Sed        BasePtr1Ty = 0;
954193323Sed    }
955193323Sed
956193323Sed    if (BasePtr2Ty && Op2) {
957193323Sed      if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
958193323Sed        BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
959193323Sed      else
960193323Sed        BasePtr2Ty = 0;
961193323Sed    }
962193323Sed  }
963193323Sed
964198090Srdivacky  if (TD && GEPPointerTy->getElementType()->isSized()) {
965193323Sed    int64_t Offset1 =
966198090Srdivacky      TD->getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
967193323Sed    int64_t Offset2 =
968198090Srdivacky      TD->getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
969193323Sed    assert(Offset1 != Offset2 &&
970193323Sed           "There is at least one different constant here!");
971193323Sed
972193323Sed    // Make sure we compare the absolute difference.
973193323Sed    if (Offset1 > Offset2)
974193323Sed      std::swap(Offset1, Offset2);
975193323Sed
976193323Sed    if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
977193323Sed      //cerr << "Determined that these two GEP's don't alias ["
978193323Sed      //     << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
979193323Sed      return NoAlias;
980193323Sed    }
981193323Sed  }
982193323Sed  return MayAlias;
983193323Sed}
984193323Sed
985193323Sed// Make sure that anything that uses AliasAnalysis pulls in this file...
986193323SedDEFINING_FILE_FOR(BasicAliasAnalysis)
987