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/Passes.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/CFG.h"
22 #include "llvm/Analysis/CaptureTracking.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/ErrorHandling.h"
45 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
46 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
47 /// careful with value equivalence. We use reachability to make sure a value
48 /// cannot be involved in a cycle.
49 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
51 // The max limit of the search depth in DecomposeGEPExpression() and
52 // GetUnderlyingObject(), both functions need to use the same search
53 // depth otherwise the algorithm in aliasGEP will assert.
54 static const unsigned MaxLookupSearchDepth = 6;
56 //===----------------------------------------------------------------------===//
58 //===----------------------------------------------------------------------===//
60 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
61 /// object that never escapes from the function.
62 static bool isNonEscapingLocalObject(const Value *V) {
63 // If this is a local allocation, check to see if it escapes.
64 if (isa<AllocaInst>(V) || isNoAliasCall(V))
65 // Set StoreCaptures to True so that we can assume in our callers that the
66 // pointer is not the result of a load instruction. Currently
67 // PointerMayBeCaptured doesn't have any special analysis for the
68 // StoreCaptures=false case; if it did, our callers could be refined to be
70 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
72 // If this is an argument that corresponds to a byval or noalias argument,
73 // then it has not escaped before entering the function. Check if it escapes
74 // inside the function.
75 if (const Argument *A = dyn_cast<Argument>(V))
76 if (A->hasByValAttr() || A->hasNoAliasAttr())
77 // Note even if the argument is marked nocapture we still need to check
78 // for copies made inside the function. The nocapture attribute only
79 // specifies that there are no copies made that outlive the function.
80 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
85 /// isEscapeSource - Return true if the pointer is one which would have
86 /// been considered an escape by isNonEscapingLocalObject.
87 static bool isEscapeSource(const Value *V) {
88 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
91 // The load case works because isNonEscapingLocalObject considers all
92 // stores to be escapes (it passes true for the StoreCaptures argument
93 // to PointerMayBeCaptured).
100 /// getObjectSize - Return the size of the object specified by V, or
101 /// UnknownSize if unknown.
102 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
103 const TargetLibraryInfo &TLI,
104 bool RoundToAlign = false) {
106 if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign))
108 return AliasAnalysis::UnknownSize;
111 /// isObjectSmallerThan - Return true if we can prove that the object specified
112 /// by V is smaller than Size.
113 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
114 const DataLayout &DL,
115 const TargetLibraryInfo &TLI) {
116 // Note that the meanings of the "object" are slightly different in the
117 // following contexts:
118 // c1: llvm::getObjectSize()
119 // c2: llvm.objectsize() intrinsic
120 // c3: isObjectSmallerThan()
121 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
122 // refers to the "entire object".
124 // Consider this example:
125 // char *p = (char*)malloc(100)
128 // In the context of c1 and c2, the "object" pointed by q refers to the
129 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
131 // However, in the context of c3, the "object" refers to the chunk of memory
132 // being allocated. So, the "object" has 100 bytes, and q points to the middle
133 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
134 // parameter, before the llvm::getObjectSize() is called to get the size of
135 // entire object, we should:
136 // - either rewind the pointer q to the base-address of the object in
137 // question (in this case rewind to p), or
138 // - just give up. It is up to caller to make sure the pointer is pointing
139 // to the base address the object.
141 // We go for 2nd option for simplicity.
142 if (!isIdentifiedObject(V))
145 // This function needs to use the aligned object size because we allow
146 // reads a bit past the end given sufficient alignment.
147 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
149 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
152 /// isObjectSize - Return true if we can prove that the object specified
153 /// by V has size Size.
154 static bool isObjectSize(const Value *V, uint64_t Size,
155 const DataLayout &DL, const TargetLibraryInfo &TLI) {
156 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
157 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
160 //===----------------------------------------------------------------------===//
161 // GetElementPtr Instruction Decomposition and Analysis
162 //===----------------------------------------------------------------------===//
171 struct VariableGEPIndex {
173 ExtensionKind Extension;
176 bool operator==(const VariableGEPIndex &Other) const {
177 return V == Other.V && Extension == Other.Extension &&
178 Scale == Other.Scale;
181 bool operator!=(const VariableGEPIndex &Other) const {
182 return !operator==(Other);
188 /// GetLinearExpression - Analyze the specified value as a linear expression:
189 /// "A*V + B", where A and B are constant integers. Return the scale and offset
190 /// values as APInts and return V as a Value*, and return whether we looked
191 /// through any sign or zero extends. The incoming Value is known to have
192 /// IntegerType and it may already be sign or zero extended.
194 /// Note that this looks through extends, so the high bits may not be
195 /// represented in the result.
196 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
197 ExtensionKind &Extension,
198 const DataLayout &DL, unsigned Depth,
199 AssumptionCache *AC, DominatorTree *DT) {
200 assert(V->getType()->isIntegerTy() && "Not an integer value");
202 // Limit our recursion depth.
209 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
210 // if it's a constant, just convert it to an offset
211 // and remove the variable.
212 Offset += Const->getValue();
213 assert(Scale == 0 && "Constant values don't have a scale");
217 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
218 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
219 switch (BOp->getOpcode()) {
221 case Instruction::Or:
222 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
224 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL, 0, AC,
228 case Instruction::Add:
229 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
230 DL, Depth + 1, AC, DT);
231 Offset += RHSC->getValue();
233 case Instruction::Mul:
234 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
235 DL, Depth + 1, AC, DT);
236 Offset *= RHSC->getValue();
237 Scale *= RHSC->getValue();
239 case Instruction::Shl:
240 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
241 DL, Depth + 1, AC, DT);
242 Offset <<= RHSC->getValue().getLimitedValue();
243 Scale <<= RHSC->getValue().getLimitedValue();
249 // Since GEP indices are sign extended anyway, we don't care about the high
250 // bits of a sign or zero extended value - just scales and offsets. The
251 // extensions have to be consistent though.
252 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
253 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
254 Value *CastOp = cast<CastInst>(V)->getOperand(0);
255 unsigned OldWidth = Scale.getBitWidth();
256 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
257 Scale = Scale.trunc(SmallWidth);
258 Offset = Offset.trunc(SmallWidth);
259 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
261 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
263 Scale = Scale.zext(OldWidth);
265 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
266 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
267 Offset = Offset.sext(OldWidth);
277 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
278 /// into a base pointer with a constant offset and a number of scaled symbolic
281 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
282 /// the VarIndices vector) are Value*'s that are known to be scaled by the
283 /// specified amount, but which may have other unrepresented high bits. As such,
284 /// the gep cannot necessarily be reconstructed from its decomposed form.
286 /// When DataLayout is around, this function is capable of analyzing everything
287 /// that GetUnderlyingObject can look through. To be able to do that
288 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
289 /// depth (MaxLookupSearchDepth).
290 /// When DataLayout not is around, it just looks through pointer casts.
293 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
294 SmallVectorImpl<VariableGEPIndex> &VarIndices,
295 bool &MaxLookupReached, const DataLayout *DL,
296 AssumptionCache *AC, DominatorTree *DT) {
297 // Limit recursion depth to limit compile time in crazy cases.
298 unsigned MaxLookup = MaxLookupSearchDepth;
299 MaxLookupReached = false;
303 // See if this is a bitcast or GEP.
304 const Operator *Op = dyn_cast<Operator>(V);
306 // The only non-operator case we can handle are GlobalAliases.
307 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
308 if (!GA->mayBeOverridden()) {
309 V = GA->getAliasee();
316 if (Op->getOpcode() == Instruction::BitCast ||
317 Op->getOpcode() == Instruction::AddrSpaceCast) {
318 V = Op->getOperand(0);
322 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
324 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
325 // can come up with something. This matches what GetUnderlyingObject does.
326 if (const Instruction *I = dyn_cast<Instruction>(V))
327 // TODO: Get a DominatorTree and AssumptionCache and use them here
328 // (these are both now available in this function, but this should be
329 // updated when GetUnderlyingObject is updated). TLI should be
331 if (const Value *Simplified =
332 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
340 // Don't attempt to analyze GEPs over unsized objects.
341 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
344 // If we are lacking DataLayout information, we can't compute the offets of
345 // elements computed by GEPs. However, we can handle bitcast equivalent
348 if (!GEPOp->hasAllZeroIndices())
350 V = GEPOp->getOperand(0);
354 unsigned AS = GEPOp->getPointerAddressSpace();
355 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
356 gep_type_iterator GTI = gep_type_begin(GEPOp);
357 for (User::const_op_iterator I = GEPOp->op_begin()+1,
358 E = GEPOp->op_end(); I != E; ++I) {
360 // Compute the (potentially symbolic) offset in bytes for this index.
361 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
362 // For a struct, add the member offset.
363 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
364 if (FieldNo == 0) continue;
366 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
370 // For an array/pointer, add the element offset, explicitly scaled.
371 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
372 if (CIdx->isZero()) continue;
373 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
377 uint64_t Scale = DL->getTypeAllocSize(*GTI);
378 ExtensionKind Extension = EK_NotExtended;
380 // If the integer type is smaller than the pointer size, it is implicitly
381 // sign extended to pointer size.
382 unsigned Width = Index->getType()->getIntegerBitWidth();
383 if (DL->getPointerSizeInBits(AS) > Width)
384 Extension = EK_SignExt;
386 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
387 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
388 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
391 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
392 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
393 BaseOffs += IndexOffset.getSExtValue()*Scale;
394 Scale *= IndexScale.getSExtValue();
396 // If we already had an occurrence of this index variable, merge this
397 // scale into it. For example, we want to handle:
398 // A[x][x] -> x*16 + x*4 -> x*20
399 // This also ensures that 'x' only appears in the index list once.
400 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
401 if (VarIndices[i].V == Index &&
402 VarIndices[i].Extension == Extension) {
403 Scale += VarIndices[i].Scale;
404 VarIndices.erase(VarIndices.begin()+i);
409 // Make sure that we have a scale that makes sense for this target's
411 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
413 Scale = (int64_t)Scale >> ShiftBits;
417 VariableGEPIndex Entry = {Index, Extension,
418 static_cast<int64_t>(Scale)};
419 VarIndices.push_back(Entry);
423 // Analyze the base pointer next.
424 V = GEPOp->getOperand(0);
425 } while (--MaxLookup);
427 // If the chain of expressions is too deep, just return early.
428 MaxLookupReached = true;
432 //===----------------------------------------------------------------------===//
433 // BasicAliasAnalysis Pass
434 //===----------------------------------------------------------------------===//
437 static const Function *getParent(const Value *V) {
438 if (const Instruction *inst = dyn_cast<Instruction>(V))
439 return inst->getParent()->getParent();
441 if (const Argument *arg = dyn_cast<Argument>(V))
442 return arg->getParent();
447 static bool notDifferentParent(const Value *O1, const Value *O2) {
449 const Function *F1 = getParent(O1);
450 const Function *F2 = getParent(O2);
452 return !F1 || !F2 || F1 == F2;
457 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
458 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
459 static char ID; // Class identification, replacement for typeinfo
460 BasicAliasAnalysis() : ImmutablePass(ID) {
461 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
464 bool doInitialization(Module &M) override;
466 void getAnalysisUsage(AnalysisUsage &AU) const override {
467 AU.addRequired<AliasAnalysis>();
468 AU.addRequired<AssumptionCacheTracker>();
469 AU.addRequired<TargetLibraryInfoWrapperPass>();
472 AliasResult alias(const Location &LocA, const Location &LocB) override {
473 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
474 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
475 "BasicAliasAnalysis doesn't support interprocedural queries.");
476 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
477 LocB.Ptr, LocB.Size, LocB.AATags);
478 // AliasCache rarely has more than 1 or 2 elements, always use
479 // shrink_and_clear so it quickly returns to the inline capacity of the
480 // SmallDenseMap if it ever grows larger.
481 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
482 AliasCache.shrink_and_clear();
483 VisitedPhiBBs.clear();
487 ModRefResult getModRefInfo(ImmutableCallSite CS,
488 const Location &Loc) override;
490 ModRefResult getModRefInfo(ImmutableCallSite CS1,
491 ImmutableCallSite CS2) override;
493 /// pointsToConstantMemory - Chase pointers until we find a (constant
495 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
497 /// Get the location associated with a pointer argument of a callsite.
498 Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
499 ModRefResult &Mask) override;
501 /// getModRefBehavior - Return the behavior when calling the given
503 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
505 /// getModRefBehavior - Return the behavior when calling the given function.
506 /// For use when the call site is not known.
507 ModRefBehavior getModRefBehavior(const Function *F) override;
509 /// getAdjustedAnalysisPointer - This method is used when a pass implements
510 /// an analysis interface through multiple inheritance. If needed, it
511 /// should override this to adjust the this pointer as needed for the
512 /// specified pass info.
513 void *getAdjustedAnalysisPointer(const void *ID) override {
514 if (ID == &AliasAnalysis::ID)
515 return (AliasAnalysis*)this;
520 // AliasCache - Track alias queries to guard against recursion.
521 typedef std::pair<Location, Location> LocPair;
522 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
523 AliasCacheTy AliasCache;
525 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
526 /// equality as value equality we need to make sure that the "Value" is not
527 /// part of a cycle. Otherwise, two uses could come from different
528 /// "iterations" of a cycle and see different values for the same "Value"
530 /// The following example shows the problem:
531 /// %p = phi(%alloca1, %addr2)
533 /// %addr1 = gep, %alloca2, 0, %l
534 /// %addr2 = gep %alloca2, 0, (%l + 1)
535 /// alias(%p, %addr1) -> MayAlias !
537 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
539 // Visited - Track instructions visited by pointsToConstantMemory.
540 SmallPtrSet<const Value*, 16> Visited;
542 /// \brief Check whether two Values can be considered equivalent.
544 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
545 /// whether they can not be part of a cycle in the value graph by looking at
546 /// all visited phi nodes an making sure that the phis cannot reach the
547 /// value. We have to do this because we are looking through phi nodes (That
548 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
549 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
551 /// \brief Dest and Src are the variable indices from two decomposed
552 /// GetElementPtr instructions GEP1 and GEP2 which have common base
553 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
554 /// difference between the two pointers.
555 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
556 const SmallVectorImpl<VariableGEPIndex> &Src);
558 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
559 // instruction against another.
560 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
561 const AAMDNodes &V1AAInfo,
562 const Value *V2, uint64_t V2Size,
563 const AAMDNodes &V2AAInfo,
564 const Value *UnderlyingV1, const Value *UnderlyingV2);
566 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
567 // instruction against another.
568 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
569 const AAMDNodes &PNAAInfo,
570 const Value *V2, uint64_t V2Size,
571 const AAMDNodes &V2AAInfo);
573 /// aliasSelect - Disambiguate a Select instruction against another value.
574 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
575 const AAMDNodes &SIAAInfo,
576 const Value *V2, uint64_t V2Size,
577 const AAMDNodes &V2AAInfo);
579 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
581 const Value *V2, uint64_t V2Size,
584 } // End of anonymous namespace
586 // Register this pass...
587 char BasicAliasAnalysis::ID = 0;
588 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
589 "Basic Alias Analysis (stateless AA impl)",
591 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
592 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
593 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
594 "Basic Alias Analysis (stateless AA impl)",
598 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
599 return new BasicAliasAnalysis();
602 /// pointsToConstantMemory - Returns whether the given pointer value
603 /// points to memory that is local to the function, with global constants being
604 /// considered local to all functions.
606 BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
607 assert(Visited.empty() && "Visited must be cleared after use!");
609 unsigned MaxLookup = 8;
610 SmallVector<const Value *, 16> Worklist;
611 Worklist.push_back(Loc.Ptr);
613 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
614 if (!Visited.insert(V).second) {
616 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
619 // An alloca instruction defines local memory.
620 if (OrLocal && isa<AllocaInst>(V))
623 // A global constant counts as local memory for our purposes.
624 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
625 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
626 // global to be marked constant in some modules and non-constant in
627 // others. GV may even be a declaration, not a definition.
628 if (!GV->isConstant()) {
630 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
635 // If both select values point to local memory, then so does the select.
636 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
637 Worklist.push_back(SI->getTrueValue());
638 Worklist.push_back(SI->getFalseValue());
642 // If all values incoming to a phi node point to local memory, then so does
644 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
645 // Don't bother inspecting phi nodes with many operands.
646 if (PN->getNumIncomingValues() > MaxLookup) {
648 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
650 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
651 Worklist.push_back(PN->getIncomingValue(i));
655 // Otherwise be conservative.
657 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
659 } while (!Worklist.empty() && --MaxLookup);
662 return Worklist.empty();
665 static bool isMemsetPattern16(const Function *MS,
666 const TargetLibraryInfo &TLI) {
667 if (TLI.has(LibFunc::memset_pattern16) &&
668 MS->getName() == "memset_pattern16") {
669 FunctionType *MemsetType = MS->getFunctionType();
670 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
671 isa<PointerType>(MemsetType->getParamType(0)) &&
672 isa<PointerType>(MemsetType->getParamType(1)) &&
673 isa<IntegerType>(MemsetType->getParamType(2)))
680 /// getModRefBehavior - Return the behavior when calling the given call site.
681 AliasAnalysis::ModRefBehavior
682 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
683 if (CS.doesNotAccessMemory())
684 // Can't do better than this.
685 return DoesNotAccessMemory;
687 ModRefBehavior Min = UnknownModRefBehavior;
689 // If the callsite knows it only reads memory, don't return worse
691 if (CS.onlyReadsMemory())
692 Min = OnlyReadsMemory;
694 // The AliasAnalysis base class has some smarts, lets use them.
695 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
698 /// getModRefBehavior - Return the behavior when calling the given function.
699 /// For use when the call site is not known.
700 AliasAnalysis::ModRefBehavior
701 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
702 // If the function declares it doesn't access memory, we can't do better.
703 if (F->doesNotAccessMemory())
704 return DoesNotAccessMemory;
706 // For intrinsics, we can check the table.
707 if (unsigned iid = F->getIntrinsicID()) {
708 #define GET_INTRINSIC_MODREF_BEHAVIOR
709 #include "llvm/IR/Intrinsics.gen"
710 #undef GET_INTRINSIC_MODREF_BEHAVIOR
713 ModRefBehavior Min = UnknownModRefBehavior;
715 // If the function declares it only reads memory, go with that.
716 if (F->onlyReadsMemory())
717 Min = OnlyReadsMemory;
719 const TargetLibraryInfo &TLI =
720 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
721 if (isMemsetPattern16(F, TLI))
722 Min = OnlyAccessesArgumentPointees;
724 // Otherwise be conservative.
725 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
728 AliasAnalysis::Location
729 BasicAliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
730 ModRefResult &Mask) {
731 Location Loc = AliasAnalysis::getArgLocation(CS, ArgIdx, Mask);
732 const TargetLibraryInfo &TLI =
733 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
734 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
736 switch (II->getIntrinsicID()) {
738 case Intrinsic::memset:
739 case Intrinsic::memcpy:
740 case Intrinsic::memmove: {
741 assert((ArgIdx == 0 || ArgIdx == 1) &&
742 "Invalid argument index for memory intrinsic");
743 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
744 Loc.Size = LenCI->getZExtValue();
745 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
746 "Memory intrinsic location pointer not argument?");
747 Mask = ArgIdx ? Ref : Mod;
750 case Intrinsic::lifetime_start:
751 case Intrinsic::lifetime_end:
752 case Intrinsic::invariant_start: {
753 assert(ArgIdx == 1 && "Invalid argument index");
754 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
755 "Intrinsic location pointer not argument?");
756 Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
759 case Intrinsic::invariant_end: {
760 assert(ArgIdx == 2 && "Invalid argument index");
761 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
762 "Intrinsic location pointer not argument?");
763 Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
766 case Intrinsic::arm_neon_vld1: {
767 assert(ArgIdx == 0 && "Invalid argument index");
768 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
769 "Intrinsic location pointer not argument?");
770 // LLVM's vld1 and vst1 intrinsics currently only support a single
773 Loc.Size = DL->getTypeStoreSize(II->getType());
776 case Intrinsic::arm_neon_vst1: {
777 assert(ArgIdx == 0 && "Invalid argument index");
778 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
779 "Intrinsic location pointer not argument?");
781 Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType());
786 // We can bound the aliasing properties of memset_pattern16 just as we can
787 // for memcpy/memset. This is particularly important because the
788 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
789 // whenever possible.
790 else if (CS.getCalledFunction() &&
791 isMemsetPattern16(CS.getCalledFunction(), TLI)) {
792 assert((ArgIdx == 0 || ArgIdx == 1) &&
793 "Invalid argument index for memset_pattern16");
796 else if (const ConstantInt *LenCI =
797 dyn_cast<ConstantInt>(CS.getArgument(2)))
798 Loc.Size = LenCI->getZExtValue();
799 assert(Loc.Ptr == CS.getArgument(ArgIdx) &&
800 "memset_pattern16 location pointer not argument?");
801 Mask = ArgIdx ? Ref : Mod;
803 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
808 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
809 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
810 if (II && II->getIntrinsicID() == Intrinsic::assume)
816 bool BasicAliasAnalysis::doInitialization(Module &M) {
817 InitializeAliasAnalysis(this, &M.getDataLayout());
821 /// getModRefInfo - Check to see if the specified callsite can clobber the
822 /// specified memory object. Since we only look at local properties of this
823 /// function, we really can't say much about this query. We do, however, use
824 /// simple "address taken" analysis on local objects.
825 AliasAnalysis::ModRefResult
826 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
827 const Location &Loc) {
828 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
829 "AliasAnalysis query involving multiple functions!");
831 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
833 // If this is a tail call and Loc.Ptr points to a stack location, we know that
834 // the tail call cannot access or modify the local stack.
835 // We cannot exclude byval arguments here; these belong to the caller of
836 // the current function not to the current function, and a tail callee
837 // may reference them.
838 if (isa<AllocaInst>(Object))
839 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
840 if (CI->isTailCall())
843 // If the pointer is to a locally allocated object that does not escape,
844 // then the call can not mod/ref the pointer unless the call takes the pointer
845 // as an argument, and itself doesn't capture it.
846 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
847 isNonEscapingLocalObject(Object)) {
848 bool PassedAsArg = false;
850 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
851 CI != CE; ++CI, ++ArgNo) {
852 // Only look at the no-capture or byval pointer arguments. If this
853 // pointer were passed to arguments that were neither of these, then it
854 // couldn't be no-capture.
855 if (!(*CI)->getType()->isPointerTy() ||
856 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
859 // If this is a no-capture pointer argument, see if we can tell that it
860 // is impossible to alias the pointer we're checking. If not, we have to
861 // assume that the call could touch the pointer, even though it doesn't
863 if (!isNoAlias(Location(*CI), Location(Object))) {
873 // While the assume intrinsic is marked as arbitrarily writing so that
874 // proper control dependencies will be maintained, it never aliases any
875 // particular memory location.
876 if (isAssumeIntrinsic(CS))
879 // The AliasAnalysis base class has some smarts, lets use them.
880 return AliasAnalysis::getModRefInfo(CS, Loc);
883 AliasAnalysis::ModRefResult
884 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
885 ImmutableCallSite CS2) {
886 // While the assume intrinsic is marked as arbitrarily writing so that
887 // proper control dependencies will be maintained, it never aliases any
888 // particular memory location.
889 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
892 // The AliasAnalysis base class has some smarts, lets use them.
893 return AliasAnalysis::getModRefInfo(CS1, CS2);
896 /// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
897 /// operators, both having the exact same pointer operand.
898 static AliasAnalysis::AliasResult
899 aliasSameBasePointerGEPs(const GEPOperator *GEP1, uint64_t V1Size,
900 const GEPOperator *GEP2, uint64_t V2Size,
901 const DataLayout &DL) {
903 assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
904 "Expected GEPs with the same pointer operand");
906 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
907 // such that the struct field accesses provably cannot alias.
908 // We also need at least two indices (the pointer, and the struct field).
909 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
910 GEP1->getNumIndices() < 2)
911 return AliasAnalysis::MayAlias;
913 // If we don't know the size of the accesses through both GEPs, we can't
914 // determine whether the struct fields accessed can't alias.
915 if (V1Size == AliasAnalysis::UnknownSize ||
916 V2Size == AliasAnalysis::UnknownSize)
917 return AliasAnalysis::MayAlias;
920 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
922 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
924 // If the last (struct) indices aren't constants, we can't say anything.
925 // If they're identical, the other indices might be also be dynamically
926 // equal, so the GEPs can alias.
927 if (!C1 || !C2 || C1 == C2)
928 return AliasAnalysis::MayAlias;
930 // Find the last-indexed type of the GEP, i.e., the type you'd get if
931 // you stripped the last index.
932 // On the way, look at each indexed type. If there's something other
933 // than an array, different indices can lead to different final types.
934 SmallVector<Value *, 8> IntermediateIndices;
936 // Insert the first index; we don't need to check the type indexed
937 // through it as it only drops the pointer indirection.
938 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
939 IntermediateIndices.push_back(GEP1->getOperand(1));
941 // Insert all the remaining indices but the last one.
942 // Also, check that they all index through arrays.
943 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
944 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
945 GEP1->getPointerOperandType(), IntermediateIndices)))
946 return AliasAnalysis::MayAlias;
947 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
950 StructType *LastIndexedStruct =
951 dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
952 GEP1->getPointerOperandType(), IntermediateIndices));
954 if (!LastIndexedStruct)
955 return AliasAnalysis::MayAlias;
958 // - both GEPs begin indexing from the exact same pointer;
959 // - the last indices in both GEPs are constants, indexing into a struct;
960 // - said indices are different, hence, the pointed-to fields are different;
961 // - both GEPs only index through arrays prior to that.
963 // This lets us determine that the struct that GEP1 indexes into and the
964 // struct that GEP2 indexes into must either precisely overlap or be
965 // completely disjoint. Because they cannot partially overlap, indexing into
966 // different non-overlapping fields of the struct will never alias.
968 // Therefore, the only remaining thing needed to show that both GEPs can't
969 // alias is that the fields are not overlapping.
970 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
971 const uint64_t StructSize = SL->getSizeInBytes();
972 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
973 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
975 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
976 uint64_t V2Off, uint64_t V2Size) {
977 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
978 ((V2Off + V2Size <= StructSize) ||
979 (V2Off + V2Size - StructSize <= V1Off));
982 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
983 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
984 return AliasAnalysis::NoAlias;
986 return AliasAnalysis::MayAlias;
989 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
990 /// against another pointer. We know that V1 is a GEP, but we don't know
991 /// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
992 /// UnderlyingV2 is the same for V2.
994 AliasAnalysis::AliasResult
995 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
996 const AAMDNodes &V1AAInfo,
997 const Value *V2, uint64_t V2Size,
998 const AAMDNodes &V2AAInfo,
999 const Value *UnderlyingV1,
1000 const Value *UnderlyingV2) {
1001 int64_t GEP1BaseOffset;
1002 bool GEP1MaxLookupReached;
1003 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
1005 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
1006 // different functions.
1007 // FIXME: This really doesn't make any sense. We get a dominator tree below
1008 // that can only refer to a single function. But this function (aliasGEP) is
1009 // a method on an immutable pass that can be called when there *isn't*
1010 // a single function. The old pass management layer makes this "work", but
1011 // this isn't really a clean solution.
1012 AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
1013 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
1014 if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
1015 AC1 = &ACT.getAssumptionCache(
1016 const_cast<Function &>(*GEP1I->getParent()->getParent()));
1017 if (auto *I2 = dyn_cast<Instruction>(V2))
1018 AC2 = &ACT.getAssumptionCache(
1019 const_cast<Function &>(*I2->getParent()->getParent()));
1021 DominatorTreeWrapperPass *DTWP =
1022 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1023 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1025 // If we have two gep instructions with must-alias or not-alias'ing base
1026 // pointers, figure out if the indexes to the GEP tell us anything about the
1028 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
1029 // Do the base pointers alias?
1030 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
1031 UnderlyingV2, UnknownSize, AAMDNodes());
1033 // Check for geps of non-aliasing underlying pointers where the offsets are
1035 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
1036 // Do the base pointers alias assuming type and size.
1037 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
1038 V1AAInfo, UnderlyingV2,
1040 if (PreciseBaseAlias == NoAlias) {
1041 // See if the computed offset from the common pointer tells us about the
1042 // relation of the resulting pointer.
1043 int64_t GEP2BaseOffset;
1044 bool GEP2MaxLookupReached;
1045 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
1046 const Value *GEP2BasePtr =
1047 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
1048 GEP2MaxLookupReached, DL, AC2, DT);
1049 const Value *GEP1BasePtr =
1050 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1051 GEP1MaxLookupReached, DL, AC1, DT);
1052 // DecomposeGEPExpression and GetUnderlyingObject should return the
1053 // same result except when DecomposeGEPExpression has no DataLayout.
1054 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
1056 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1059 // If the max search depth is reached the result is undefined
1060 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1064 if (GEP1BaseOffset == GEP2BaseOffset &&
1065 GEP1VariableIndices == GEP2VariableIndices)
1067 GEP1VariableIndices.clear();
1071 // If we get a No or May, then return it immediately, no amount of analysis
1072 // will improve this situation.
1073 if (BaseAlias != MustAlias) return BaseAlias;
1075 // Otherwise, we have a MustAlias. Since the base pointers alias each other
1076 // exactly, see if the computed offset from the common pointer tells us
1077 // about the relation of the resulting pointer.
1078 const Value *GEP1BasePtr =
1079 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1080 GEP1MaxLookupReached, DL, AC1, DT);
1082 int64_t GEP2BaseOffset;
1083 bool GEP2MaxLookupReached;
1084 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
1085 const Value *GEP2BasePtr =
1086 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
1087 GEP2MaxLookupReached, DL, AC2, DT);
1089 // DecomposeGEPExpression and GetUnderlyingObject should return the
1090 // same result except when DecomposeGEPExpression has no DataLayout.
1091 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
1093 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1097 // If we know the two GEPs are based off of the exact same pointer (and not
1098 // just the same underlying object), see if that tells us anything about
1099 // the resulting pointers.
1100 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
1101 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
1102 // If we couldn't find anything interesting, don't abandon just yet.
1107 // If the max search depth is reached the result is undefined
1108 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1111 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1112 // symbolic difference.
1113 GEP1BaseOffset -= GEP2BaseOffset;
1114 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
1117 // Check to see if these two pointers are related by the getelementptr
1118 // instruction. If one pointer is a GEP with a non-zero index of the other
1119 // pointer, we know they cannot alias.
1121 // If both accesses are unknown size, we can't do anything useful here.
1122 if (V1Size == UnknownSize && V2Size == UnknownSize)
1125 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
1126 V2, V2Size, V2AAInfo);
1128 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1129 // If V2 is known not to alias GEP base pointer, then the two values
1130 // cannot alias per GEP semantics: "A pointer value formed from a
1131 // getelementptr instruction is associated with the addresses associated
1132 // with the first operand of the getelementptr".
1135 const Value *GEP1BasePtr =
1136 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1137 GEP1MaxLookupReached, DL, AC1, DT);
1139 // DecomposeGEPExpression and GetUnderlyingObject should return the
1140 // same result except when DecomposeGEPExpression has no DataLayout.
1141 if (GEP1BasePtr != UnderlyingV1) {
1143 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1146 // If the max search depth is reached the result is undefined
1147 if (GEP1MaxLookupReached)
1151 // In the two GEP Case, if there is no difference in the offsets of the
1152 // computed pointers, the resultant pointers are a must alias. This
1153 // hapens when we have two lexically identical GEP's (for example).
1155 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1156 // must aliases the GEP, the end result is a must alias also.
1157 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
1160 // If there is a constant difference between the pointers, but the difference
1161 // is less than the size of the associated memory object, then we know
1162 // that the objects are partially overlapping. If the difference is
1163 // greater, we know they do not overlap.
1164 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
1165 if (GEP1BaseOffset >= 0) {
1166 if (V2Size != UnknownSize) {
1167 if ((uint64_t)GEP1BaseOffset < V2Size)
1168 return PartialAlias;
1172 // We have the situation where:
1175 // ---------------->|
1176 // |-->V1Size |-------> V2Size
1178 // We need to know that V2Size is not unknown, otherwise we might have
1179 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1180 if (V1Size != UnknownSize && V2Size != UnknownSize) {
1181 if (-(uint64_t)GEP1BaseOffset < V1Size)
1182 return PartialAlias;
1188 if (!GEP1VariableIndices.empty()) {
1189 uint64_t Modulo = 0;
1190 bool AllPositive = true;
1191 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
1193 // Try to distinguish something like &A[i][1] against &A[42][0].
1194 // Grab the least significant bit set in any of the scales. We
1195 // don't need std::abs here (even if the scale's negative) as we'll
1196 // be ^'ing Modulo with itself later.
1197 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
1200 // If the Value could change between cycles, then any reasoning about
1201 // the Value this cycle may not hold in the next cycle. We'll just
1202 // give up if we can't determine conditions that hold for every cycle:
1203 const Value *V = GEP1VariableIndices[i].V;
1205 bool SignKnownZero, SignKnownOne;
1206 ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, DL,
1207 0, AC1, nullptr, DT);
1209 // Zero-extension widens the variable, and so forces the sign
1211 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
1212 SignKnownZero |= IsZExt;
1213 SignKnownOne &= !IsZExt;
1215 // If the variable begins with a zero then we know it's
1216 // positive, regardless of whether the value is signed or
1218 int64_t Scale = GEP1VariableIndices[i].Scale;
1220 (SignKnownZero && Scale >= 0) ||
1221 (SignKnownOne && Scale < 0);
1225 Modulo = Modulo ^ (Modulo & (Modulo - 1));
1227 // We can compute the difference between the two addresses
1228 // mod Modulo. Check whether that difference guarantees that the
1229 // two locations do not alias.
1230 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1231 if (V1Size != UnknownSize && V2Size != UnknownSize &&
1232 ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1235 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1236 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1237 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1238 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1242 // Statically, we can see that the base objects are the same, but the
1243 // pointers have dynamic offsets which we can't resolve. And none of our
1244 // little tricks above worked.
1246 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1247 // practical effect of this is protecting TBAA in the case of dynamic
1248 // indices into arrays of unions or malloc'd memory.
1249 return PartialAlias;
1252 static AliasAnalysis::AliasResult
1253 MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1254 // If the results agree, take it.
1257 // A mix of PartialAlias and MustAlias is PartialAlias.
1258 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1259 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1260 return AliasAnalysis::PartialAlias;
1261 // Otherwise, we don't know anything.
1262 return AliasAnalysis::MayAlias;
1265 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1266 /// instruction against another.
1267 AliasAnalysis::AliasResult
1268 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
1269 const AAMDNodes &SIAAInfo,
1270 const Value *V2, uint64_t V2Size,
1271 const AAMDNodes &V2AAInfo) {
1272 // If the values are Selects with the same condition, we can do a more precise
1273 // check: just check for aliases between the values on corresponding arms.
1274 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1275 if (SI->getCondition() == SI2->getCondition()) {
1277 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1278 SI2->getTrueValue(), V2Size, V2AAInfo);
1279 if (Alias == MayAlias)
1281 AliasResult ThisAlias =
1282 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1283 SI2->getFalseValue(), V2Size, V2AAInfo);
1284 return MergeAliasResults(ThisAlias, Alias);
1287 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1288 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1290 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
1291 if (Alias == MayAlias)
1294 AliasResult ThisAlias =
1295 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
1296 return MergeAliasResults(ThisAlias, Alias);
1299 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
1301 AliasAnalysis::AliasResult
1302 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1303 const AAMDNodes &PNAAInfo,
1304 const Value *V2, uint64_t V2Size,
1305 const AAMDNodes &V2AAInfo) {
1306 // Track phi nodes we have visited. We use this information when we determine
1307 // value equivalence.
1308 VisitedPhiBBs.insert(PN->getParent());
1310 // If the values are PHIs in the same block, we can do a more precise
1311 // as well as efficient check: just check for aliases between the values
1312 // on corresponding edges.
1313 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1314 if (PN2->getParent() == PN->getParent()) {
1315 LocPair Locs(Location(PN, PNSize, PNAAInfo),
1316 Location(V2, V2Size, V2AAInfo));
1318 std::swap(Locs.first, Locs.second);
1319 // Analyse the PHIs' inputs under the assumption that the PHIs are
1321 // If the PHIs are May/MustAlias there must be (recursively) an input
1322 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1323 // there must be an operation on the PHIs within the PHIs' value cycle
1324 // that causes a MayAlias.
1325 // Pretend the phis do not alias.
1326 AliasResult Alias = NoAlias;
1327 assert(AliasCache.count(Locs) &&
1328 "There must exist an entry for the phi node");
1329 AliasResult OrigAliasResult = AliasCache[Locs];
1330 AliasCache[Locs] = NoAlias;
1332 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1333 AliasResult ThisAlias =
1334 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1335 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1337 Alias = MergeAliasResults(ThisAlias, Alias);
1338 if (Alias == MayAlias)
1342 // Reset if speculation failed.
1343 if (Alias != NoAlias)
1344 AliasCache[Locs] = OrigAliasResult;
1349 SmallPtrSet<Value*, 4> UniqueSrc;
1350 SmallVector<Value*, 4> V1Srcs;
1351 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1352 Value *PV1 = PN->getIncomingValue(i);
1353 if (isa<PHINode>(PV1))
1354 // If any of the source itself is a PHI, return MayAlias conservatively
1355 // to avoid compile time explosion. The worst possible case is if both
1356 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1357 // and 'n' are the number of PHI sources.
1359 if (UniqueSrc.insert(PV1).second)
1360 V1Srcs.push_back(PV1);
1363 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1364 V1Srcs[0], PNSize, PNAAInfo);
1365 // Early exit if the check of the first PHI source against V2 is MayAlias.
1366 // Other results are not possible.
1367 if (Alias == MayAlias)
1370 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1371 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1372 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1373 Value *V = V1Srcs[i];
1375 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1376 V, PNSize, PNAAInfo);
1377 Alias = MergeAliasResults(ThisAlias, Alias);
1378 if (Alias == MayAlias)
1385 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1386 // such as array references.
1388 AliasAnalysis::AliasResult
1389 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1391 const Value *V2, uint64_t V2Size,
1392 AAMDNodes V2AAInfo) {
1393 // If either of the memory references is empty, it doesn't matter what the
1394 // pointer values are.
1395 if (V1Size == 0 || V2Size == 0)
1398 // Strip off any casts if they exist.
1399 V1 = V1->stripPointerCasts();
1400 V2 = V2->stripPointerCasts();
1402 // Are we checking for alias of the same value?
1403 // Because we look 'through' phi nodes we could look at "Value" pointers from
1404 // different iterations. We must therefore make sure that this is not the
1405 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1406 // happen by looking at the visited phi nodes and making sure they cannot
1408 if (isValueEqualInPotentialCycles(V1, V2))
1411 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1412 return NoAlias; // Scalars cannot alias each other
1414 // Figure out what objects these things are pointing to if we can.
1415 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1416 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
1418 // Null values in the default address space don't point to any object, so they
1419 // don't alias any other pointer.
1420 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1421 if (CPN->getType()->getAddressSpace() == 0)
1423 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1424 if (CPN->getType()->getAddressSpace() == 0)
1428 // If V1/V2 point to two different objects we know that we have no alias.
1429 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1432 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1433 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1434 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1437 // Function arguments can't alias with things that are known to be
1438 // unambigously identified at the function level.
1439 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1440 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1443 // Most objects can't alias null.
1444 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1445 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1448 // If one pointer is the result of a call/invoke or load and the other is a
1449 // non-escaping local object within the same function, then we know the
1450 // object couldn't escape to a point where the call could return it.
1452 // Note that if the pointers are in different functions, there are a
1453 // variety of complications. A call with a nocapture argument may still
1454 // temporary store the nocapture argument's value in a temporary memory
1455 // location if that memory location doesn't escape. Or it may pass a
1456 // nocapture value to other functions as long as they don't capture it.
1457 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1459 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1463 // If the size of one access is larger than the entire object on the other
1464 // side, then we know such behavior is undefined and can assume no alias.
1466 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1467 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1470 // Check the cache before climbing up use-def chains. This also terminates
1471 // otherwise infinitely recursive queries.
1472 LocPair Locs(Location(V1, V1Size, V1AAInfo),
1473 Location(V2, V2Size, V2AAInfo));
1475 std::swap(Locs.first, Locs.second);
1476 std::pair<AliasCacheTy::iterator, bool> Pair =
1477 AliasCache.insert(std::make_pair(Locs, MayAlias));
1479 return Pair.first->second;
1481 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1482 // GEP can't simplify, we don't even look at the PHI cases.
1483 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1485 std::swap(V1Size, V2Size);
1487 std::swap(V1AAInfo, V2AAInfo);
1489 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1490 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
1491 if (Result != MayAlias) return AliasCache[Locs] = Result;
1494 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1496 std::swap(V1Size, V2Size);
1497 std::swap(V1AAInfo, V2AAInfo);
1499 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1500 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1501 V2, V2Size, V2AAInfo);
1502 if (Result != MayAlias) return AliasCache[Locs] = Result;
1505 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1507 std::swap(V1Size, V2Size);
1508 std::swap(V1AAInfo, V2AAInfo);
1510 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1511 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1512 V2, V2Size, V2AAInfo);
1513 if (Result != MayAlias) return AliasCache[Locs] = Result;
1516 // If both pointers are pointing into the same object and one of them
1517 // accesses is accessing the entire object, then the accesses must
1518 // overlap in some way.
1520 if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1521 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
1522 return AliasCache[Locs] = PartialAlias;
1524 AliasResult Result =
1525 AliasAnalysis::alias(Location(V1, V1Size, V1AAInfo),
1526 Location(V2, V2Size, V2AAInfo));
1527 return AliasCache[Locs] = Result;
1530 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1535 const Instruction *Inst = dyn_cast<Instruction>(V);
1539 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1542 // Use dominance or loop info if available.
1543 DominatorTreeWrapperPass *DTWP =
1544 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1545 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1546 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1547 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
1549 // Make sure that the visited phis cannot reach the Value. This ensures that
1550 // the Values cannot come from different iterations of a potential cycle the
1551 // phi nodes could be involved in.
1552 for (auto *P : VisitedPhiBBs)
1553 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
1559 /// GetIndexDifference - Dest and Src are the variable indices from two
1560 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1561 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1562 /// difference between the two pointers.
1563 void BasicAliasAnalysis::GetIndexDifference(
1564 SmallVectorImpl<VariableGEPIndex> &Dest,
1565 const SmallVectorImpl<VariableGEPIndex> &Src) {
1569 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1570 const Value *V = Src[i].V;
1571 ExtensionKind Extension = Src[i].Extension;
1572 int64_t Scale = Src[i].Scale;
1574 // Find V in Dest. This is N^2, but pointer indices almost never have more
1575 // than a few variable indexes.
1576 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1577 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1578 Dest[j].Extension != Extension)
1581 // If we found it, subtract off Scale V's from the entry in Dest. If it
1582 // goes to zero, remove the entry.
1583 if (Dest[j].Scale != Scale)
1584 Dest[j].Scale -= Scale;
1586 Dest.erase(Dest.begin() + j);
1591 // If we didn't consume this entry, add it to the end of the Dest list.
1593 VariableGEPIndex Entry = { V, Extension, -Scale };
1594 Dest.push_back(Entry);