1 //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the default implementation of the Alias Analysis interface
11 // that simply implements a few identities (two different globals cannot alias,
12 // etc), but otherwise does no analysis.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/CaptureTracking.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 static const Value *GetGEPOperands(const Value *V,
42 SmallVector<Value*, 16> &GEPOps) {
43 assert(GEPOps.empty() && "Expect empty list to populate!");
44 GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1,
45 cast<User>(V)->op_end());
47 // Accumulate all of the chained indexes into the operand array
48 V = cast<User>(V)->getOperand(0);
50 while (const GEPOperator *G = dyn_cast<GEPOperator>(V)) {
51 if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) ||
52 !cast<Constant>(GEPOps[0])->isNullValue())
53 break; // Don't handle folding arbitrary pointer offsets yet...
54 GEPOps.erase(GEPOps.begin()); // Drop the zero index
55 GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end());
61 /// isKnownNonNull - Return true if we know that the specified value is never
63 static bool isKnownNonNull(const Value *V) {
64 // Alloca never returns null, malloc might.
65 if (isa<AllocaInst>(V)) return true;
67 // A byval argument is never null.
68 if (const Argument *A = dyn_cast<Argument>(V))
69 return A->hasByValAttr();
71 // Global values are not null unless extern weak.
72 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
73 return !GV->hasExternalWeakLinkage();
77 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
78 /// object that never escapes from the function.
79 static bool isNonEscapingLocalObject(const Value *V) {
80 // If this is a local allocation, check to see if it escapes.
81 if (isa<AllocaInst>(V) || isNoAliasCall(V))
82 return !PointerMayBeCaptured(V, false);
84 // If this is an argument that corresponds to a byval or noalias argument,
85 // then it has not escaped before entering the function. Check if it escapes
86 // inside the function.
87 if (const Argument *A = dyn_cast<Argument>(V))
88 if (A->hasByValAttr() || A->hasNoAliasAttr()) {
89 // Don't bother analyzing arguments already known not to escape.
90 if (A->hasNoCaptureAttr())
92 return !PointerMayBeCaptured(V, false);
98 /// isObjectSmallerThan - Return true if we can prove that the object specified
99 /// by V is smaller than Size.
100 static bool isObjectSmallerThan(const Value *V, unsigned Size,
101 const TargetData &TD) {
102 const Type *AccessTy;
103 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
104 AccessTy = GV->getType()->getElementType();
105 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
106 if (!AI->isArrayAllocation())
107 AccessTy = AI->getType()->getElementType();
110 } else if (const CallInst* CI = extractMallocCall(V)) {
111 if (!isArrayMalloc(V, &TD))
112 // The size is the argument to the malloc call.
113 if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
114 return (C->getZExtValue() < Size);
116 } else if (const Argument *A = dyn_cast<Argument>(V)) {
117 if (A->hasByValAttr())
118 AccessTy = cast<PointerType>(A->getType())->getElementType();
125 if (AccessTy->isSized())
126 return TD.getTypeAllocSize(AccessTy) < Size;
130 //===----------------------------------------------------------------------===//
132 //===----------------------------------------------------------------------===//
135 /// NoAA - This class implements the -no-aa pass, which always returns "I
136 /// don't know" for alias queries. NoAA is unlike other alias analysis
137 /// implementations, in that it does not chain to a previous analysis. As
138 /// such it doesn't follow many of the rules that other alias analyses must.
140 struct NoAA : public ImmutablePass, public AliasAnalysis {
141 static char ID; // Class identification, replacement for typeinfo
142 NoAA() : ImmutablePass(&ID) {}
143 explicit NoAA(void *PID) : ImmutablePass(PID) { }
145 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
148 virtual void initializePass() {
149 TD = getAnalysisIfAvailable<TargetData>();
152 virtual AliasResult alias(const Value *V1, unsigned V1Size,
153 const Value *V2, unsigned V2Size) {
157 virtual void getArgumentAccesses(Function *F, CallSite CS,
158 std::vector<PointerAccessInfo> &Info) {
159 llvm_unreachable("This method may not be called on this function!");
162 virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { }
163 virtual bool pointsToConstantMemory(const Value *P) { return false; }
164 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
167 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
170 virtual bool hasNoModRefInfoForCalls() const { return true; }
172 virtual void deleteValue(Value *V) {}
173 virtual void copyValue(Value *From, Value *To) {}
175 } // End of anonymous namespace
177 // Register this pass...
179 static RegisterPass<NoAA>
180 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
182 // Declare that we implement the AliasAnalysis interface
183 static RegisterAnalysisGroup<AliasAnalysis> V(U);
185 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
187 //===----------------------------------------------------------------------===//
189 //===----------------------------------------------------------------------===//
192 /// BasicAliasAnalysis - This is the default alias analysis implementation.
193 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
194 /// derives from the NoAA class.
195 struct BasicAliasAnalysis : public NoAA {
196 static char ID; // Class identification, replacement for typeinfo
197 BasicAliasAnalysis() : NoAA(&ID) {}
198 AliasResult alias(const Value *V1, unsigned V1Size,
199 const Value *V2, unsigned V2Size) {
200 assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
201 AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
206 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
207 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
209 /// hasNoModRefInfoForCalls - We can provide mod/ref information against
210 /// non-escaping allocations.
211 virtual bool hasNoModRefInfoForCalls() const { return false; }
213 /// pointsToConstantMemory - Chase pointers until we find a (constant
215 bool pointsToConstantMemory(const Value *P);
218 // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
219 SmallPtrSet<const Value*, 16> VisitedPHIs;
221 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
223 AliasResult aliasGEP(const Value *V1, unsigned V1Size,
224 const Value *V2, unsigned V2Size);
226 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
228 AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
229 const Value *V2, unsigned V2Size);
231 /// aliasSelect - Disambiguate a Select instruction against another value.
232 AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
233 const Value *V2, unsigned V2Size);
235 AliasResult aliasCheck(const Value *V1, unsigned V1Size,
236 const Value *V2, unsigned V2Size);
238 // CheckGEPInstructions - Check two GEP instructions with known
239 // must-aliasing base pointers. This checks to see if the index expressions
240 // preclude the pointers from aliasing...
242 CheckGEPInstructions(const Type* BasePtr1Ty,
243 Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
244 const Type *BasePtr2Ty,
245 Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
247 } // End of anonymous namespace
249 // Register this pass...
250 char BasicAliasAnalysis::ID = 0;
251 static RegisterPass<BasicAliasAnalysis>
252 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
254 // Declare that we implement the AliasAnalysis interface
255 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
257 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
258 return new BasicAliasAnalysis();
262 /// pointsToConstantMemory - Chase pointers until we find a (constant
264 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
265 if (const GlobalVariable *GV =
266 dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
267 return GV->isConstant();
272 // getModRefInfo - Check to see if the specified callsite can clobber the
273 // specified memory object. Since we only look at local properties of this
274 // function, we really can't say much about this query. We do, however, use
275 // simple "address taken" analysis on local objects.
277 AliasAnalysis::ModRefResult
278 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
279 if (!isa<Constant>(P)) {
280 const Value *Object = P->getUnderlyingObject();
282 // If this is a tail call and P points to a stack location, we know that
283 // the tail call cannot access or modify the local stack.
284 // We cannot exclude byval arguments here; these belong to the caller of
285 // the current function not to the current function, and a tail callee
286 // may reference them.
287 if (isa<AllocaInst>(Object))
288 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
289 if (CI->isTailCall())
292 // If the pointer is to a locally allocated object that does not escape,
293 // then the call can not mod/ref the pointer unless the call takes the
294 // argument without capturing it.
295 if (isNonEscapingLocalObject(Object) && CS.getInstruction() != Object) {
296 bool passedAsArg = false;
297 // TODO: Eventually only check 'nocapture' arguments.
298 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
300 if (isa<PointerType>((*CI)->getType()) &&
301 alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias)
308 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
309 switch (II->getIntrinsicID()) {
311 case Intrinsic::memcpy:
312 case Intrinsic::memmove: {
314 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
315 Len = LenCI->getZExtValue();
316 Value *Dest = II->getOperand(1);
317 Value *Src = II->getOperand(2);
318 if (alias(Dest, Len, P, Size) == NoAlias) {
319 if (alias(Src, Len, P, Size) == NoAlias)
325 case Intrinsic::memset:
326 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
327 unsigned Len = LenCI->getZExtValue();
328 Value *Dest = II->getOperand(1);
329 if (alias(Dest, Len, P, Size) == NoAlias)
333 case Intrinsic::atomic_cmp_swap:
334 case Intrinsic::atomic_swap:
335 case Intrinsic::atomic_load_add:
336 case Intrinsic::atomic_load_sub:
337 case Intrinsic::atomic_load_and:
338 case Intrinsic::atomic_load_nand:
339 case Intrinsic::atomic_load_or:
340 case Intrinsic::atomic_load_xor:
341 case Intrinsic::atomic_load_max:
342 case Intrinsic::atomic_load_min:
343 case Intrinsic::atomic_load_umax:
344 case Intrinsic::atomic_load_umin:
346 Value *Op1 = II->getOperand(1);
347 unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
348 if (alias(Op1, Op1Size, P, Size) == NoAlias)
352 case Intrinsic::lifetime_start:
353 case Intrinsic::lifetime_end:
354 case Intrinsic::invariant_start: {
355 unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
356 if (alias(II->getOperand(2), PtrSize, P, Size) == NoAlias)
360 case Intrinsic::invariant_end: {
361 unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
362 if (alias(II->getOperand(3), PtrSize, P, Size) == NoAlias)
370 // The AliasAnalysis base class has some smarts, lets use them.
371 return AliasAnalysis::getModRefInfo(CS, P, Size);
375 AliasAnalysis::ModRefResult
376 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
377 // If CS1 or CS2 are readnone, they don't interact.
378 ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
379 if (CS1B == DoesNotAccessMemory) return NoModRef;
381 ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
382 if (CS2B == DoesNotAccessMemory) return NoModRef;
384 // If they both only read from memory, just return ref.
385 if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
388 // Otherwise, fall back to NoAA (mod+ref).
389 return NoAA::getModRefInfo(CS1, CS2);
392 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
395 AliasAnalysis::AliasResult
396 BasicAliasAnalysis::aliasGEP(const Value *V1, unsigned V1Size,
397 const Value *V2, unsigned V2Size) {
398 // If we have two gep instructions with must-alias'ing base pointers, figure
399 // out if the indexes to the GEP tell us anything about the derived pointer.
400 // Note that we also handle chains of getelementptr instructions as well as
401 // constant expression getelementptrs here.
403 if (isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
404 const User *GEP1 = cast<User>(V1);
405 const User *GEP2 = cast<User>(V2);
407 // If V1 and V2 are identical GEPs, just recurse down on both of them.
408 // This allows us to analyze things like:
409 // P = gep A, 0, i, 1
410 // Q = gep B, 0, i, 1
411 // by just analyzing A and B. This is even safe for variable indices.
412 if (GEP1->getType() == GEP2->getType() &&
413 GEP1->getNumOperands() == GEP2->getNumOperands() &&
414 GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
415 // All operands are the same, ignoring the base.
416 std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
417 return aliasCheck(GEP1->getOperand(0), V1Size,
418 GEP2->getOperand(0), V2Size);
420 // Drill down into the first non-gep value, to test for must-aliasing of
421 // the base pointers.
422 while (isa<GEPOperator>(GEP1->getOperand(0)) &&
423 GEP1->getOperand(1) ==
424 Constant::getNullValue(GEP1->getOperand(1)->getType()))
425 GEP1 = cast<User>(GEP1->getOperand(0));
426 const Value *BasePtr1 = GEP1->getOperand(0);
428 while (isa<GEPOperator>(GEP2->getOperand(0)) &&
429 GEP2->getOperand(1) ==
430 Constant::getNullValue(GEP2->getOperand(1)->getType()))
431 GEP2 = cast<User>(GEP2->getOperand(0));
432 const Value *BasePtr2 = GEP2->getOperand(0);
434 // Do the base pointers alias?
435 AliasResult BaseAlias = aliasCheck(BasePtr1, ~0U, BasePtr2, ~0U);
436 if (BaseAlias == NoAlias) return NoAlias;
437 if (BaseAlias == MustAlias) {
438 // If the base pointers alias each other exactly, check to see if we can
439 // figure out anything about the resultant pointers, to try to prove
442 // Collect all of the chained GEP operands together into one simple place
443 SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
444 BasePtr1 = GetGEPOperands(V1, GEP1Ops);
445 BasePtr2 = GetGEPOperands(V2, GEP2Ops);
447 // If GetGEPOperands were able to fold to the same must-aliased pointer,
448 // do the comparison.
449 if (BasePtr1 == BasePtr2) {
451 CheckGEPInstructions(BasePtr1->getType(),
452 &GEP1Ops[0], GEP1Ops.size(), V1Size,
454 &GEP2Ops[0], GEP2Ops.size(), V2Size);
455 if (GAlias != MayAlias)
461 // Check to see if these two pointers are related by a getelementptr
462 // instruction. If one pointer is a GEP with a non-zero index of the other
463 // pointer, we know they cannot alias.
465 if (V1Size == ~0U || V2Size == ~0U)
468 SmallVector<Value*, 16> GEPOperands;
469 const Value *BasePtr = GetGEPOperands(V1, GEPOperands);
471 AliasResult R = aliasCheck(BasePtr, ~0U, V2, V2Size);
473 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
474 // If V2 is known not to alias GEP base pointer, then the two values
475 // cannot alias per GEP semantics: "A pointer value formed from a
476 // getelementptr instruction is associated with the addresses associated
477 // with the first operand of the getelementptr".
480 // If there is at least one non-zero constant index, we know they cannot
482 bool ConstantFound = false;
483 bool AllZerosFound = true;
484 for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i)
485 if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) {
486 if (!C->isNullValue()) {
487 ConstantFound = true;
488 AllZerosFound = false;
492 AllZerosFound = false;
495 // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
496 // the ptr, the end result is a must alias also.
501 if (V2Size <= 1 && V1Size <= 1) // Just pointer check?
504 // Otherwise we have to check to see that the distance is more than
505 // the size of the argument... build an index vector that is equal to
506 // the arguments provided, except substitute 0's for any variable
507 // indexes we find...
509 cast<PointerType>(BasePtr->getType())->getElementType()->isSized()) {
510 for (unsigned i = 0; i != GEPOperands.size(); ++i)
511 if (!isa<ConstantInt>(GEPOperands[i]))
512 GEPOperands[i] = Constant::getNullValue(GEPOperands[i]->getType());
513 int64_t Offset = TD->getIndexedOffset(BasePtr->getType(),
517 if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size)
525 // aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select instruction
527 AliasAnalysis::AliasResult
528 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
529 const Value *V2, unsigned V2Size) {
530 // If the values are Selects with the same condition, we can do a more precise
531 // check: just check for aliases between the values on corresponding arms.
532 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
533 if (SI->getCondition() == SI2->getCondition()) {
535 aliasCheck(SI->getTrueValue(), SISize,
536 SI2->getTrueValue(), V2Size);
537 if (Alias == MayAlias)
539 AliasResult ThisAlias =
540 aliasCheck(SI->getFalseValue(), SISize,
541 SI2->getFalseValue(), V2Size);
542 if (ThisAlias != Alias)
547 // If both arms of the Select node NoAlias or MustAlias V2, then returns
548 // NoAlias / MustAlias. Otherwise, returns MayAlias.
550 aliasCheck(SI->getTrueValue(), SISize, V2, V2Size);
551 if (Alias == MayAlias)
553 AliasResult ThisAlias =
554 aliasCheck(SI->getFalseValue(), SISize, V2, V2Size);
555 if (ThisAlias != Alias)
560 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
562 AliasAnalysis::AliasResult
563 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
564 const Value *V2, unsigned V2Size) {
565 // The PHI node has already been visited, avoid recursion any further.
566 if (!VisitedPHIs.insert(PN))
569 // If the values are PHIs in the same block, we can do a more precise
570 // as well as efficient check: just check for aliases between the values
571 // on corresponding edges.
572 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
573 if (PN2->getParent() == PN->getParent()) {
575 aliasCheck(PN->getIncomingValue(0), PNSize,
576 PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
578 if (Alias == MayAlias)
580 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
581 AliasResult ThisAlias =
582 aliasCheck(PN->getIncomingValue(i), PNSize,
583 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
585 if (ThisAlias != Alias)
591 SmallPtrSet<Value*, 4> UniqueSrc;
592 SmallVector<Value*, 4> V1Srcs;
593 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
594 Value *PV1 = PN->getIncomingValue(i);
595 if (isa<PHINode>(PV1))
596 // If any of the source itself is a PHI, return MayAlias conservatively
597 // to avoid compile time explosion. The worst possible case is if both
598 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
599 // and 'n' are the number of PHI sources.
601 if (UniqueSrc.insert(PV1))
602 V1Srcs.push_back(PV1);
605 AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
606 // Early exit if the check of the first PHI source against V2 is MayAlias.
607 // Other results are not possible.
608 if (Alias == MayAlias)
611 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
612 // NoAlias / MustAlias. Otherwise, returns MayAlias.
613 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
614 Value *V = V1Srcs[i];
616 // If V2 is a PHI, the recursive case will have been caught in the
617 // above aliasCheck call, so these subsequent calls to aliasCheck
618 // don't need to assume that V2 is being visited recursively.
619 VisitedPHIs.erase(V2);
621 AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
622 if (ThisAlias != Alias || ThisAlias == MayAlias)
629 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
630 // such as array references.
632 AliasAnalysis::AliasResult
633 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
634 const Value *V2, unsigned V2Size) {
635 // Strip off any casts if they exist.
636 V1 = V1->stripPointerCasts();
637 V2 = V2->stripPointerCasts();
639 // Are we checking for alias of the same value?
640 if (V1 == V2) return MustAlias;
642 if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
643 return NoAlias; // Scalars cannot alias each other
645 // Figure out what objects these things are pointing to if we can.
646 const Value *O1 = V1->getUnderlyingObject();
647 const Value *O2 = V2->getUnderlyingObject();
649 // Null values in the default address space don't point to any object, so they
650 // don't alias any other pointer.
651 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
652 if (CPN->getType()->getAddressSpace() == 0)
654 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
655 if (CPN->getType()->getAddressSpace() == 0)
659 // If V1/V2 point to two different objects we know that we have no alias.
660 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
663 // Arguments can't alias with local allocations or noalias calls.
664 if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
665 (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
668 // Most objects can't alias null.
669 if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
670 (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
674 // If the size of one access is larger than the entire object on the other
675 // side, then we know such behavior is undefined and can assume no alias.
677 if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
678 (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
681 // If one pointer is the result of a call/invoke and the other is a
682 // non-escaping local object, then we know the object couldn't escape to a
683 // point where the call could return it.
684 if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) &&
685 isNonEscapingLocalObject(O2) && O1 != O2)
687 if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) &&
688 isNonEscapingLocalObject(O1) && O1 != O2)
691 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
693 std::swap(V1Size, V2Size);
695 if (isa<GEPOperator>(V1))
696 return aliasGEP(V1, V1Size, V2, V2Size);
698 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
700 std::swap(V1Size, V2Size);
702 if (const PHINode *PN = dyn_cast<PHINode>(V1))
703 return aliasPHI(PN, V1Size, V2, V2Size);
705 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
707 std::swap(V1Size, V2Size);
709 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
710 return aliasSelect(S1, V1Size, V2, V2Size);
715 // This function is used to determine if the indices of two GEP instructions are
716 // equal. V1 and V2 are the indices.
717 static bool IndexOperandsEqual(Value *V1, Value *V2) {
718 if (V1->getType() == V2->getType())
720 if (Constant *C1 = dyn_cast<Constant>(V1))
721 if (Constant *C2 = dyn_cast<Constant>(V2)) {
722 // Sign extend the constants to long types, if necessary
723 if (C1->getType() != Type::getInt64Ty(C1->getContext()))
724 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
725 if (C2->getType() != Type::getInt64Ty(C1->getContext()))
726 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
732 /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
733 /// base pointers. This checks to see if the index expressions preclude the
734 /// pointers from aliasing...
735 AliasAnalysis::AliasResult
736 BasicAliasAnalysis::CheckGEPInstructions(
737 const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
738 const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
739 // We currently can't handle the case when the base pointers have different
740 // primitive types. Since this is uncommon anyway, we are happy being
741 // extremely conservative.
742 if (BasePtr1Ty != BasePtr2Ty)
745 const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
747 // Find the (possibly empty) initial sequence of equal values... which are not
748 // necessarily constants.
749 unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
750 unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
751 unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
752 unsigned UnequalOper = 0;
753 while (UnequalOper != MinOperands &&
754 IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) {
755 // Advance through the type as we go...
757 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
758 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
760 // If all operands equal each other, then the derived pointers must
761 // alias each other...
763 assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
764 "Ran out of type nesting, but not out of operands?");
769 // If we have seen all constant operands, and run out of indexes on one of the
770 // getelementptrs, check to see if the tail of the leftover one is all zeros.
771 // If so, return mustalias.
772 if (UnequalOper == MinOperands) {
773 if (NumGEP1Ops < NumGEP2Ops) {
774 std::swap(GEP1Ops, GEP2Ops);
775 std::swap(NumGEP1Ops, NumGEP2Ops);
778 bool AllAreZeros = true;
779 for (unsigned i = UnequalOper; i != MaxOperands; ++i)
780 if (!isa<Constant>(GEP1Ops[i]) ||
781 !cast<Constant>(GEP1Ops[i])->isNullValue()) {
785 if (AllAreZeros) return MustAlias;
789 // So now we know that the indexes derived from the base pointers,
790 // which are known to alias, are different. We can still determine a
791 // no-alias result if there are differing constant pairs in the index
792 // chain. For example:
793 // A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
795 // We have to be careful here about array accesses. In particular, consider:
796 // A[1][0] vs A[0][i]
797 // In this case, we don't *know* that the array will be accessed in bounds:
798 // the index could even be negative. Because of this, we have to
799 // conservatively *give up* and return may alias. We disregard differing
800 // array subscripts that are followed by a variable index without going
803 unsigned SizeMax = std::max(G1S, G2S);
804 if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
806 // Scan for the first operand that is constant and unequal in the
807 // two getelementptrs...
808 unsigned FirstConstantOper = UnequalOper;
809 for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
810 const Value *G1Oper = GEP1Ops[FirstConstantOper];
811 const Value *G2Oper = GEP2Ops[FirstConstantOper];
813 if (G1Oper != G2Oper) // Found non-equal constant indexes...
814 if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
815 if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
816 if (G1OC->getType() != G2OC->getType()) {
817 // Sign extend both operands to long.
818 const Type *Int64Ty = Type::getInt64Ty(G1OC->getContext());
819 if (G1OC->getType() != Int64Ty)
820 G1OC = ConstantExpr::getSExt(G1OC, Int64Ty);
821 if (G2OC->getType() != Int64Ty)
822 G2OC = ConstantExpr::getSExt(G2OC, Int64Ty);
823 GEP1Ops[FirstConstantOper] = G1OC;
824 GEP2Ops[FirstConstantOper] = G2OC;
828 // Handle the "be careful" case above: if this is an array/vector
829 // subscript, scan for a subsequent variable array index.
830 if (const SequentialType *STy =
831 dyn_cast<SequentialType>(BasePtr1Ty)) {
832 const Type *NextTy = STy;
833 bool isBadCase = false;
835 for (unsigned Idx = FirstConstantOper;
836 Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
837 const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
838 if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
842 // If the array is indexed beyond the bounds of the static type
843 // at this level, it will also fall into the "be careful" case.
844 // It would theoretically be possible to analyze these cases,
845 // but for now just be conservatively correct.
846 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
847 if (cast<ConstantInt>(G1OC)->getZExtValue() >=
848 ATy->getNumElements() ||
849 cast<ConstantInt>(G2OC)->getZExtValue() >=
850 ATy->getNumElements()) {
854 if (const VectorType *VTy = dyn_cast<VectorType>(STy))
855 if (cast<ConstantInt>(G1OC)->getZExtValue() >=
856 VTy->getNumElements() ||
857 cast<ConstantInt>(G2OC)->getZExtValue() >=
858 VTy->getNumElements()) {
862 STy = cast<SequentialType>(NextTy);
863 NextTy = cast<SequentialType>(NextTy)->getElementType();
866 if (isBadCase) G1OC = 0;
869 // Make sure they are comparable (ie, not constant expressions), and
870 // make sure the GEP with the smaller leading constant is GEP1.
872 Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT,
874 if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
875 if (CV->getZExtValue()) { // If they are comparable and G2 > G1
876 std::swap(GEP1Ops, GEP2Ops); // Make GEP1 < GEP2
877 std::swap(NumGEP1Ops, NumGEP2Ops);
884 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
887 // No shared constant operands, and we ran out of common operands. At this
888 // point, the GEP instructions have run through all of their operands, and we
889 // haven't found evidence that there are any deltas between the GEP's.
890 // However, one GEP may have more operands than the other. If this is the
891 // case, there may still be hope. Check this now.
892 if (FirstConstantOper == MinOperands) {
893 // Without TargetData, we won't know what the offsets are.
897 // Make GEP1Ops be the longer one if there is a longer one.
898 if (NumGEP1Ops < NumGEP2Ops) {
899 std::swap(GEP1Ops, GEP2Ops);
900 std::swap(NumGEP1Ops, NumGEP2Ops);
903 // Is there anything to check?
904 if (NumGEP1Ops > MinOperands) {
905 for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
906 if (isa<ConstantInt>(GEP1Ops[i]) &&
907 !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
908 // Yup, there's a constant in the tail. Set all variables to
909 // constants in the GEP instruction to make it suitable for
910 // TargetData::getIndexedOffset.
911 for (i = 0; i != MaxOperands; ++i)
912 if (!isa<ConstantInt>(GEP1Ops[i]))
913 GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
914 // Okay, now get the offset. This is the relative offset for the full
916 int64_t Offset1 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
919 // Now check without any constants at the end.
920 int64_t Offset2 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
923 // Make sure we compare the absolute difference.
924 if (Offset1 > Offset2)
925 std::swap(Offset1, Offset2);
927 // If the tail provided a bit enough offset, return noalias!
928 if ((uint64_t)(Offset2-Offset1) >= SizeMax)
930 // Otherwise break - we don't look for another constant in the tail.
935 // Couldn't find anything useful.
939 // If there are non-equal constants arguments, then we can figure
940 // out a minimum known delta between the two index expressions... at
941 // this point we know that the first constant index of GEP1 is less
942 // than the first constant index of GEP2.
944 // Advance BasePtr[12]Ty over this first differing constant operand.
945 BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
946 getTypeAtIndex(GEP2Ops[FirstConstantOper]);
947 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
948 getTypeAtIndex(GEP1Ops[FirstConstantOper]);
950 // We are going to be using TargetData::getIndexedOffset to determine the
951 // offset that each of the GEP's is reaching. To do this, we have to convert
952 // all variable references to constant references. To do this, we convert the
953 // initial sequence of array subscripts into constant zeros to start with.
954 const Type *ZeroIdxTy = GEPPointerTy;
955 for (unsigned i = 0; i != FirstConstantOper; ++i) {
956 if (!isa<StructType>(ZeroIdxTy))
957 GEP1Ops[i] = GEP2Ops[i] =
958 Constant::getNullValue(Type::getInt32Ty(ZeroIdxTy->getContext()));
960 if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
961 ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
964 // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
966 // Loop over the rest of the operands...
967 for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
968 const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
969 const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
970 // If they are equal, use a zero index...
971 if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
972 if (!isa<ConstantInt>(Op1))
973 GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
974 // Otherwise, just keep the constants we have.
977 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
978 // If this is an array index, make sure the array element is in range.
979 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
980 if (Op1C->getZExtValue() >= AT->getNumElements())
981 return MayAlias; // Be conservative with out-of-range accesses
982 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
983 if (Op1C->getZExtValue() >= VT->getNumElements())
984 return MayAlias; // Be conservative with out-of-range accesses
988 // GEP1 is known to produce a value less than GEP2. To be
989 // conservatively correct, we must assume the largest possible
990 // constant is used in this position. This cannot be the initial
991 // index to the GEP instructions (because we know we have at least one
992 // element before this one with the different constant arguments), so
993 // we know that the current index must be into either a struct or
994 // array. Because we know it's not constant, this cannot be a
995 // structure index. Because of this, we can calculate the maximum
998 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
1000 ConstantInt::get(Type::getInt64Ty(AT->getContext()),
1001 AT->getNumElements()-1);
1002 else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
1004 ConstantInt::get(Type::getInt64Ty(VT->getContext()),
1005 VT->getNumElements()-1);
1010 if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
1011 // If this is an array index, make sure the array element is in range.
1012 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
1013 if (Op2C->getZExtValue() >= AT->getNumElements())
1014 return MayAlias; // Be conservative with out-of-range accesses
1015 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
1016 if (Op2C->getZExtValue() >= VT->getNumElements())
1017 return MayAlias; // Be conservative with out-of-range accesses
1019 } else { // Conservatively assume the minimum value for this index
1020 GEP2Ops[i] = Constant::getNullValue(Op2->getType());
1025 if (BasePtr1Ty && Op1) {
1026 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
1027 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
1032 if (BasePtr2Ty && Op2) {
1033 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
1034 BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
1040 if (TD && GEPPointerTy->getElementType()->isSized()) {
1042 TD->getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
1044 TD->getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
1045 assert(Offset1 != Offset2 &&
1046 "There is at least one different constant here!");
1048 // Make sure we compare the absolute difference.
1049 if (Offset1 > Offset2)
1050 std::swap(Offset1, Offset2);
1052 if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
1053 //cerr << "Determined that these two GEP's don't alias ["
1054 // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
1061 // Make sure that anything that uses AliasAnalysis pulls in this file...
1062 DEFINING_FILE_FOR(BasicAliasAnalysis)