BasicAliasAnalysis.cpp revision 207618
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/Passes.h"
18193323Sed#include "llvm/Constants.h"
19193323Sed#include "llvm/DerivedTypes.h"
20193323Sed#include "llvm/Function.h"
21193323Sed#include "llvm/GlobalVariable.h"
22193323Sed#include "llvm/Instructions.h"
23193323Sed#include "llvm/IntrinsicInst.h"
24198090Srdivacky#include "llvm/Operator.h"
25193323Sed#include "llvm/Pass.h"
26199989Srdivacky#include "llvm/Analysis/CaptureTracking.h"
27199989Srdivacky#include "llvm/Analysis/MemoryBuiltins.h"
28199989Srdivacky#include "llvm/Analysis/ValueTracking.h"
29193323Sed#include "llvm/Target/TargetData.h"
30199989Srdivacky#include "llvm/ADT/SmallPtrSet.h"
31193323Sed#include "llvm/ADT/SmallVector.h"
32198090Srdivacky#include "llvm/Support/ErrorHandling.h"
33193323Sed#include <algorithm>
34193323Sedusing namespace llvm;
35193323Sed
36193323Sed//===----------------------------------------------------------------------===//
37193323Sed// Useful predicates
38193323Sed//===----------------------------------------------------------------------===//
39193323Sed
40193323Sed/// isKnownNonNull - Return true if we know that the specified value is never
41193323Sed/// null.
42193323Sedstatic bool isKnownNonNull(const Value *V) {
43193323Sed  // Alloca never returns null, malloc might.
44193323Sed  if (isa<AllocaInst>(V)) return true;
45193323Sed
46193323Sed  // A byval argument is never null.
47193323Sed  if (const Argument *A = dyn_cast<Argument>(V))
48193323Sed    return A->hasByValAttr();
49193323Sed
50193323Sed  // Global values are not null unless extern weak.
51193323Sed  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
52193323Sed    return !GV->hasExternalWeakLinkage();
53193323Sed  return false;
54193323Sed}
55193323Sed
56193323Sed/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
57193323Sed/// object that never escapes from the function.
58193323Sedstatic bool isNonEscapingLocalObject(const Value *V) {
59193323Sed  // If this is a local allocation, check to see if it escapes.
60198892Srdivacky  if (isa<AllocaInst>(V) || isNoAliasCall(V))
61199989Srdivacky    // Set StoreCaptures to True so that we can assume in our callers that the
62199989Srdivacky    // pointer is not the result of a load instruction. Currently
63199989Srdivacky    // PointerMayBeCaptured doesn't have any special analysis for the
64199989Srdivacky    // StoreCaptures=false case; if it did, our callers could be refined to be
65199989Srdivacky    // more precise.
66199989Srdivacky    return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
67193323Sed
68193323Sed  // If this is an argument that corresponds to a byval or noalias argument,
69193323Sed  // then it has not escaped before entering the function.  Check if it escapes
70193323Sed  // inside the function.
71193323Sed  if (const Argument *A = dyn_cast<Argument>(V))
72193323Sed    if (A->hasByValAttr() || A->hasNoAliasAttr()) {
73193323Sed      // Don't bother analyzing arguments already known not to escape.
74193323Sed      if (A->hasNoCaptureAttr())
75193323Sed        return true;
76199989Srdivacky      return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
77193323Sed    }
78193323Sed  return false;
79193323Sed}
80193323Sed
81193323Sed
82193323Sed/// isObjectSmallerThan - Return true if we can prove that the object specified
83193323Sed/// by V is smaller than Size.
84193323Sedstatic bool isObjectSmallerThan(const Value *V, unsigned Size,
85199481Srdivacky                                const TargetData &TD) {
86193323Sed  const Type *AccessTy;
87193323Sed  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
88193323Sed    AccessTy = GV->getType()->getElementType();
89198892Srdivacky  } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
90193323Sed    if (!AI->isArrayAllocation())
91193323Sed      AccessTy = AI->getType()->getElementType();
92193323Sed    else
93193323Sed      return false;
94198090Srdivacky  } else if (const CallInst* CI = extractMallocCall(V)) {
95199481Srdivacky    if (!isArrayMalloc(V, &TD))
96198090Srdivacky      // The size is the argument to the malloc call.
97198090Srdivacky      if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
98198090Srdivacky        return (C->getZExtValue() < Size);
99198090Srdivacky    return false;
100193323Sed  } else if (const Argument *A = dyn_cast<Argument>(V)) {
101193323Sed    if (A->hasByValAttr())
102193323Sed      AccessTy = cast<PointerType>(A->getType())->getElementType();
103193323Sed    else
104193323Sed      return false;
105193323Sed  } else {
106193323Sed    return false;
107193323Sed  }
108193323Sed
109193323Sed  if (AccessTy->isSized())
110193323Sed    return TD.getTypeAllocSize(AccessTy) < Size;
111193323Sed  return false;
112193323Sed}
113193323Sed
114193323Sed//===----------------------------------------------------------------------===//
115193323Sed// NoAA Pass
116193323Sed//===----------------------------------------------------------------------===//
117193323Sed
118193323Sednamespace {
119193323Sed  /// NoAA - This class implements the -no-aa pass, which always returns "I
120193323Sed  /// don't know" for alias queries.  NoAA is unlike other alias analysis
121193323Sed  /// implementations, in that it does not chain to a previous analysis.  As
122193323Sed  /// such it doesn't follow many of the rules that other alias analyses must.
123193323Sed  ///
124198892Srdivacky  struct NoAA : public ImmutablePass, public AliasAnalysis {
125193323Sed    static char ID; // Class identification, replacement for typeinfo
126193323Sed    NoAA() : ImmutablePass(&ID) {}
127193323Sed    explicit NoAA(void *PID) : ImmutablePass(PID) { }
128193323Sed
129193323Sed    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
130193323Sed    }
131193323Sed
132193323Sed    virtual void initializePass() {
133198090Srdivacky      TD = getAnalysisIfAvailable<TargetData>();
134193323Sed    }
135193323Sed
136193323Sed    virtual AliasResult alias(const Value *V1, unsigned V1Size,
137193323Sed                              const Value *V2, unsigned V2Size) {
138193323Sed      return MayAlias;
139193323Sed    }
140193323Sed
141193323Sed    virtual void getArgumentAccesses(Function *F, CallSite CS,
142193323Sed                                     std::vector<PointerAccessInfo> &Info) {
143198090Srdivacky      llvm_unreachable("This method may not be called on this function!");
144193323Sed    }
145193323Sed
146193323Sed    virtual bool pointsToConstantMemory(const Value *P) { return false; }
147193323Sed    virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
148193323Sed      return ModRef;
149193323Sed    }
150193323Sed    virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
151193323Sed      return ModRef;
152193323Sed    }
153193323Sed
154193323Sed    virtual void deleteValue(Value *V) {}
155193323Sed    virtual void copyValue(Value *From, Value *To) {}
156202878Srdivacky
157202878Srdivacky    /// getAdjustedAnalysisPointer - This method is used when a pass implements
158202878Srdivacky    /// an analysis interface through multiple inheritance.  If needed, it should
159202878Srdivacky    /// override this to adjust the this pointer as needed for the specified pass
160202878Srdivacky    /// info.
161202878Srdivacky    virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
162202878Srdivacky      if (PI->isPassID(&AliasAnalysis::ID))
163202878Srdivacky        return (AliasAnalysis*)this;
164202878Srdivacky      return this;
165202878Srdivacky    }
166193323Sed  };
167193323Sed}  // End of anonymous namespace
168193323Sed
169193323Sed// Register this pass...
170193323Sedchar NoAA::ID = 0;
171193323Sedstatic RegisterPass<NoAA>
172193323SedU("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
173193323Sed
174193323Sed// Declare that we implement the AliasAnalysis interface
175193323Sedstatic RegisterAnalysisGroup<AliasAnalysis> V(U);
176193323Sed
177193323SedImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
178193323Sed
179193323Sed//===----------------------------------------------------------------------===//
180193323Sed// BasicAA Pass
181193323Sed//===----------------------------------------------------------------------===//
182193323Sed
183193323Sednamespace {
184193323Sed  /// BasicAliasAnalysis - This is the default alias analysis implementation.
185193323Sed  /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
186193323Sed  /// derives from the NoAA class.
187198892Srdivacky  struct BasicAliasAnalysis : public NoAA {
188193323Sed    static char ID; // Class identification, replacement for typeinfo
189193323Sed    BasicAliasAnalysis() : NoAA(&ID) {}
190193323Sed    AliasResult alias(const Value *V1, unsigned V1Size,
191198090Srdivacky                      const Value *V2, unsigned V2Size) {
192198090Srdivacky      assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
193198090Srdivacky      AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
194198090Srdivacky      VisitedPHIs.clear();
195198090Srdivacky      return Alias;
196198090Srdivacky    }
197193323Sed
198193323Sed    ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
199193323Sed    ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
200193323Sed
201193323Sed    /// pointsToConstantMemory - Chase pointers until we find a (constant
202193323Sed    /// global) or not.
203193323Sed    bool pointsToConstantMemory(const Value *P);
204193323Sed
205202878Srdivacky    /// getAdjustedAnalysisPointer - This method is used when a pass implements
206202878Srdivacky    /// an analysis interface through multiple inheritance.  If needed, it should
207202878Srdivacky    /// override this to adjust the this pointer as needed for the specified pass
208202878Srdivacky    /// info.
209202878Srdivacky    virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
210202878Srdivacky      if (PI->isPassID(&AliasAnalysis::ID))
211202878Srdivacky        return (AliasAnalysis*)this;
212202878Srdivacky      return this;
213202878Srdivacky    }
214202878Srdivacky
215193323Sed  private:
216198090Srdivacky    // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
217198892Srdivacky    SmallPtrSet<const Value*, 16> VisitedPHIs;
218198090Srdivacky
219199989Srdivacky    // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
220199989Srdivacky    // instruction against another.
221199989Srdivacky    AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
222199989Srdivacky                         const Value *V2, unsigned V2Size,
223199989Srdivacky                         const Value *UnderlyingV1, const Value *UnderlyingV2);
224198090Srdivacky
225199989Srdivacky    // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
226199989Srdivacky    // instruction against another.
227198090Srdivacky    AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
228198090Srdivacky                         const Value *V2, unsigned V2Size);
229198090Srdivacky
230198892Srdivacky    /// aliasSelect - Disambiguate a Select instruction against another value.
231198892Srdivacky    AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
232198892Srdivacky                            const Value *V2, unsigned V2Size);
233198892Srdivacky
234198090Srdivacky    AliasResult aliasCheck(const Value *V1, unsigned V1Size,
235198090Srdivacky                           const Value *V2, unsigned V2Size);
236193323Sed  };
237193323Sed}  // End of anonymous namespace
238193323Sed
239193323Sed// Register this pass...
240193323Sedchar BasicAliasAnalysis::ID = 0;
241193323Sedstatic RegisterPass<BasicAliasAnalysis>
242193323SedX("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
243193323Sed
244193323Sed// Declare that we implement the AliasAnalysis interface
245193323Sedstatic RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
246193323Sed
247193323SedImmutablePass *llvm::createBasicAliasAnalysisPass() {
248193323Sed  return new BasicAliasAnalysis();
249193323Sed}
250193323Sed
251193323Sed
252193323Sed/// pointsToConstantMemory - Chase pointers until we find a (constant
253193323Sed/// global) or not.
254193323Sedbool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
255193323Sed  if (const GlobalVariable *GV =
256193323Sed        dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
257199989Srdivacky    // Note: this doesn't require GV to be "ODR" because it isn't legal for a
258199989Srdivacky    // global to be marked constant in some modules and non-constant in others.
259199989Srdivacky    // GV may even be a declaration, not a definition.
260193323Sed    return GV->isConstant();
261193323Sed  return false;
262193323Sed}
263193323Sed
264193323Sed
265199989Srdivacky/// getModRefInfo - Check to see if the specified callsite can clobber the
266199989Srdivacky/// specified memory object.  Since we only look at local properties of this
267199989Srdivacky/// function, we really can't say much about this query.  We do, however, use
268199989Srdivacky/// simple "address taken" analysis on local objects.
269193323SedAliasAnalysis::ModRefResult
270193323SedBasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
271199989Srdivacky  const Value *Object = P->getUnderlyingObject();
272199989Srdivacky
273199989Srdivacky  // If this is a tail call and P points to a stack location, we know that
274199989Srdivacky  // the tail call cannot access or modify the local stack.
275199989Srdivacky  // We cannot exclude byval arguments here; these belong to the caller of
276199989Srdivacky  // the current function not to the current function, and a tail callee
277199989Srdivacky  // may reference them.
278199989Srdivacky  if (isa<AllocaInst>(Object))
279199989Srdivacky    if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
280199989Srdivacky      if (CI->isTailCall())
281199989Srdivacky        return NoModRef;
282199989Srdivacky
283199989Srdivacky  // If the pointer is to a locally allocated object that does not escape,
284199989Srdivacky  // then the call can not mod/ref the pointer unless the call takes the pointer
285199989Srdivacky  // as an argument, and itself doesn't capture it.
286199989Srdivacky  if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
287199989Srdivacky      isNonEscapingLocalObject(Object)) {
288199989Srdivacky    bool PassedAsArg = false;
289199989Srdivacky    unsigned ArgNo = 0;
290199989Srdivacky    for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
291199989Srdivacky         CI != CE; ++CI, ++ArgNo) {
292199989Srdivacky      // Only look at the no-capture pointer arguments.
293204642Srdivacky      if (!(*CI)->getType()->isPointerTy() ||
294199989Srdivacky          !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
295199989Srdivacky        continue;
296193323Sed
297199989Srdivacky      // If  this is a no-capture pointer argument, see if we can tell that it
298199989Srdivacky      // is impossible to alias the pointer we're checking.  If not, we have to
299199989Srdivacky      // assume that the call could touch the pointer, even though it doesn't
300199989Srdivacky      // escape.
301199989Srdivacky      if (!isNoAlias(cast<Value>(CI), ~0U, P, ~0U)) {
302199989Srdivacky        PassedAsArg = true;
303198113Srdivacky        break;
304198090Srdivacky      }
305198090Srdivacky    }
306199989Srdivacky
307199989Srdivacky    if (!PassedAsArg)
308199989Srdivacky      return NoModRef;
309193323Sed  }
310193323Sed
311199989Srdivacky  // Finally, handle specific knowledge of intrinsics.
312199989Srdivacky  IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
313199989Srdivacky  if (II == 0)
314199989Srdivacky    return AliasAnalysis::getModRefInfo(CS, P, Size);
315199989Srdivacky
316199989Srdivacky  switch (II->getIntrinsicID()) {
317199989Srdivacky  default: break;
318199989Srdivacky  case Intrinsic::memcpy:
319199989Srdivacky  case Intrinsic::memmove: {
320199989Srdivacky    unsigned Len = ~0U;
321199989Srdivacky    if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
322199989Srdivacky      Len = LenCI->getZExtValue();
323199989Srdivacky    Value *Dest = II->getOperand(1);
324199989Srdivacky    Value *Src = II->getOperand(2);
325199989Srdivacky    if (isNoAlias(Dest, Len, P, Size)) {
326199989Srdivacky      if (isNoAlias(Src, Len, P, Size))
327199989Srdivacky        return NoModRef;
328199989Srdivacky      return Ref;
329199989Srdivacky    }
330199989Srdivacky    break;
331199989Srdivacky  }
332199989Srdivacky  case Intrinsic::memset:
333199989Srdivacky    // Since memset is 'accesses arguments' only, the AliasAnalysis base class
334199989Srdivacky    // will handle it for the variable length case.
335199989Srdivacky    if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
336199989Srdivacky      unsigned Len = LenCI->getZExtValue();
337199989Srdivacky      Value *Dest = II->getOperand(1);
338199989Srdivacky      if (isNoAlias(Dest, Len, P, Size))
339199989Srdivacky        return NoModRef;
340199989Srdivacky    }
341199989Srdivacky    break;
342199989Srdivacky  case Intrinsic::atomic_cmp_swap:
343199989Srdivacky  case Intrinsic::atomic_swap:
344199989Srdivacky  case Intrinsic::atomic_load_add:
345199989Srdivacky  case Intrinsic::atomic_load_sub:
346199989Srdivacky  case Intrinsic::atomic_load_and:
347199989Srdivacky  case Intrinsic::atomic_load_nand:
348199989Srdivacky  case Intrinsic::atomic_load_or:
349199989Srdivacky  case Intrinsic::atomic_load_xor:
350199989Srdivacky  case Intrinsic::atomic_load_max:
351199989Srdivacky  case Intrinsic::atomic_load_min:
352199989Srdivacky  case Intrinsic::atomic_load_umax:
353199989Srdivacky  case Intrinsic::atomic_load_umin:
354199989Srdivacky    if (TD) {
355199989Srdivacky      Value *Op1 = II->getOperand(1);
356199989Srdivacky      unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
357199989Srdivacky      if (isNoAlias(Op1, Op1Size, P, Size))
358199989Srdivacky        return NoModRef;
359199989Srdivacky    }
360199989Srdivacky    break;
361199989Srdivacky  case Intrinsic::lifetime_start:
362199989Srdivacky  case Intrinsic::lifetime_end:
363199989Srdivacky  case Intrinsic::invariant_start: {
364199989Srdivacky    unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
365199989Srdivacky    if (isNoAlias(II->getOperand(2), PtrSize, P, Size))
366199989Srdivacky      return NoModRef;
367199989Srdivacky    break;
368199989Srdivacky  }
369199989Srdivacky  case Intrinsic::invariant_end: {
370199989Srdivacky    unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
371199989Srdivacky    if (isNoAlias(II->getOperand(3), PtrSize, P, Size))
372199989Srdivacky      return NoModRef;
373199989Srdivacky    break;
374199989Srdivacky  }
375199989Srdivacky  }
376199989Srdivacky
377193323Sed  // The AliasAnalysis base class has some smarts, lets use them.
378193323Sed  return AliasAnalysis::getModRefInfo(CS, P, Size);
379193323Sed}
380193323Sed
381193323Sed
382193323SedAliasAnalysis::ModRefResult
383193323SedBasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
384193323Sed  // If CS1 or CS2 are readnone, they don't interact.
385193323Sed  ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
386193323Sed  if (CS1B == DoesNotAccessMemory) return NoModRef;
387193323Sed
388193323Sed  ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
389193323Sed  if (CS2B == DoesNotAccessMemory) return NoModRef;
390193323Sed
391193323Sed  // If they both only read from memory, just return ref.
392193323Sed  if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
393193323Sed    return Ref;
394193323Sed
395193323Sed  // Otherwise, fall back to NoAA (mod+ref).
396193323Sed  return NoAA::getModRefInfo(CS1, CS2);
397193323Sed}
398193323Sed
399199989Srdivacky/// GetIndiceDifference - Dest and Src are the variable indices from two
400199989Srdivacky/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
401199989Srdivacky/// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
402199989Srdivacky/// difference between the two pointers.
403199989Srdivackystatic void GetIndiceDifference(
404199989Srdivacky                      SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
405199989Srdivacky                const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
406199989Srdivacky  if (Src.empty()) return;
407199989Srdivacky
408199989Srdivacky  for (unsigned i = 0, e = Src.size(); i != e; ++i) {
409199989Srdivacky    const Value *V = Src[i].first;
410199989Srdivacky    int64_t Scale = Src[i].second;
411199989Srdivacky
412199989Srdivacky    // Find V in Dest.  This is N^2, but pointer indices almost never have more
413199989Srdivacky    // than a few variable indexes.
414199989Srdivacky    for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
415199989Srdivacky      if (Dest[j].first != V) continue;
416199989Srdivacky
417199989Srdivacky      // If we found it, subtract off Scale V's from the entry in Dest.  If it
418199989Srdivacky      // goes to zero, remove the entry.
419199989Srdivacky      if (Dest[j].second != Scale)
420199989Srdivacky        Dest[j].second -= Scale;
421199989Srdivacky      else
422199989Srdivacky        Dest.erase(Dest.begin()+j);
423199989Srdivacky      Scale = 0;
424199989Srdivacky      break;
425199989Srdivacky    }
426199989Srdivacky
427199989Srdivacky    // If we didn't consume this entry, add it to the end of the Dest list.
428199989Srdivacky    if (Scale)
429199989Srdivacky      Dest.push_back(std::make_pair(V, -Scale));
430199989Srdivacky  }
431199989Srdivacky}
432199989Srdivacky
433199989Srdivacky/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
434199989Srdivacky/// against another pointer.  We know that V1 is a GEP, but we don't know
435199989Srdivacky/// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
436199989Srdivacky/// UnderlyingV2 is the same for V2.
437199989Srdivacky///
438193323SedAliasAnalysis::AliasResult
439199989SrdivackyBasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
440199989Srdivacky                             const Value *V2, unsigned V2Size,
441199989Srdivacky                             const Value *UnderlyingV1,
442199989Srdivacky                             const Value *UnderlyingV2) {
443199989Srdivacky  int64_t GEP1BaseOffset;
444199989Srdivacky  SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
445199989Srdivacky
446193323Sed  // If we have two gep instructions with must-alias'ing base pointers, figure
447193323Sed  // out if the indexes to the GEP tell us anything about the derived pointer.
448199989Srdivacky  if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
449199989Srdivacky    // Do the base pointers alias?
450199989Srdivacky    AliasResult BaseAlias = aliasCheck(UnderlyingV1, ~0U, UnderlyingV2, ~0U);
451193323Sed
452199989Srdivacky    // If we get a No or May, then return it immediately, no amount of analysis
453199989Srdivacky    // will improve this situation.
454199989Srdivacky    if (BaseAlias != MustAlias) return BaseAlias;
455193323Sed
456199989Srdivacky    // Otherwise, we have a MustAlias.  Since the base pointers alias each other
457199989Srdivacky    // exactly, see if the computed offset from the common pointer tells us
458199989Srdivacky    // about the relation of the resulting pointer.
459199989Srdivacky    const Value *GEP1BasePtr =
460199989Srdivacky      DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
461199989Srdivacky
462199989Srdivacky    int64_t GEP2BaseOffset;
463199989Srdivacky    SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
464199989Srdivacky    const Value *GEP2BasePtr =
465199989Srdivacky      DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
466199989Srdivacky
467199989Srdivacky    // If DecomposeGEPExpression isn't able to look all the way through the
468199989Srdivacky    // addressing operation, we must not have TD and this is too complex for us
469199989Srdivacky    // to handle without it.
470199989Srdivacky    if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
471199989Srdivacky      assert(TD == 0 &&
472199989Srdivacky             "DecomposeGEPExpression and getUnderlyingObject disagree!");
473199989Srdivacky      return MayAlias;
474199989Srdivacky    }
475199989Srdivacky
476199989Srdivacky    // Subtract the GEP2 pointer from the GEP1 pointer to find out their
477199989Srdivacky    // symbolic difference.
478199989Srdivacky    GEP1BaseOffset -= GEP2BaseOffset;
479199989Srdivacky    GetIndiceDifference(GEP1VariableIndices, GEP2VariableIndices);
480199989Srdivacky
481199989Srdivacky  } else {
482199989Srdivacky    // Check to see if these two pointers are related by the getelementptr
483199989Srdivacky    // instruction.  If one pointer is a GEP with a non-zero index of the other
484199989Srdivacky    // pointer, we know they cannot alias.
485193323Sed
486199989Srdivacky    // If both accesses are unknown size, we can't do anything useful here.
487199989Srdivacky    if (V1Size == ~0U && V2Size == ~0U)
488199989Srdivacky      return MayAlias;
489193323Sed
490199989Srdivacky    AliasResult R = aliasCheck(UnderlyingV1, ~0U, V2, V2Size);
491199989Srdivacky    if (R != MustAlias)
492199989Srdivacky      // If V2 may alias GEP base pointer, conservatively returns MayAlias.
493199989Srdivacky      // If V2 is known not to alias GEP base pointer, then the two values
494199989Srdivacky      // cannot alias per GEP semantics: "A pointer value formed from a
495199989Srdivacky      // getelementptr instruction is associated with the addresses associated
496199989Srdivacky      // with the first operand of the getelementptr".
497199989Srdivacky      return R;
498193323Sed
499199989Srdivacky    const Value *GEP1BasePtr =
500199989Srdivacky      DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
501199989Srdivacky
502199989Srdivacky    // If DecomposeGEPExpression isn't able to look all the way through the
503199989Srdivacky    // addressing operation, we must not have TD and this is too complex for us
504199989Srdivacky    // to handle without it.
505199989Srdivacky    if (GEP1BasePtr != UnderlyingV1) {
506199989Srdivacky      assert(TD == 0 &&
507199989Srdivacky             "DecomposeGEPExpression and getUnderlyingObject disagree!");
508199989Srdivacky      return MayAlias;
509193323Sed    }
510193323Sed  }
511199989Srdivacky
512199989Srdivacky  // In the two GEP Case, if there is no difference in the offsets of the
513199989Srdivacky  // computed pointers, the resultant pointers are a must alias.  This
514199989Srdivacky  // hapens when we have two lexically identical GEP's (for example).
515193323Sed  //
516199989Srdivacky  // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
517199989Srdivacky  // must aliases the GEP, the end result is a must alias also.
518199989Srdivacky  if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
519198090Srdivacky    return MustAlias;
520193323Sed
521199989Srdivacky  // If we have a known constant offset, see if this offset is larger than the
522199989Srdivacky  // access size being queried.  If so, and if no variable indices can remove
523199989Srdivacky  // pieces of this constant, then we know we have a no-alias.  For example,
524199989Srdivacky  //   &A[100] != &A.
525199989Srdivacky
526199989Srdivacky  // In order to handle cases like &A[100][i] where i is an out of range
527199989Srdivacky  // subscript, we have to ignore all constant offset pieces that are a multiple
528199989Srdivacky  // of a scaled index.  Do this by removing constant offsets that are a
529199989Srdivacky  // multiple of any of our variable indices.  This allows us to transform
530199989Srdivacky  // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
531199989Srdivacky  // provides an offset of 4 bytes (assuming a <= 4 byte access).
532199989Srdivacky  for (unsigned i = 0, e = GEP1VariableIndices.size();
533199989Srdivacky       i != e && GEP1BaseOffset;++i)
534199989Srdivacky    if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
535199989Srdivacky      GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
536199989Srdivacky
537199989Srdivacky  // If our known offset is bigger than the access size, we know we don't have
538199989Srdivacky  // an alias.
539199989Srdivacky  if (GEP1BaseOffset) {
540199989Srdivacky    if (GEP1BaseOffset >= (int64_t)V2Size ||
541199989Srdivacky        GEP1BaseOffset <= -(int64_t)V1Size)
542198090Srdivacky      return NoAlias;
543198090Srdivacky  }
544199989Srdivacky
545193323Sed  return MayAlias;
546193323Sed}
547193323Sed
548199989Srdivacky/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
549199989Srdivacky/// instruction against another.
550198892SrdivackyAliasAnalysis::AliasResult
551198892SrdivackyBasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
552198892Srdivacky                                const Value *V2, unsigned V2Size) {
553198892Srdivacky  // If the values are Selects with the same condition, we can do a more precise
554198892Srdivacky  // check: just check for aliases between the values on corresponding arms.
555198892Srdivacky  if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
556198892Srdivacky    if (SI->getCondition() == SI2->getCondition()) {
557198892Srdivacky      AliasResult Alias =
558198892Srdivacky        aliasCheck(SI->getTrueValue(), SISize,
559198892Srdivacky                   SI2->getTrueValue(), V2Size);
560198892Srdivacky      if (Alias == MayAlias)
561198892Srdivacky        return MayAlias;
562198892Srdivacky      AliasResult ThisAlias =
563198892Srdivacky        aliasCheck(SI->getFalseValue(), SISize,
564198892Srdivacky                   SI2->getFalseValue(), V2Size);
565198892Srdivacky      if (ThisAlias != Alias)
566198892Srdivacky        return MayAlias;
567198892Srdivacky      return Alias;
568198892Srdivacky    }
569198892Srdivacky
570198892Srdivacky  // If both arms of the Select node NoAlias or MustAlias V2, then returns
571198892Srdivacky  // NoAlias / MustAlias. Otherwise, returns MayAlias.
572198892Srdivacky  AliasResult Alias =
573198892Srdivacky    aliasCheck(SI->getTrueValue(), SISize, V2, V2Size);
574198892Srdivacky  if (Alias == MayAlias)
575198892Srdivacky    return MayAlias;
576198892Srdivacky  AliasResult ThisAlias =
577198892Srdivacky    aliasCheck(SI->getFalseValue(), SISize, V2, V2Size);
578198892Srdivacky  if (ThisAlias != Alias)
579198892Srdivacky    return MayAlias;
580198892Srdivacky  return Alias;
581198892Srdivacky}
582198892Srdivacky
583198090Srdivacky// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
584198090Srdivacky// against another.
585198090SrdivackyAliasAnalysis::AliasResult
586198090SrdivackyBasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
587198090Srdivacky                             const Value *V2, unsigned V2Size) {
588198090Srdivacky  // The PHI node has already been visited, avoid recursion any further.
589198090Srdivacky  if (!VisitedPHIs.insert(PN))
590198090Srdivacky    return MayAlias;
591198090Srdivacky
592198892Srdivacky  // If the values are PHIs in the same block, we can do a more precise
593198892Srdivacky  // as well as efficient check: just check for aliases between the values
594198892Srdivacky  // on corresponding edges.
595198892Srdivacky  if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
596198892Srdivacky    if (PN2->getParent() == PN->getParent()) {
597198892Srdivacky      AliasResult Alias =
598198892Srdivacky        aliasCheck(PN->getIncomingValue(0), PNSize,
599198892Srdivacky                   PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
600198892Srdivacky                   V2Size);
601198892Srdivacky      if (Alias == MayAlias)
602198892Srdivacky        return MayAlias;
603198892Srdivacky      for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
604198892Srdivacky        AliasResult ThisAlias =
605198892Srdivacky          aliasCheck(PN->getIncomingValue(i), PNSize,
606198892Srdivacky                     PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
607198892Srdivacky                     V2Size);
608198892Srdivacky        if (ThisAlias != Alias)
609198892Srdivacky          return MayAlias;
610198892Srdivacky      }
611198892Srdivacky      return Alias;
612198892Srdivacky    }
613198892Srdivacky
614198396Srdivacky  SmallPtrSet<Value*, 4> UniqueSrc;
615198090Srdivacky  SmallVector<Value*, 4> V1Srcs;
616198090Srdivacky  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
617198090Srdivacky    Value *PV1 = PN->getIncomingValue(i);
618198090Srdivacky    if (isa<PHINode>(PV1))
619198090Srdivacky      // If any of the source itself is a PHI, return MayAlias conservatively
620198090Srdivacky      // to avoid compile time explosion. The worst possible case is if both
621198090Srdivacky      // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
622198090Srdivacky      // and 'n' are the number of PHI sources.
623198090Srdivacky      return MayAlias;
624198090Srdivacky    if (UniqueSrc.insert(PV1))
625198090Srdivacky      V1Srcs.push_back(PV1);
626198090Srdivacky  }
627198090Srdivacky
628198892Srdivacky  AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
629198090Srdivacky  // Early exit if the check of the first PHI source against V2 is MayAlias.
630198090Srdivacky  // Other results are not possible.
631198090Srdivacky  if (Alias == MayAlias)
632198090Srdivacky    return MayAlias;
633198090Srdivacky
634198090Srdivacky  // If all sources of the PHI node NoAlias or MustAlias V2, then returns
635198090Srdivacky  // NoAlias / MustAlias. Otherwise, returns MayAlias.
636198090Srdivacky  for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
637198090Srdivacky    Value *V = V1Srcs[i];
638198892Srdivacky
639198892Srdivacky    // If V2 is a PHI, the recursive case will have been caught in the
640198892Srdivacky    // above aliasCheck call, so these subsequent calls to aliasCheck
641198892Srdivacky    // don't need to assume that V2 is being visited recursively.
642198892Srdivacky    VisitedPHIs.erase(V2);
643198892Srdivacky
644198396Srdivacky    AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
645198090Srdivacky    if (ThisAlias != Alias || ThisAlias == MayAlias)
646198090Srdivacky      return MayAlias;
647198090Srdivacky  }
648198090Srdivacky
649198090Srdivacky  return Alias;
650198090Srdivacky}
651198090Srdivacky
652198090Srdivacky// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
653198090Srdivacky// such as array references.
654198090Srdivacky//
655198090SrdivackyAliasAnalysis::AliasResult
656198090SrdivackyBasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
657198090Srdivacky                               const Value *V2, unsigned V2Size) {
658207618Srdivacky  // If either of the memory references is empty, it doesn't matter what the
659207618Srdivacky  // pointer values are.
660207618Srdivacky  if (V1Size == 0 || V2Size == 0)
661207618Srdivacky    return NoAlias;
662207618Srdivacky
663198090Srdivacky  // Strip off any casts if they exist.
664198090Srdivacky  V1 = V1->stripPointerCasts();
665198090Srdivacky  V2 = V2->stripPointerCasts();
666198090Srdivacky
667198090Srdivacky  // Are we checking for alias of the same value?
668198090Srdivacky  if (V1 == V2) return MustAlias;
669198090Srdivacky
670204642Srdivacky  if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
671198090Srdivacky    return NoAlias;  // Scalars cannot alias each other
672198090Srdivacky
673198090Srdivacky  // Figure out what objects these things are pointing to if we can.
674198090Srdivacky  const Value *O1 = V1->getUnderlyingObject();
675198090Srdivacky  const Value *O2 = V2->getUnderlyingObject();
676198090Srdivacky
677199481Srdivacky  // Null values in the default address space don't point to any object, so they
678199481Srdivacky  // don't alias any other pointer.
679199481Srdivacky  if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
680199481Srdivacky    if (CPN->getType()->getAddressSpace() == 0)
681199481Srdivacky      return NoAlias;
682199481Srdivacky  if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
683199481Srdivacky    if (CPN->getType()->getAddressSpace() == 0)
684199481Srdivacky      return NoAlias;
685199481Srdivacky
686198090Srdivacky  if (O1 != O2) {
687198090Srdivacky    // If V1/V2 point to two different objects we know that we have no alias.
688198090Srdivacky    if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
689198090Srdivacky      return NoAlias;
690199481Srdivacky
691199481Srdivacky    // Constant pointers can't alias with non-const isIdentifiedObject objects.
692199481Srdivacky    if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
693199481Srdivacky        (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
694199481Srdivacky      return NoAlias;
695199481Srdivacky
696198090Srdivacky    // Arguments can't alias with local allocations or noalias calls.
697198892Srdivacky    if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
698198892Srdivacky        (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
699198090Srdivacky      return NoAlias;
700198090Srdivacky
701198090Srdivacky    // Most objects can't alias null.
702198090Srdivacky    if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
703198090Srdivacky        (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
704198090Srdivacky      return NoAlias;
705198090Srdivacky  }
706198090Srdivacky
707198090Srdivacky  // If the size of one access is larger than the entire object on the other
708198090Srdivacky  // side, then we know such behavior is undefined and can assume no alias.
709198090Srdivacky  if (TD)
710199481Srdivacky    if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
711199481Srdivacky        (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
712198090Srdivacky      return NoAlias;
713198090Srdivacky
714199989Srdivacky  // If one pointer is the result of a call/invoke or load and the other is a
715198090Srdivacky  // non-escaping local object, then we know the object couldn't escape to a
716199989Srdivacky  // point where the call could return it. The load case works because
717199989Srdivacky  // isNonEscapingLocalObject considers all stores to be escapes (it
718199989Srdivacky  // passes true for the StoreCaptures argument to PointerMayBeCaptured).
719199989Srdivacky  if (O1 != O2) {
720199989Srdivacky    if ((isa<CallInst>(O1) || isa<InvokeInst>(O1) || isa<LoadInst>(O1) ||
721199989Srdivacky         isa<Argument>(O1)) &&
722199989Srdivacky        isNonEscapingLocalObject(O2))
723199989Srdivacky      return NoAlias;
724199989Srdivacky    if ((isa<CallInst>(O2) || isa<InvokeInst>(O2) || isa<LoadInst>(O2) ||
725199989Srdivacky         isa<Argument>(O2)) &&
726199989Srdivacky        isNonEscapingLocalObject(O1))
727199989Srdivacky      return NoAlias;
728199989Srdivacky  }
729198090Srdivacky
730199989Srdivacky  // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
731199989Srdivacky  // GEP can't simplify, we don't even look at the PHI cases.
732198396Srdivacky  if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
733198090Srdivacky    std::swap(V1, V2);
734198090Srdivacky    std::swap(V1Size, V2Size);
735199989Srdivacky    std::swap(O1, O2);
736198090Srdivacky  }
737199989Srdivacky  if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
738199989Srdivacky    return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
739198090Srdivacky
740198090Srdivacky  if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
741198090Srdivacky    std::swap(V1, V2);
742198090Srdivacky    std::swap(V1Size, V2Size);
743198090Srdivacky  }
744198090Srdivacky  if (const PHINode *PN = dyn_cast<PHINode>(V1))
745198090Srdivacky    return aliasPHI(PN, V1Size, V2, V2Size);
746198090Srdivacky
747198892Srdivacky  if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
748198892Srdivacky    std::swap(V1, V2);
749198892Srdivacky    std::swap(V1Size, V2Size);
750198892Srdivacky  }
751198892Srdivacky  if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
752198892Srdivacky    return aliasSelect(S1, V1Size, V2, V2Size);
753198892Srdivacky
754198090Srdivacky  return MayAlias;
755198090Srdivacky}
756198090Srdivacky
757199989Srdivacky// Make sure that anything that uses AliasAnalysis pulls in this file.
758193323SedDEFINING_FILE_FOR(BasicAliasAnalysis)
759