1 //===- BasicAliasAnalysis.cpp - Stateless 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 primary stateless implementation of the
11 // Alias Analysis interface that implements identities (two different
12 // globals cannot alias, etc), but does no stateful analysis.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalAlias.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/Analysis/MemoryBuiltins.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 /// isKnownNonNull - Return true if we know that the specified value is never
45 static bool isKnownNonNull(const Value *V) {
46 // Alloca never returns null, malloc might.
47 if (isa<AllocaInst>(V)) return true;
49 // A byval argument is never null.
50 if (const Argument *A = dyn_cast<Argument>(V))
51 return A->hasByValAttr();
53 // Global values are not null unless extern weak.
54 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
55 return !GV->hasExternalWeakLinkage();
59 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
60 /// object that never escapes from the function.
61 static bool isNonEscapingLocalObject(const Value *V) {
62 // If this is a local allocation, check to see if it escapes.
63 if (isa<AllocaInst>(V) || isNoAliasCall(V))
64 // Set StoreCaptures to True so that we can assume in our callers that the
65 // pointer is not the result of a load instruction. Currently
66 // PointerMayBeCaptured doesn't have any special analysis for the
67 // StoreCaptures=false case; if it did, our callers could be refined to be
69 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
71 // If this is an argument that corresponds to a byval or noalias argument,
72 // then it has not escaped before entering the function. Check if it escapes
73 // inside the function.
74 if (const Argument *A = dyn_cast<Argument>(V))
75 if (A->hasByValAttr() || A->hasNoAliasAttr()) {
76 // Don't bother analyzing arguments already known not to escape.
77 if (A->hasNoCaptureAttr())
79 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
84 /// isEscapeSource - Return true if the pointer is one which would have
85 /// been considered an escape by isNonEscapingLocalObject.
86 static bool isEscapeSource(const Value *V) {
87 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
90 // The load case works because isNonEscapingLocalObject considers all
91 // stores to be escapes (it passes true for the StoreCaptures argument
92 // to PointerMayBeCaptured).
99 /// isObjectSmallerThan - Return true if we can prove that the object specified
100 /// by V is smaller than Size.
101 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
102 const TargetData &TD) {
103 const Type *AccessTy;
104 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
105 AccessTy = GV->getType()->getElementType();
106 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
107 if (!AI->isArrayAllocation())
108 AccessTy = AI->getType()->getElementType();
111 } else if (const CallInst* CI = extractMallocCall(V)) {
112 if (!isArrayMalloc(V, &TD))
113 // The size is the argument to the malloc call.
114 if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getArgOperand(0)))
115 return (C->getZExtValue() < Size);
117 } else if (const Argument *A = dyn_cast<Argument>(V)) {
118 if (A->hasByValAttr())
119 AccessTy = cast<PointerType>(A->getType())->getElementType();
126 if (AccessTy->isSized())
127 return TD.getTypeAllocSize(AccessTy) < Size;
131 //===----------------------------------------------------------------------===//
132 // GetElementPtr Instruction Decomposition and Analysis
133 //===----------------------------------------------------------------------===//
142 struct VariableGEPIndex {
144 ExtensionKind Extension;
150 /// GetLinearExpression - Analyze the specified value as a linear expression:
151 /// "A*V + B", where A and B are constant integers. Return the scale and offset
152 /// values as APInts and return V as a Value*, and return whether we looked
153 /// through any sign or zero extends. The incoming Value is known to have
154 /// IntegerType and it may already be sign or zero extended.
156 /// Note that this looks through extends, so the high bits may not be
157 /// represented in the result.
158 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
159 ExtensionKind &Extension,
160 const TargetData &TD, unsigned Depth) {
161 assert(V->getType()->isIntegerTy() && "Not an integer value");
163 // Limit our recursion depth.
170 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
171 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
172 switch (BOp->getOpcode()) {
174 case Instruction::Or:
175 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
177 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &TD))
180 case Instruction::Add:
181 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
183 Offset += RHSC->getValue();
185 case Instruction::Mul:
186 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
188 Offset *= RHSC->getValue();
189 Scale *= RHSC->getValue();
191 case Instruction::Shl:
192 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
194 Offset <<= RHSC->getValue().getLimitedValue();
195 Scale <<= RHSC->getValue().getLimitedValue();
201 // Since GEP indices are sign extended anyway, we don't care about the high
202 // bits of a sign or zero extended value - just scales and offsets. The
203 // extensions have to be consistent though.
204 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
205 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
206 Value *CastOp = cast<CastInst>(V)->getOperand(0);
207 unsigned OldWidth = Scale.getBitWidth();
208 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
209 Scale.trunc(SmallWidth);
210 Offset.trunc(SmallWidth);
211 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
213 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
215 Scale.zext(OldWidth);
216 Offset.zext(OldWidth);
226 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
227 /// into a base pointer with a constant offset and a number of scaled symbolic
230 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
231 /// the VarIndices vector) are Value*'s that are known to be scaled by the
232 /// specified amount, but which may have other unrepresented high bits. As such,
233 /// the gep cannot necessarily be reconstructed from its decomposed form.
235 /// When TargetData is around, this function is capable of analyzing everything
236 /// that Value::getUnderlyingObject() can look through. When not, it just looks
237 /// through pointer casts.
240 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
241 SmallVectorImpl<VariableGEPIndex> &VarIndices,
242 const TargetData *TD) {
243 // Limit recursion depth to limit compile time in crazy cases.
244 unsigned MaxLookup = 6;
248 // See if this is a bitcast or GEP.
249 const Operator *Op = dyn_cast<Operator>(V);
251 // The only non-operator case we can handle are GlobalAliases.
252 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
253 if (!GA->mayBeOverridden()) {
254 V = GA->getAliasee();
261 if (Op->getOpcode() == Instruction::BitCast) {
262 V = Op->getOperand(0);
266 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
270 // Don't attempt to analyze GEPs over unsized objects.
271 if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
272 ->getElementType()->isSized())
275 // If we are lacking TargetData information, we can't compute the offets of
276 // elements computed by GEPs. However, we can handle bitcast equivalent
279 if (!GEPOp->hasAllZeroIndices())
281 V = GEPOp->getOperand(0);
285 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
286 gep_type_iterator GTI = gep_type_begin(GEPOp);
287 for (User::const_op_iterator I = GEPOp->op_begin()+1,
288 E = GEPOp->op_end(); I != E; ++I) {
290 // Compute the (potentially symbolic) offset in bytes for this index.
291 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
292 // For a struct, add the member offset.
293 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
294 if (FieldNo == 0) continue;
296 BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
300 // For an array/pointer, add the element offset, explicitly scaled.
301 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
302 if (CIdx->isZero()) continue;
303 BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
307 uint64_t Scale = TD->getTypeAllocSize(*GTI);
308 ExtensionKind Extension = EK_NotExtended;
310 // If the integer type is smaller than the pointer size, it is implicitly
311 // sign extended to pointer size.
312 unsigned Width = cast<IntegerType>(Index->getType())->getBitWidth();
313 if (TD->getPointerSizeInBits() > Width)
314 Extension = EK_SignExt;
316 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
317 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
318 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
321 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
322 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
323 BaseOffs += IndexOffset.getSExtValue()*Scale;
324 Scale *= IndexScale.getSExtValue();
327 // If we already had an occurrance of this index variable, merge this
328 // scale into it. For example, we want to handle:
329 // A[x][x] -> x*16 + x*4 -> x*20
330 // This also ensures that 'x' only appears in the index list once.
331 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
332 if (VarIndices[i].V == Index &&
333 VarIndices[i].Extension == Extension) {
334 Scale += VarIndices[i].Scale;
335 VarIndices.erase(VarIndices.begin()+i);
340 // Make sure that we have a scale that makes sense for this target's
342 if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
344 Scale = (int64_t)Scale >> ShiftBits;
348 VariableGEPIndex Entry = {Index, Extension, Scale};
349 VarIndices.push_back(Entry);
353 // Analyze the base pointer next.
354 V = GEPOp->getOperand(0);
355 } while (--MaxLookup);
357 // If the chain of expressions is too deep, just return early.
361 /// GetIndexDifference - Dest and Src are the variable indices from two
362 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
363 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
364 /// difference between the two pointers.
365 static void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
366 const SmallVectorImpl<VariableGEPIndex> &Src) {
367 if (Src.empty()) return;
369 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
370 const Value *V = Src[i].V;
371 ExtensionKind Extension = Src[i].Extension;
372 int64_t Scale = Src[i].Scale;
374 // Find V in Dest. This is N^2, but pointer indices almost never have more
375 // than a few variable indexes.
376 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
377 if (Dest[j].V != V || Dest[j].Extension != Extension) continue;
379 // If we found it, subtract off Scale V's from the entry in Dest. If it
380 // goes to zero, remove the entry.
381 if (Dest[j].Scale != Scale)
382 Dest[j].Scale -= Scale;
384 Dest.erase(Dest.begin()+j);
389 // If we didn't consume this entry, add it to the end of the Dest list.
391 VariableGEPIndex Entry = { V, Extension, -Scale };
392 Dest.push_back(Entry);
397 //===----------------------------------------------------------------------===//
398 // BasicAliasAnalysis Pass
399 //===----------------------------------------------------------------------===//
402 static const Function *getParent(const Value *V) {
403 if (const Instruction *inst = dyn_cast<Instruction>(V))
404 return inst->getParent()->getParent();
406 if (const Argument *arg = dyn_cast<Argument>(V))
407 return arg->getParent();
412 static bool notDifferentParent(const Value *O1, const Value *O2) {
414 const Function *F1 = getParent(O1);
415 const Function *F2 = getParent(O2);
417 return !F1 || !F2 || F1 == F2;
422 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
423 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
424 static char ID; // Class identification, replacement for typeinfo
425 BasicAliasAnalysis() : ImmutablePass(ID) {
426 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
429 virtual void initializePass() {
430 InitializeAliasAnalysis(this);
433 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
434 AU.addRequired<AliasAnalysis>();
437 virtual AliasResult alias(const Location &LocA,
438 const Location &LocB) {
439 assert(Visited.empty() && "Visited must be cleared after use!");
440 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
441 "BasicAliasAnalysis doesn't support interprocedural queries.");
442 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.TBAATag,
443 LocB.Ptr, LocB.Size, LocB.TBAATag);
448 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
449 const Location &Loc);
451 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
452 ImmutableCallSite CS2) {
453 // The AliasAnalysis base class has some smarts, lets use them.
454 return AliasAnalysis::getModRefInfo(CS1, CS2);
457 /// pointsToConstantMemory - Chase pointers until we find a (constant
459 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
461 /// getModRefBehavior - Return the behavior when calling the given
463 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
465 /// getModRefBehavior - Return the behavior when calling the given function.
466 /// For use when the call site is not known.
467 virtual ModRefBehavior getModRefBehavior(const Function *F);
469 /// getAdjustedAnalysisPointer - This method is used when a pass implements
470 /// an analysis interface through multiple inheritance. If needed, it
471 /// should override this to adjust the this pointer as needed for the
472 /// specified pass info.
473 virtual void *getAdjustedAnalysisPointer(const void *ID) {
474 if (ID == &AliasAnalysis::ID)
475 return (AliasAnalysis*)this;
480 // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
481 SmallPtrSet<const Value*, 16> Visited;
483 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
484 // instruction against another.
485 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
486 const Value *V2, uint64_t V2Size,
487 const MDNode *V2TBAAInfo,
488 const Value *UnderlyingV1, const Value *UnderlyingV2);
490 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
491 // instruction against another.
492 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
493 const MDNode *PNTBAAInfo,
494 const Value *V2, uint64_t V2Size,
495 const MDNode *V2TBAAInfo);
497 /// aliasSelect - Disambiguate a Select instruction against another value.
498 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
499 const MDNode *SITBAAInfo,
500 const Value *V2, uint64_t V2Size,
501 const MDNode *V2TBAAInfo);
503 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
504 const MDNode *V1TBAATag,
505 const Value *V2, uint64_t V2Size,
506 const MDNode *V2TBAATag);
508 } // End of anonymous namespace
510 // Register this pass...
511 char BasicAliasAnalysis::ID = 0;
512 INITIALIZE_AG_PASS(BasicAliasAnalysis, AliasAnalysis, "basicaa",
513 "Basic Alias Analysis (stateless AA impl)",
516 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
517 return new BasicAliasAnalysis();
520 /// pointsToConstantMemory - Returns whether the given pointer value
521 /// points to memory that is local to the function, with global constants being
522 /// considered local to all functions.
524 BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
525 assert(Visited.empty() && "Visited must be cleared after use!");
527 unsigned MaxLookup = 8;
528 SmallVector<const Value *, 16> Worklist;
529 Worklist.push_back(Loc.Ptr);
531 const Value *V = Worklist.pop_back_val()->getUnderlyingObject();
532 if (!Visited.insert(V)) {
534 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
537 // An alloca instruction defines local memory.
538 if (OrLocal && isa<AllocaInst>(V))
541 // A global constant counts as local memory for our purposes.
542 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
543 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
544 // global to be marked constant in some modules and non-constant in
545 // others. GV may even be a declaration, not a definition.
546 if (!GV->isConstant()) {
548 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
553 // If both select values point to local memory, then so does the select.
554 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
555 Worklist.push_back(SI->getTrueValue());
556 Worklist.push_back(SI->getFalseValue());
560 // If all values incoming to a phi node point to local memory, then so does
562 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
563 // Don't bother inspecting phi nodes with many operands.
564 if (PN->getNumIncomingValues() > MaxLookup) {
566 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
568 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
569 Worklist.push_back(PN->getIncomingValue(i));
573 // Otherwise be conservative.
575 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
577 } while (!Worklist.empty() && --MaxLookup);
580 return Worklist.empty();
583 /// getModRefBehavior - Return the behavior when calling the given call site.
584 AliasAnalysis::ModRefBehavior
585 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
586 if (CS.doesNotAccessMemory())
587 // Can't do better than this.
588 return DoesNotAccessMemory;
590 ModRefBehavior Min = UnknownModRefBehavior;
592 // If the callsite knows it only reads memory, don't return worse
594 if (CS.onlyReadsMemory())
595 Min = OnlyReadsMemory;
597 // The AliasAnalysis base class has some smarts, lets use them.
598 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
601 /// getModRefBehavior - Return the behavior when calling the given function.
602 /// For use when the call site is not known.
603 AliasAnalysis::ModRefBehavior
604 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
605 // If the function declares it doesn't access memory, we can't do better.
606 if (F->doesNotAccessMemory())
607 return DoesNotAccessMemory;
609 // For intrinsics, we can check the table.
610 if (unsigned iid = F->getIntrinsicID()) {
611 #define GET_INTRINSIC_MODREF_BEHAVIOR
612 #include "llvm/Intrinsics.gen"
613 #undef GET_INTRINSIC_MODREF_BEHAVIOR
616 ModRefBehavior Min = UnknownModRefBehavior;
618 // If the function declares it only reads memory, go with that.
619 if (F->onlyReadsMemory())
620 Min = OnlyReadsMemory;
622 // Otherwise be conservative.
623 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
626 /// getModRefInfo - Check to see if the specified callsite can clobber the
627 /// specified memory object. Since we only look at local properties of this
628 /// function, we really can't say much about this query. We do, however, use
629 /// simple "address taken" analysis on local objects.
630 AliasAnalysis::ModRefResult
631 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
632 const Location &Loc) {
633 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
634 "AliasAnalysis query involving multiple functions!");
636 const Value *Object = Loc.Ptr->getUnderlyingObject();
638 // If this is a tail call and Loc.Ptr points to a stack location, we know that
639 // the tail call cannot access or modify the local stack.
640 // We cannot exclude byval arguments here; these belong to the caller of
641 // the current function not to the current function, and a tail callee
642 // may reference them.
643 if (isa<AllocaInst>(Object))
644 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
645 if (CI->isTailCall())
648 // If the pointer is to a locally allocated object that does not escape,
649 // then the call can not mod/ref the pointer unless the call takes the pointer
650 // as an argument, and itself doesn't capture it.
651 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
652 isNonEscapingLocalObject(Object)) {
653 bool PassedAsArg = false;
655 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
656 CI != CE; ++CI, ++ArgNo) {
657 // Only look at the no-capture pointer arguments.
658 if (!(*CI)->getType()->isPointerTy() ||
659 !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
662 // If this is a no-capture pointer argument, see if we can tell that it
663 // is impossible to alias the pointer we're checking. If not, we have to
664 // assume that the call could touch the pointer, even though it doesn't
666 if (!isNoAlias(Location(cast<Value>(CI)), Loc)) {
676 ModRefResult Min = ModRef;
678 // Finally, handle specific knowledge of intrinsics.
679 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
681 switch (II->getIntrinsicID()) {
683 case Intrinsic::memcpy:
684 case Intrinsic::memmove: {
685 uint64_t Len = UnknownSize;
686 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
687 Len = LenCI->getZExtValue();
688 Value *Dest = II->getArgOperand(0);
689 Value *Src = II->getArgOperand(1);
690 if (isNoAlias(Location(Dest, Len), Loc)) {
691 if (isNoAlias(Location(Src, Len), Loc))
697 case Intrinsic::memset:
698 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
699 // will handle it for the variable length case.
700 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
701 uint64_t Len = LenCI->getZExtValue();
702 Value *Dest = II->getArgOperand(0);
703 if (isNoAlias(Location(Dest, Len), Loc))
707 case Intrinsic::atomic_cmp_swap:
708 case Intrinsic::atomic_swap:
709 case Intrinsic::atomic_load_add:
710 case Intrinsic::atomic_load_sub:
711 case Intrinsic::atomic_load_and:
712 case Intrinsic::atomic_load_nand:
713 case Intrinsic::atomic_load_or:
714 case Intrinsic::atomic_load_xor:
715 case Intrinsic::atomic_load_max:
716 case Intrinsic::atomic_load_min:
717 case Intrinsic::atomic_load_umax:
718 case Intrinsic::atomic_load_umin:
720 Value *Op1 = II->getArgOperand(0);
721 uint64_t Op1Size = TD->getTypeStoreSize(Op1->getType());
722 MDNode *Tag = II->getMetadata(LLVMContext::MD_tbaa);
723 if (isNoAlias(Location(Op1, Op1Size, Tag), Loc))
727 case Intrinsic::lifetime_start:
728 case Intrinsic::lifetime_end:
729 case Intrinsic::invariant_start: {
731 cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
732 if (isNoAlias(Location(II->getArgOperand(1),
734 II->getMetadata(LLVMContext::MD_tbaa)),
739 case Intrinsic::invariant_end: {
741 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
742 if (isNoAlias(Location(II->getArgOperand(2),
744 II->getMetadata(LLVMContext::MD_tbaa)),
751 // The AliasAnalysis base class has some smarts, lets use them.
752 return ModRefResult(AliasAnalysis::getModRefInfo(CS, Loc) & Min);
755 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
756 /// against another pointer. We know that V1 is a GEP, but we don't know
757 /// anything about V2. UnderlyingV1 is GEP1->getUnderlyingObject(),
758 /// UnderlyingV2 is the same for V2.
760 AliasAnalysis::AliasResult
761 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
762 const Value *V2, uint64_t V2Size,
763 const MDNode *V2TBAAInfo,
764 const Value *UnderlyingV1,
765 const Value *UnderlyingV2) {
766 // If this GEP has been visited before, we're on a use-def cycle.
767 // Such cycles are only valid when PHI nodes are involved or in unreachable
768 // code. The visitPHI function catches cycles containing PHIs, but there
769 // could still be a cycle without PHIs in unreachable code.
770 if (!Visited.insert(GEP1))
773 int64_t GEP1BaseOffset;
774 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
776 // If we have two gep instructions with must-alias'ing base pointers, figure
777 // out if the indexes to the GEP tell us anything about the derived pointer.
778 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
779 // Do the base pointers alias?
780 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, 0,
781 UnderlyingV2, UnknownSize, 0);
783 // If we get a No or May, then return it immediately, no amount of analysis
784 // will improve this situation.
785 if (BaseAlias != MustAlias) return BaseAlias;
787 // Otherwise, we have a MustAlias. Since the base pointers alias each other
788 // exactly, see if the computed offset from the common pointer tells us
789 // about the relation of the resulting pointer.
790 const Value *GEP1BasePtr =
791 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
793 int64_t GEP2BaseOffset;
794 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
795 const Value *GEP2BasePtr =
796 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
798 // If DecomposeGEPExpression isn't able to look all the way through the
799 // addressing operation, we must not have TD and this is too complex for us
800 // to handle without it.
801 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
803 "DecomposeGEPExpression and getUnderlyingObject disagree!");
807 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
808 // symbolic difference.
809 GEP1BaseOffset -= GEP2BaseOffset;
810 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
813 // Check to see if these two pointers are related by the getelementptr
814 // instruction. If one pointer is a GEP with a non-zero index of the other
815 // pointer, we know they cannot alias.
817 // If both accesses are unknown size, we can't do anything useful here.
818 if (V1Size == UnknownSize && V2Size == UnknownSize)
821 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, 0,
822 V2, V2Size, V2TBAAInfo);
824 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
825 // If V2 is known not to alias GEP base pointer, then the two values
826 // cannot alias per GEP semantics: "A pointer value formed from a
827 // getelementptr instruction is associated with the addresses associated
828 // with the first operand of the getelementptr".
831 const Value *GEP1BasePtr =
832 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
834 // If DecomposeGEPExpression isn't able to look all the way through the
835 // addressing operation, we must not have TD and this is too complex for us
836 // to handle without it.
837 if (GEP1BasePtr != UnderlyingV1) {
839 "DecomposeGEPExpression and getUnderlyingObject disagree!");
844 // In the two GEP Case, if there is no difference in the offsets of the
845 // computed pointers, the resultant pointers are a must alias. This
846 // hapens when we have two lexically identical GEP's (for example).
848 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
849 // must aliases the GEP, the end result is a must alias also.
850 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
853 // If we have a known constant offset, see if this offset is larger than the
854 // access size being queried. If so, and if no variable indices can remove
855 // pieces of this constant, then we know we have a no-alias. For example,
858 // In order to handle cases like &A[100][i] where i is an out of range
859 // subscript, we have to ignore all constant offset pieces that are a multiple
860 // of a scaled index. Do this by removing constant offsets that are a
861 // multiple of any of our variable indices. This allows us to transform
862 // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
863 // provides an offset of 4 bytes (assuming a <= 4 byte access).
864 for (unsigned i = 0, e = GEP1VariableIndices.size();
865 i != e && GEP1BaseOffset;++i)
866 if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].Scale)
867 GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].Scale;
869 // If our known offset is bigger than the access size, we know we don't have
871 if (GEP1BaseOffset) {
872 if (GEP1BaseOffset >= 0 ?
873 (V2Size != UnknownSize && (uint64_t)GEP1BaseOffset >= V2Size) :
874 (V1Size != UnknownSize && -(uint64_t)GEP1BaseOffset >= V1Size &&
875 GEP1BaseOffset != INT64_MIN))
882 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
883 /// instruction against another.
884 AliasAnalysis::AliasResult
885 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
886 const MDNode *SITBAAInfo,
887 const Value *V2, uint64_t V2Size,
888 const MDNode *V2TBAAInfo) {
889 // If this select has been visited before, we're on a use-def cycle.
890 // Such cycles are only valid when PHI nodes are involved or in unreachable
891 // code. The visitPHI function catches cycles containing PHIs, but there
892 // could still be a cycle without PHIs in unreachable code.
893 if (!Visited.insert(SI))
896 // If the values are Selects with the same condition, we can do a more precise
897 // check: just check for aliases between the values on corresponding arms.
898 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
899 if (SI->getCondition() == SI2->getCondition()) {
901 aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
902 SI2->getTrueValue(), V2Size, V2TBAAInfo);
903 if (Alias == MayAlias)
905 AliasResult ThisAlias =
906 aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
907 SI2->getFalseValue(), V2Size, V2TBAAInfo);
908 if (ThisAlias != Alias)
913 // If both arms of the Select node NoAlias or MustAlias V2, then returns
914 // NoAlias / MustAlias. Otherwise, returns MayAlias.
916 aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
917 if (Alias == MayAlias)
920 // If V2 is visited, the recursive case will have been caught in the
921 // above aliasCheck call, so these subsequent calls to aliasCheck
922 // don't need to assume that V2 is being visited recursively.
925 AliasResult ThisAlias =
926 aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
927 if (ThisAlias != Alias)
932 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
934 AliasAnalysis::AliasResult
935 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
936 const MDNode *PNTBAAInfo,
937 const Value *V2, uint64_t V2Size,
938 const MDNode *V2TBAAInfo) {
939 // The PHI node has already been visited, avoid recursion any further.
940 if (!Visited.insert(PN))
943 // If the values are PHIs in the same block, we can do a more precise
944 // as well as efficient check: just check for aliases between the values
945 // on corresponding edges.
946 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
947 if (PN2->getParent() == PN->getParent()) {
949 aliasCheck(PN->getIncomingValue(0), PNSize, PNTBAAInfo,
950 PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
952 if (Alias == MayAlias)
954 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
955 AliasResult ThisAlias =
956 aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
957 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
959 if (ThisAlias != Alias)
965 SmallPtrSet<Value*, 4> UniqueSrc;
966 SmallVector<Value*, 4> V1Srcs;
967 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
968 Value *PV1 = PN->getIncomingValue(i);
969 if (isa<PHINode>(PV1))
970 // If any of the source itself is a PHI, return MayAlias conservatively
971 // to avoid compile time explosion. The worst possible case is if both
972 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
973 // and 'n' are the number of PHI sources.
975 if (UniqueSrc.insert(PV1))
976 V1Srcs.push_back(PV1);
979 AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
980 V1Srcs[0], PNSize, PNTBAAInfo);
981 // Early exit if the check of the first PHI source against V2 is MayAlias.
982 // Other results are not possible.
983 if (Alias == MayAlias)
986 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
987 // NoAlias / MustAlias. Otherwise, returns MayAlias.
988 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
989 Value *V = V1Srcs[i];
991 // If V2 is visited, the recursive case will have been caught in the
992 // above aliasCheck call, so these subsequent calls to aliasCheck
993 // don't need to assume that V2 is being visited recursively.
996 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
997 V, PNSize, PNTBAAInfo);
998 if (ThisAlias != Alias || ThisAlias == MayAlias)
1005 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1006 // such as array references.
1008 AliasAnalysis::AliasResult
1009 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1010 const MDNode *V1TBAAInfo,
1011 const Value *V2, uint64_t V2Size,
1012 const MDNode *V2TBAAInfo) {
1013 // If either of the memory references is empty, it doesn't matter what the
1014 // pointer values are.
1015 if (V1Size == 0 || V2Size == 0)
1018 // Strip off any casts if they exist.
1019 V1 = V1->stripPointerCasts();
1020 V2 = V2->stripPointerCasts();
1022 // Are we checking for alias of the same value?
1023 if (V1 == V2) return MustAlias;
1025 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1026 return NoAlias; // Scalars cannot alias each other
1028 // Figure out what objects these things are pointing to if we can.
1029 const Value *O1 = V1->getUnderlyingObject();
1030 const Value *O2 = V2->getUnderlyingObject();
1032 // Null values in the default address space don't point to any object, so they
1033 // don't alias any other pointer.
1034 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1035 if (CPN->getType()->getAddressSpace() == 0)
1037 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1038 if (CPN->getType()->getAddressSpace() == 0)
1042 // If V1/V2 point to two different objects we know that we have no alias.
1043 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1046 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1047 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1048 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1051 // Arguments can't alias with local allocations or noalias calls
1052 // in the same function.
1053 if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
1054 (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
1057 // Most objects can't alias null.
1058 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1059 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1062 // If one pointer is the result of a call/invoke or load and the other is a
1063 // non-escaping local object within the same function, then we know the
1064 // object couldn't escape to a point where the call could return it.
1066 // Note that if the pointers are in different functions, there are a
1067 // variety of complications. A call with a nocapture argument may still
1068 // temporary store the nocapture argument's value in a temporary memory
1069 // location if that memory location doesn't escape. Or it may pass a
1070 // nocapture value to other functions as long as they don't capture it.
1071 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1073 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1077 // If the size of one access is larger than the entire object on the other
1078 // side, then we know such behavior is undefined and can assume no alias.
1080 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
1081 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
1084 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1085 // GEP can't simplify, we don't even look at the PHI cases.
1086 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1088 std::swap(V1Size, V2Size);
1091 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1092 AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, V2TBAAInfo, O1, O2);
1093 if (Result != MayAlias) return Result;
1096 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1098 std::swap(V1Size, V2Size);
1100 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1101 AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1102 V2, V2Size, V2TBAAInfo);
1103 if (Result != MayAlias) return Result;
1106 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1108 std::swap(V1Size, V2Size);
1110 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1111 AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1112 V2, V2Size, V2TBAAInfo);
1113 if (Result != MayAlias) return Result;
1116 return AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1117 Location(V2, V2Size, V2TBAAInfo));