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 /// Enable analysis of recursive PHI nodes.
46 static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi",
47 cl::Hidden, cl::init(false));
49 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
50 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
51 /// careful with value equivalence. We use reachability to make sure a value
52 /// cannot be involved in a cycle.
53 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
55 // The max limit of the search depth in DecomposeGEPExpression() and
56 // GetUnderlyingObject(), both functions need to use the same search
57 // depth otherwise the algorithm in aliasGEP will assert.
58 static const unsigned MaxLookupSearchDepth = 6;
60 //===----------------------------------------------------------------------===//
62 //===----------------------------------------------------------------------===//
64 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
65 /// object that never escapes from the function.
66 static bool isNonEscapingLocalObject(const Value *V) {
67 // If this is a local allocation, check to see if it escapes.
68 if (isa<AllocaInst>(V) || isNoAliasCall(V))
69 // Set StoreCaptures to True so that we can assume in our callers that the
70 // pointer is not the result of a load instruction. Currently
71 // PointerMayBeCaptured doesn't have any special analysis for the
72 // StoreCaptures=false case; if it did, our callers could be refined to be
74 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
76 // If this is an argument that corresponds to a byval or noalias argument,
77 // then it has not escaped before entering the function. Check if it escapes
78 // inside the function.
79 if (const Argument *A = dyn_cast<Argument>(V))
80 if (A->hasByValAttr() || A->hasNoAliasAttr())
81 // Note even if the argument is marked nocapture we still need to check
82 // for copies made inside the function. The nocapture attribute only
83 // specifies that there are no copies made that outlive the function.
84 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
89 /// isEscapeSource - Return true if the pointer is one which would have
90 /// been considered an escape by isNonEscapingLocalObject.
91 static bool isEscapeSource(const Value *V) {
92 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
95 // The load case works because isNonEscapingLocalObject considers all
96 // stores to be escapes (it passes true for the StoreCaptures argument
97 // to PointerMayBeCaptured).
104 /// getObjectSize - Return the size of the object specified by V, or
105 /// UnknownSize if unknown.
106 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
107 const TargetLibraryInfo &TLI,
108 bool RoundToAlign = false) {
110 if (getObjectSize(V, Size, DL, &TLI, RoundToAlign))
112 return MemoryLocation::UnknownSize;
115 /// isObjectSmallerThan - Return true if we can prove that the object specified
116 /// by V is smaller than Size.
117 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
118 const DataLayout &DL,
119 const TargetLibraryInfo &TLI) {
120 // Note that the meanings of the "object" are slightly different in the
121 // following contexts:
122 // c1: llvm::getObjectSize()
123 // c2: llvm.objectsize() intrinsic
124 // c3: isObjectSmallerThan()
125 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
126 // refers to the "entire object".
128 // Consider this example:
129 // char *p = (char*)malloc(100)
132 // In the context of c1 and c2, the "object" pointed by q refers to the
133 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
135 // However, in the context of c3, the "object" refers to the chunk of memory
136 // being allocated. So, the "object" has 100 bytes, and q points to the middle
137 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
138 // parameter, before the llvm::getObjectSize() is called to get the size of
139 // entire object, we should:
140 // - either rewind the pointer q to the base-address of the object in
141 // question (in this case rewind to p), or
142 // - just give up. It is up to caller to make sure the pointer is pointing
143 // to the base address the object.
145 // We go for 2nd option for simplicity.
146 if (!isIdentifiedObject(V))
149 // This function needs to use the aligned object size because we allow
150 // reads a bit past the end given sufficient alignment.
151 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
153 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
156 /// isObjectSize - Return true if we can prove that the object specified
157 /// by V has size Size.
158 static bool isObjectSize(const Value *V, uint64_t Size,
159 const DataLayout &DL, const TargetLibraryInfo &TLI) {
160 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
161 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
164 //===----------------------------------------------------------------------===//
165 // GetElementPtr Instruction Decomposition and Analysis
166 //===----------------------------------------------------------------------===//
175 struct VariableGEPIndex {
177 ExtensionKind Extension;
180 bool operator==(const VariableGEPIndex &Other) const {
181 return V == Other.V && Extension == Other.Extension &&
182 Scale == Other.Scale;
185 bool operator!=(const VariableGEPIndex &Other) const {
186 return !operator==(Other);
192 /// GetLinearExpression - Analyze the specified value as a linear expression:
193 /// "A*V + B", where A and B are constant integers. Return the scale and offset
194 /// values as APInts and return V as a Value*, and return whether we looked
195 /// through any sign or zero extends. The incoming Value is known to have
196 /// IntegerType and it may already be sign or zero extended.
198 /// Note that this looks through extends, so the high bits may not be
199 /// represented in the result.
200 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
201 ExtensionKind &Extension,
202 const DataLayout &DL, unsigned Depth,
203 AssumptionCache *AC, DominatorTree *DT) {
204 assert(V->getType()->isIntegerTy() && "Not an integer value");
206 // Limit our recursion depth.
213 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
214 // if it's a constant, just convert it to an offset
215 // and remove the variable.
216 Offset += Const->getValue();
217 assert(Scale == 0 && "Constant values don't have a scale");
221 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
222 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
223 switch (BOp->getOpcode()) {
225 case Instruction::Or:
226 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
228 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
232 case Instruction::Add:
233 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
234 DL, Depth + 1, AC, DT);
235 Offset += RHSC->getValue();
237 case Instruction::Mul:
238 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
239 DL, Depth + 1, AC, DT);
240 Offset *= RHSC->getValue();
241 Scale *= RHSC->getValue();
243 case Instruction::Shl:
244 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
245 DL, Depth + 1, AC, DT);
246 Offset <<= RHSC->getValue().getLimitedValue();
247 Scale <<= RHSC->getValue().getLimitedValue();
253 // Since GEP indices are sign extended anyway, we don't care about the high
254 // bits of a sign or zero extended value - just scales and offsets. The
255 // extensions have to be consistent though.
256 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
257 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
258 Value *CastOp = cast<CastInst>(V)->getOperand(0);
259 unsigned OldWidth = Scale.getBitWidth();
260 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
261 Scale = Scale.trunc(SmallWidth);
262 Offset = Offset.trunc(SmallWidth);
263 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
265 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
267 Scale = Scale.zext(OldWidth);
269 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
270 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
271 Offset = Offset.sext(OldWidth);
281 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
282 /// into a base pointer with a constant offset and a number of scaled symbolic
285 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
286 /// the VarIndices vector) are Value*'s that are known to be scaled by the
287 /// specified amount, but which may have other unrepresented high bits. As such,
288 /// the gep cannot necessarily be reconstructed from its decomposed form.
290 /// When DataLayout is around, this function is capable of analyzing everything
291 /// that GetUnderlyingObject can look through. To be able to do that
292 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
293 /// depth (MaxLookupSearchDepth).
294 /// When DataLayout not is around, it just looks through pointer casts.
297 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
298 SmallVectorImpl<VariableGEPIndex> &VarIndices,
299 bool &MaxLookupReached, const DataLayout &DL,
300 AssumptionCache *AC, DominatorTree *DT) {
301 // Limit recursion depth to limit compile time in crazy cases.
302 unsigned MaxLookup = MaxLookupSearchDepth;
303 MaxLookupReached = false;
307 // See if this is a bitcast or GEP.
308 const Operator *Op = dyn_cast<Operator>(V);
310 // The only non-operator case we can handle are GlobalAliases.
311 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
312 if (!GA->mayBeOverridden()) {
313 V = GA->getAliasee();
320 if (Op->getOpcode() == Instruction::BitCast ||
321 Op->getOpcode() == Instruction::AddrSpaceCast) {
322 V = Op->getOperand(0);
326 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
328 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
329 // can come up with something. This matches what GetUnderlyingObject does.
330 if (const Instruction *I = dyn_cast<Instruction>(V))
331 // TODO: Get a DominatorTree and AssumptionCache and use them here
332 // (these are both now available in this function, but this should be
333 // updated when GetUnderlyingObject is updated). TLI should be
335 if (const Value *Simplified =
336 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
344 // Don't attempt to analyze GEPs over unsized objects.
345 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
348 unsigned AS = GEPOp->getPointerAddressSpace();
349 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
350 gep_type_iterator GTI = gep_type_begin(GEPOp);
351 for (User::const_op_iterator I = GEPOp->op_begin()+1,
352 E = GEPOp->op_end(); I != E; ++I) {
354 // Compute the (potentially symbolic) offset in bytes for this index.
355 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
356 // For a struct, add the member offset.
357 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
358 if (FieldNo == 0) continue;
360 BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
364 // For an array/pointer, add the element offset, explicitly scaled.
365 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
366 if (CIdx->isZero()) continue;
367 BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
371 uint64_t Scale = DL.getTypeAllocSize(*GTI);
372 ExtensionKind Extension = EK_NotExtended;
374 // If the integer type is smaller than the pointer size, it is implicitly
375 // sign extended to pointer size.
376 unsigned Width = Index->getType()->getIntegerBitWidth();
377 if (DL.getPointerSizeInBits(AS) > Width)
378 Extension = EK_SignExt;
380 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
381 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
382 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, DL,
385 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
386 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
387 BaseOffs += IndexOffset.getSExtValue()*Scale;
388 Scale *= IndexScale.getSExtValue();
390 // If we already had an occurrence of this index variable, merge this
391 // scale into it. For example, we want to handle:
392 // A[x][x] -> x*16 + x*4 -> x*20
393 // This also ensures that 'x' only appears in the index list once.
394 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
395 if (VarIndices[i].V == Index &&
396 VarIndices[i].Extension == Extension) {
397 Scale += VarIndices[i].Scale;
398 VarIndices.erase(VarIndices.begin()+i);
403 // Make sure that we have a scale that makes sense for this target's
405 if (unsigned ShiftBits = 64 - DL.getPointerSizeInBits(AS)) {
407 Scale = (int64_t)Scale >> ShiftBits;
411 VariableGEPIndex Entry = {Index, Extension,
412 static_cast<int64_t>(Scale)};
413 VarIndices.push_back(Entry);
417 // Analyze the base pointer next.
418 V = GEPOp->getOperand(0);
419 } while (--MaxLookup);
421 // If the chain of expressions is too deep, just return early.
422 MaxLookupReached = true;
426 //===----------------------------------------------------------------------===//
427 // BasicAliasAnalysis Pass
428 //===----------------------------------------------------------------------===//
431 static const Function *getParent(const Value *V) {
432 if (const Instruction *inst = dyn_cast<Instruction>(V))
433 return inst->getParent()->getParent();
435 if (const Argument *arg = dyn_cast<Argument>(V))
436 return arg->getParent();
441 static bool notDifferentParent(const Value *O1, const Value *O2) {
443 const Function *F1 = getParent(O1);
444 const Function *F2 = getParent(O2);
446 return !F1 || !F2 || F1 == F2;
451 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
452 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
453 static char ID; // Class identification, replacement for typeinfo
454 BasicAliasAnalysis() : ImmutablePass(ID) {
455 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
458 bool doInitialization(Module &M) override;
460 void getAnalysisUsage(AnalysisUsage &AU) const override {
461 AU.addRequired<AliasAnalysis>();
462 AU.addRequired<AssumptionCacheTracker>();
463 AU.addRequired<TargetLibraryInfoWrapperPass>();
466 AliasResult alias(const MemoryLocation &LocA,
467 const MemoryLocation &LocB) override {
468 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
469 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
470 "BasicAliasAnalysis doesn't support interprocedural queries.");
471 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
472 LocB.Ptr, LocB.Size, LocB.AATags);
473 // AliasCache rarely has more than 1 or 2 elements, always use
474 // shrink_and_clear so it quickly returns to the inline capacity of the
475 // SmallDenseMap if it ever grows larger.
476 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
477 AliasCache.shrink_and_clear();
478 VisitedPhiBBs.clear();
482 ModRefResult getModRefInfo(ImmutableCallSite CS,
483 const MemoryLocation &Loc) override;
485 ModRefResult getModRefInfo(ImmutableCallSite CS1,
486 ImmutableCallSite CS2) override;
488 /// pointsToConstantMemory - Chase pointers until we find a (constant
490 bool pointsToConstantMemory(const MemoryLocation &Loc,
491 bool OrLocal) override;
493 /// Get the location associated with a pointer argument of a callsite.
494 ModRefResult getArgModRefInfo(ImmutableCallSite CS,
495 unsigned ArgIdx) override;
497 /// getModRefBehavior - Return the behavior when calling the given
499 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
501 /// getModRefBehavior - Return the behavior when calling the given function.
502 /// For use when the call site is not known.
503 ModRefBehavior getModRefBehavior(const Function *F) override;
505 /// getAdjustedAnalysisPointer - This method is used when a pass implements
506 /// an analysis interface through multiple inheritance. If needed, it
507 /// should override this to adjust the this pointer as needed for the
508 /// specified pass info.
509 void *getAdjustedAnalysisPointer(const void *ID) override {
510 if (ID == &AliasAnalysis::ID)
511 return (AliasAnalysis*)this;
516 // AliasCache - Track alias queries to guard against recursion.
517 typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
518 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
519 AliasCacheTy AliasCache;
521 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
522 /// equality as value equality we need to make sure that the "Value" is not
523 /// part of a cycle. Otherwise, two uses could come from different
524 /// "iterations" of a cycle and see different values for the same "Value"
526 /// The following example shows the problem:
527 /// %p = phi(%alloca1, %addr2)
529 /// %addr1 = gep, %alloca2, 0, %l
530 /// %addr2 = gep %alloca2, 0, (%l + 1)
531 /// alias(%p, %addr1) -> MayAlias !
533 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
535 // Visited - Track instructions visited by pointsToConstantMemory.
536 SmallPtrSet<const Value*, 16> Visited;
538 /// \brief Check whether two Values can be considered equivalent.
540 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
541 /// whether they can not be part of a cycle in the value graph by looking at
542 /// all visited phi nodes an making sure that the phis cannot reach the
543 /// value. We have to do this because we are looking through phi nodes (That
544 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
545 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
547 /// \brief Dest and Src are the variable indices from two decomposed
548 /// GetElementPtr instructions GEP1 and GEP2 which have common base
549 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
550 /// difference between the two pointers.
551 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
552 const SmallVectorImpl<VariableGEPIndex> &Src);
554 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
555 // instruction against another.
556 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
557 const AAMDNodes &V1AAInfo,
558 const Value *V2, uint64_t V2Size,
559 const AAMDNodes &V2AAInfo,
560 const Value *UnderlyingV1, const Value *UnderlyingV2);
562 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
563 // instruction against another.
564 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
565 const AAMDNodes &PNAAInfo,
566 const Value *V2, uint64_t V2Size,
567 const AAMDNodes &V2AAInfo);
569 /// aliasSelect - Disambiguate a Select instruction against another value.
570 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
571 const AAMDNodes &SIAAInfo,
572 const Value *V2, uint64_t V2Size,
573 const AAMDNodes &V2AAInfo);
575 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
577 const Value *V2, uint64_t V2Size,
580 } // End of anonymous namespace
582 // Register this pass...
583 char BasicAliasAnalysis::ID = 0;
584 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
585 "Basic Alias Analysis (stateless AA impl)",
587 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
588 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
589 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
590 "Basic Alias Analysis (stateless AA impl)",
594 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
595 return new BasicAliasAnalysis();
598 /// pointsToConstantMemory - Returns whether the given pointer value
599 /// points to memory that is local to the function, with global constants being
600 /// considered local to all functions.
601 bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
603 assert(Visited.empty() && "Visited must be cleared after use!");
605 unsigned MaxLookup = 8;
606 SmallVector<const Value *, 16> Worklist;
607 Worklist.push_back(Loc.Ptr);
609 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
610 if (!Visited.insert(V).second) {
612 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
615 // An alloca instruction defines local memory.
616 if (OrLocal && isa<AllocaInst>(V))
619 // A global constant counts as local memory for our purposes.
620 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
621 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
622 // global to be marked constant in some modules and non-constant in
623 // others. GV may even be a declaration, not a definition.
624 if (!GV->isConstant()) {
626 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
631 // If both select values point to local memory, then so does the select.
632 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
633 Worklist.push_back(SI->getTrueValue());
634 Worklist.push_back(SI->getFalseValue());
638 // If all values incoming to a phi node point to local memory, then so does
640 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
641 // Don't bother inspecting phi nodes with many operands.
642 if (PN->getNumIncomingValues() > MaxLookup) {
644 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
646 for (Value *IncValue : PN->incoming_values())
647 Worklist.push_back(IncValue);
651 // Otherwise be conservative.
653 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
655 } while (!Worklist.empty() && --MaxLookup);
658 return Worklist.empty();
661 // FIXME: This code is duplicated with MemoryLocation and should be hoisted to
662 // some common utility location.
663 static bool isMemsetPattern16(const Function *MS,
664 const TargetLibraryInfo &TLI) {
665 if (TLI.has(LibFunc::memset_pattern16) &&
666 MS->getName() == "memset_pattern16") {
667 FunctionType *MemsetType = MS->getFunctionType();
668 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
669 isa<PointerType>(MemsetType->getParamType(0)) &&
670 isa<PointerType>(MemsetType->getParamType(1)) &&
671 isa<IntegerType>(MemsetType->getParamType(2)))
678 /// getModRefBehavior - Return the behavior when calling the given call site.
679 AliasAnalysis::ModRefBehavior
680 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
681 if (CS.doesNotAccessMemory())
682 // Can't do better than this.
683 return DoesNotAccessMemory;
685 ModRefBehavior Min = UnknownModRefBehavior;
687 // If the callsite knows it only reads memory, don't return worse
689 if (CS.onlyReadsMemory())
690 Min = OnlyReadsMemory;
692 if (CS.onlyAccessesArgMemory())
693 Min = ModRefBehavior(Min & OnlyAccessesArgumentPointees);
695 // The AliasAnalysis base class has some smarts, lets use them.
696 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
699 /// getModRefBehavior - Return the behavior when calling the given function.
700 /// For use when the call site is not known.
701 AliasAnalysis::ModRefBehavior
702 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
703 // If the function declares it doesn't access memory, we can't do better.
704 if (F->doesNotAccessMemory())
705 return DoesNotAccessMemory;
707 // For intrinsics, we can check the table.
708 if (Intrinsic::ID iid = F->getIntrinsicID()) {
709 #define GET_INTRINSIC_MODREF_BEHAVIOR
710 #include "llvm/IR/Intrinsics.gen"
711 #undef GET_INTRINSIC_MODREF_BEHAVIOR
714 ModRefBehavior Min = UnknownModRefBehavior;
716 // If the function declares it only reads memory, go with that.
717 if (F->onlyReadsMemory())
718 Min = OnlyReadsMemory;
720 if (F->onlyAccessesArgMemory())
721 Min = ModRefBehavior(Min & OnlyAccessesArgumentPointees);
723 const TargetLibraryInfo &TLI =
724 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
725 if (isMemsetPattern16(F, TLI))
726 Min = OnlyAccessesArgumentPointees;
728 // Otherwise be conservative.
729 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
732 AliasAnalysis::ModRefResult
733 BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
734 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()))
735 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 return ArgIdx ? Ref : Mod;
746 // We can bound the aliasing properties of memset_pattern16 just as we can
747 // for memcpy/memset. This is particularly important because the
748 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
749 // whenever possible.
750 if (CS.getCalledFunction() &&
751 isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
752 assert((ArgIdx == 0 || ArgIdx == 1) &&
753 "Invalid argument index for memset_pattern16");
754 return ArgIdx ? Ref : Mod;
756 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
758 return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
761 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
762 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
763 if (II && II->getIntrinsicID() == Intrinsic::assume)
769 bool BasicAliasAnalysis::doInitialization(Module &M) {
770 InitializeAliasAnalysis(this, &M.getDataLayout());
774 /// getModRefInfo - Check to see if the specified callsite can clobber the
775 /// specified memory object. Since we only look at local properties of this
776 /// function, we really can't say much about this query. We do, however, use
777 /// simple "address taken" analysis on local objects.
778 AliasAnalysis::ModRefResult
779 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
780 const MemoryLocation &Loc) {
781 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
782 "AliasAnalysis query involving multiple functions!");
784 const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
786 // If this is a tail call and Loc.Ptr points to a stack location, we know that
787 // the tail call cannot access or modify the local stack.
788 // We cannot exclude byval arguments here; these belong to the caller of
789 // the current function not to the current function, and a tail callee
790 // may reference them.
791 if (isa<AllocaInst>(Object))
792 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
793 if (CI->isTailCall())
796 // If the pointer is to a locally allocated object that does not escape,
797 // then the call can not mod/ref the pointer unless the call takes the pointer
798 // as an argument, and itself doesn't capture it.
799 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
800 isNonEscapingLocalObject(Object)) {
801 bool PassedAsArg = false;
803 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
804 CI != CE; ++CI, ++ArgNo) {
805 // Only look at the no-capture or byval pointer arguments. If this
806 // pointer were passed to arguments that were neither of these, then it
807 // couldn't be no-capture.
808 if (!(*CI)->getType()->isPointerTy() ||
809 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
812 // If this is a no-capture pointer argument, see if we can tell that it
813 // is impossible to alias the pointer we're checking. If not, we have to
814 // assume that the call could touch the pointer, even though it doesn't
816 if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
826 // While the assume intrinsic is marked as arbitrarily writing so that
827 // proper control dependencies will be maintained, it never aliases any
828 // particular memory location.
829 if (isAssumeIntrinsic(CS))
832 // The AliasAnalysis base class has some smarts, lets use them.
833 return AliasAnalysis::getModRefInfo(CS, Loc);
836 AliasAnalysis::ModRefResult
837 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
838 ImmutableCallSite CS2) {
839 // While the assume intrinsic is marked as arbitrarily writing so that
840 // proper control dependencies will be maintained, it never aliases any
841 // particular memory location.
842 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
845 // The AliasAnalysis base class has some smarts, lets use them.
846 return AliasAnalysis::getModRefInfo(CS1, CS2);
849 /// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
850 /// operators, both having the exact same pointer operand.
851 static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
853 const GEPOperator *GEP2,
855 const DataLayout &DL) {
857 assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
858 "Expected GEPs with the same pointer operand");
860 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
861 // such that the struct field accesses provably cannot alias.
862 // We also need at least two indices (the pointer, and the struct field).
863 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
864 GEP1->getNumIndices() < 2)
867 // If we don't know the size of the accesses through both GEPs, we can't
868 // determine whether the struct fields accessed can't alias.
869 if (V1Size == MemoryLocation::UnknownSize ||
870 V2Size == MemoryLocation::UnknownSize)
874 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
876 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
878 // If the last (struct) indices aren't constants, we can't say anything.
879 // If they're identical, the other indices might be also be dynamically
880 // equal, so the GEPs can alias.
881 if (!C1 || !C2 || C1 == C2)
884 // Find the last-indexed type of the GEP, i.e., the type you'd get if
885 // you stripped the last index.
886 // On the way, look at each indexed type. If there's something other
887 // than an array, different indices can lead to different final types.
888 SmallVector<Value *, 8> IntermediateIndices;
890 // Insert the first index; we don't need to check the type indexed
891 // through it as it only drops the pointer indirection.
892 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
893 IntermediateIndices.push_back(GEP1->getOperand(1));
895 // Insert all the remaining indices but the last one.
896 // Also, check that they all index through arrays.
897 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
898 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
899 GEP1->getSourceElementType(), IntermediateIndices)))
901 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
904 StructType *LastIndexedStruct =
905 dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
906 GEP1->getSourceElementType(), IntermediateIndices));
908 if (!LastIndexedStruct)
912 // - both GEPs begin indexing from the exact same pointer;
913 // - the last indices in both GEPs are constants, indexing into a struct;
914 // - said indices are different, hence, the pointed-to fields are different;
915 // - both GEPs only index through arrays prior to that.
917 // This lets us determine that the struct that GEP1 indexes into and the
918 // struct that GEP2 indexes into must either precisely overlap or be
919 // completely disjoint. Because they cannot partially overlap, indexing into
920 // different non-overlapping fields of the struct will never alias.
922 // Therefore, the only remaining thing needed to show that both GEPs can't
923 // alias is that the fields are not overlapping.
924 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
925 const uint64_t StructSize = SL->getSizeInBytes();
926 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
927 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
929 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
930 uint64_t V2Off, uint64_t V2Size) {
931 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
932 ((V2Off + V2Size <= StructSize) ||
933 (V2Off + V2Size - StructSize <= V1Off));
936 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
937 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
943 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
944 /// against another pointer. We know that V1 is a GEP, but we don't know
945 /// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
946 /// UnderlyingV2 is the same for V2.
948 AliasResult BasicAliasAnalysis::aliasGEP(
949 const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
950 const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
951 const Value *UnderlyingV1, const Value *UnderlyingV2) {
952 int64_t GEP1BaseOffset;
953 bool GEP1MaxLookupReached;
954 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
956 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
957 // different functions.
958 // FIXME: This really doesn't make any sense. We get a dominator tree below
959 // that can only refer to a single function. But this function (aliasGEP) is
960 // a method on an immutable pass that can be called when there *isn't*
961 // a single function. The old pass management layer makes this "work", but
962 // this isn't really a clean solution.
963 AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
964 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
965 if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
966 AC1 = &ACT.getAssumptionCache(
967 const_cast<Function &>(*GEP1I->getParent()->getParent()));
968 if (auto *I2 = dyn_cast<Instruction>(V2))
969 AC2 = &ACT.getAssumptionCache(
970 const_cast<Function &>(*I2->getParent()->getParent()));
972 DominatorTreeWrapperPass *DTWP =
973 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
974 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
976 // If we have two gep instructions with must-alias or not-alias'ing base
977 // pointers, figure out if the indexes to the GEP tell us anything about the
979 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
980 // Do the base pointers alias?
981 AliasResult BaseAlias =
982 aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
983 UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
985 // Check for geps of non-aliasing underlying pointers where the offsets are
987 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
988 // Do the base pointers alias assuming type and size.
989 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
990 V1AAInfo, UnderlyingV2,
992 if (PreciseBaseAlias == NoAlias) {
993 // See if the computed offset from the common pointer tells us about the
994 // relation of the resulting pointer.
995 int64_t GEP2BaseOffset;
996 bool GEP2MaxLookupReached;
997 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
998 const Value *GEP2BasePtr =
999 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
1000 GEP2MaxLookupReached, *DL, AC2, DT);
1001 const Value *GEP1BasePtr =
1002 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1003 GEP1MaxLookupReached, *DL, AC1, DT);
1004 // DecomposeGEPExpression and GetUnderlyingObject should return the
1005 // same result except when DecomposeGEPExpression has no DataLayout.
1006 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
1008 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1011 // If the max search depth is reached the result is undefined
1012 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1016 if (GEP1BaseOffset == GEP2BaseOffset &&
1017 GEP1VariableIndices == GEP2VariableIndices)
1019 GEP1VariableIndices.clear();
1023 // If we get a No or May, then return it immediately, no amount of analysis
1024 // will improve this situation.
1025 if (BaseAlias != MustAlias) return BaseAlias;
1027 // Otherwise, we have a MustAlias. Since the base pointers alias each other
1028 // exactly, see if the computed offset from the common pointer tells us
1029 // about the relation of the resulting pointer.
1030 const Value *GEP1BasePtr =
1031 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1032 GEP1MaxLookupReached, *DL, AC1, DT);
1034 int64_t GEP2BaseOffset;
1035 bool GEP2MaxLookupReached;
1036 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
1037 const Value *GEP2BasePtr =
1038 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
1039 GEP2MaxLookupReached, *DL, AC2, DT);
1041 // DecomposeGEPExpression and GetUnderlyingObject should return the
1042 // same result except when DecomposeGEPExpression has no DataLayout.
1043 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
1045 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1049 // If we know the two GEPs are based off of the exact same pointer (and not
1050 // just the same underlying object), see if that tells us anything about
1051 // the resulting pointers.
1052 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
1053 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
1054 // If we couldn't find anything interesting, don't abandon just yet.
1059 // If the max search depth is reached the result is undefined
1060 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1063 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1064 // symbolic difference.
1065 GEP1BaseOffset -= GEP2BaseOffset;
1066 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
1069 // Check to see if these two pointers are related by the getelementptr
1070 // instruction. If one pointer is a GEP with a non-zero index of the other
1071 // pointer, we know they cannot alias.
1073 // If both accesses are unknown size, we can't do anything useful here.
1074 if (V1Size == MemoryLocation::UnknownSize &&
1075 V2Size == MemoryLocation::UnknownSize)
1078 AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
1079 AAMDNodes(), V2, V2Size, V2AAInfo);
1081 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1082 // If V2 is known not to alias GEP base pointer, then the two values
1083 // cannot alias per GEP semantics: "A pointer value formed from a
1084 // getelementptr instruction is associated with the addresses associated
1085 // with the first operand of the getelementptr".
1088 const Value *GEP1BasePtr =
1089 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1090 GEP1MaxLookupReached, *DL, AC1, DT);
1092 // DecomposeGEPExpression and GetUnderlyingObject should return the
1093 // same result except when DecomposeGEPExpression has no DataLayout.
1094 if (GEP1BasePtr != UnderlyingV1) {
1096 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1099 // If the max search depth is reached the result is undefined
1100 if (GEP1MaxLookupReached)
1104 // In the two GEP Case, if there is no difference in the offsets of the
1105 // computed pointers, the resultant pointers are a must alias. This
1106 // hapens when we have two lexically identical GEP's (for example).
1108 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1109 // must aliases the GEP, the end result is a must alias also.
1110 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
1113 // If there is a constant difference between the pointers, but the difference
1114 // is less than the size of the associated memory object, then we know
1115 // that the objects are partially overlapping. If the difference is
1116 // greater, we know they do not overlap.
1117 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
1118 if (GEP1BaseOffset >= 0) {
1119 if (V2Size != MemoryLocation::UnknownSize) {
1120 if ((uint64_t)GEP1BaseOffset < V2Size)
1121 return PartialAlias;
1125 // We have the situation where:
1128 // ---------------->|
1129 // |-->V1Size |-------> V2Size
1131 // We need to know that V2Size is not unknown, otherwise we might have
1132 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1133 if (V1Size != MemoryLocation::UnknownSize &&
1134 V2Size != MemoryLocation::UnknownSize) {
1135 if (-(uint64_t)GEP1BaseOffset < V1Size)
1136 return PartialAlias;
1142 if (!GEP1VariableIndices.empty()) {
1143 uint64_t Modulo = 0;
1144 bool AllPositive = true;
1145 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
1147 // Try to distinguish something like &A[i][1] against &A[42][0].
1148 // Grab the least significant bit set in any of the scales. We
1149 // don't need std::abs here (even if the scale's negative) as we'll
1150 // be ^'ing Modulo with itself later.
1151 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
1154 // If the Value could change between cycles, then any reasoning about
1155 // the Value this cycle may not hold in the next cycle. We'll just
1156 // give up if we can't determine conditions that hold for every cycle:
1157 const Value *V = GEP1VariableIndices[i].V;
1159 bool SignKnownZero, SignKnownOne;
1160 ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
1161 0, AC1, nullptr, DT);
1163 // Zero-extension widens the variable, and so forces the sign
1165 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
1166 SignKnownZero |= IsZExt;
1167 SignKnownOne &= !IsZExt;
1169 // If the variable begins with a zero then we know it's
1170 // positive, regardless of whether the value is signed or
1172 int64_t Scale = GEP1VariableIndices[i].Scale;
1174 (SignKnownZero && Scale >= 0) ||
1175 (SignKnownOne && Scale < 0);
1179 Modulo = Modulo ^ (Modulo & (Modulo - 1));
1181 // We can compute the difference between the two addresses
1182 // mod Modulo. Check whether that difference guarantees that the
1183 // two locations do not alias.
1184 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1185 if (V1Size != MemoryLocation::UnknownSize &&
1186 V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1187 V1Size <= Modulo - ModOffset)
1190 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1191 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1192 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1193 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1197 // Statically, we can see that the base objects are the same, but the
1198 // pointers have dynamic offsets which we can't resolve. And none of our
1199 // little tricks above worked.
1201 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1202 // practical effect of this is protecting TBAA in the case of dynamic
1203 // indices into arrays of unions or malloc'd memory.
1204 return PartialAlias;
1207 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1208 // If the results agree, take it.
1211 // A mix of PartialAlias and MustAlias is PartialAlias.
1212 if ((A == PartialAlias && B == MustAlias) ||
1213 (B == PartialAlias && A == MustAlias))
1214 return PartialAlias;
1215 // Otherwise, we don't know anything.
1219 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1220 /// instruction against another.
1221 AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
1223 const AAMDNodes &SIAAInfo,
1224 const Value *V2, uint64_t V2Size,
1225 const AAMDNodes &V2AAInfo) {
1226 // If the values are Selects with the same condition, we can do a more precise
1227 // check: just check for aliases between the values on corresponding arms.
1228 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1229 if (SI->getCondition() == SI2->getCondition()) {
1231 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1232 SI2->getTrueValue(), V2Size, V2AAInfo);
1233 if (Alias == MayAlias)
1235 AliasResult ThisAlias =
1236 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1237 SI2->getFalseValue(), V2Size, V2AAInfo);
1238 return MergeAliasResults(ThisAlias, Alias);
1241 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1242 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1244 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
1245 if (Alias == MayAlias)
1248 AliasResult ThisAlias =
1249 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
1250 return MergeAliasResults(ThisAlias, Alias);
1253 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
1255 AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1256 const AAMDNodes &PNAAInfo,
1257 const Value *V2, uint64_t V2Size,
1258 const AAMDNodes &V2AAInfo) {
1259 // Track phi nodes we have visited. We use this information when we determine
1260 // value equivalence.
1261 VisitedPhiBBs.insert(PN->getParent());
1263 // If the values are PHIs in the same block, we can do a more precise
1264 // as well as efficient check: just check for aliases between the values
1265 // on corresponding edges.
1266 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1267 if (PN2->getParent() == PN->getParent()) {
1268 LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1269 MemoryLocation(V2, V2Size, V2AAInfo));
1271 std::swap(Locs.first, Locs.second);
1272 // Analyse the PHIs' inputs under the assumption that the PHIs are
1274 // If the PHIs are May/MustAlias there must be (recursively) an input
1275 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1276 // there must be an operation on the PHIs within the PHIs' value cycle
1277 // that causes a MayAlias.
1278 // Pretend the phis do not alias.
1279 AliasResult Alias = NoAlias;
1280 assert(AliasCache.count(Locs) &&
1281 "There must exist an entry for the phi node");
1282 AliasResult OrigAliasResult = AliasCache[Locs];
1283 AliasCache[Locs] = NoAlias;
1285 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1286 AliasResult ThisAlias =
1287 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1288 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1290 Alias = MergeAliasResults(ThisAlias, Alias);
1291 if (Alias == MayAlias)
1295 // Reset if speculation failed.
1296 if (Alias != NoAlias)
1297 AliasCache[Locs] = OrigAliasResult;
1302 SmallPtrSet<Value*, 4> UniqueSrc;
1303 SmallVector<Value*, 4> V1Srcs;
1304 bool isRecursive = false;
1305 for (Value *PV1 : PN->incoming_values()) {
1306 if (isa<PHINode>(PV1))
1307 // If any of the source itself is a PHI, return MayAlias conservatively
1308 // to avoid compile time explosion. The worst possible case is if both
1309 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1310 // and 'n' are the number of PHI sources.
1313 if (EnableRecPhiAnalysis)
1314 if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
1315 // Check whether the incoming value is a GEP that advances the pointer
1316 // result of this PHI node (e.g. in a loop). If this is the case, we
1317 // would recurse and always get a MayAlias. Handle this case specially
1319 if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
1320 isa<ConstantInt>(PV1GEP->idx_begin())) {
1326 if (UniqueSrc.insert(PV1).second)
1327 V1Srcs.push_back(PV1);
1330 // If this PHI node is recursive, set the size of the accessed memory to
1331 // unknown to represent all the possible values the GEP could advance the
1334 PNSize = MemoryLocation::UnknownSize;
1336 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1337 V1Srcs[0], PNSize, PNAAInfo);
1339 // Early exit if the check of the first PHI source against V2 is MayAlias.
1340 // Other results are not possible.
1341 if (Alias == MayAlias)
1344 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1345 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1346 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1347 Value *V = V1Srcs[i];
1349 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1350 V, PNSize, PNAAInfo);
1351 Alias = MergeAliasResults(ThisAlias, Alias);
1352 if (Alias == MayAlias)
1359 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1360 // such as array references.
1362 AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1363 AAMDNodes V1AAInfo, const Value *V2,
1365 AAMDNodes V2AAInfo) {
1366 // If either of the memory references is empty, it doesn't matter what the
1367 // pointer values are.
1368 if (V1Size == 0 || V2Size == 0)
1371 // Strip off any casts if they exist.
1372 V1 = V1->stripPointerCasts();
1373 V2 = V2->stripPointerCasts();
1375 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1376 // value for undef that aliases nothing in the program.
1377 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1380 // Are we checking for alias of the same value?
1381 // Because we look 'through' phi nodes we could look at "Value" pointers from
1382 // different iterations. We must therefore make sure that this is not the
1383 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1384 // happen by looking at the visited phi nodes and making sure they cannot
1386 if (isValueEqualInPotentialCycles(V1, V2))
1389 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1390 return NoAlias; // Scalars cannot alias each other
1392 // Figure out what objects these things are pointing to if we can.
1393 const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
1394 const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
1396 // Null values in the default address space don't point to any object, so they
1397 // don't alias any other pointer.
1398 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1399 if (CPN->getType()->getAddressSpace() == 0)
1401 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1402 if (CPN->getType()->getAddressSpace() == 0)
1406 // If V1/V2 point to two different objects we know that we have no alias.
1407 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1410 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1411 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1412 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1415 // Function arguments can't alias with things that are known to be
1416 // unambigously identified at the function level.
1417 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1418 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1421 // Most objects can't alias null.
1422 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1423 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1426 // If one pointer is the result of a call/invoke or load and the other is a
1427 // non-escaping local object within the same function, then we know the
1428 // object couldn't escape to a point where the call could return it.
1430 // Note that if the pointers are in different functions, there are a
1431 // variety of complications. A call with a nocapture argument may still
1432 // temporary store the nocapture argument's value in a temporary memory
1433 // location if that memory location doesn't escape. Or it may pass a
1434 // nocapture value to other functions as long as they don't capture it.
1435 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1437 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1441 // If the size of one access is larger than the entire object on the other
1442 // side, then we know such behavior is undefined and can assume no alias.
1444 if ((V1Size != MemoryLocation::UnknownSize &&
1445 isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1446 (V2Size != MemoryLocation::UnknownSize &&
1447 isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1450 // Check the cache before climbing up use-def chains. This also terminates
1451 // otherwise infinitely recursive queries.
1452 LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1453 MemoryLocation(V2, V2Size, V2AAInfo));
1455 std::swap(Locs.first, Locs.second);
1456 std::pair<AliasCacheTy::iterator, bool> Pair =
1457 AliasCache.insert(std::make_pair(Locs, MayAlias));
1459 return Pair.first->second;
1461 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1462 // GEP can't simplify, we don't even look at the PHI cases.
1463 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1465 std::swap(V1Size, V2Size);
1467 std::swap(V1AAInfo, V2AAInfo);
1469 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1470 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
1471 if (Result != MayAlias) return AliasCache[Locs] = Result;
1474 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1476 std::swap(V1Size, V2Size);
1477 std::swap(V1AAInfo, V2AAInfo);
1479 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1480 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1481 V2, V2Size, V2AAInfo);
1482 if (Result != MayAlias) return AliasCache[Locs] = Result;
1485 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1487 std::swap(V1Size, V2Size);
1488 std::swap(V1AAInfo, V2AAInfo);
1490 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1491 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1492 V2, V2Size, V2AAInfo);
1493 if (Result != MayAlias) return AliasCache[Locs] = Result;
1496 // If both pointers are pointing into the same object and one of them
1497 // accesses is accessing the entire object, then the accesses must
1498 // overlap in some way.
1500 if ((V1Size != MemoryLocation::UnknownSize &&
1501 isObjectSize(O1, V1Size, *DL, *TLI)) ||
1502 (V2Size != MemoryLocation::UnknownSize &&
1503 isObjectSize(O2, V2Size, *DL, *TLI)))
1504 return AliasCache[Locs] = PartialAlias;
1506 AliasResult Result =
1507 AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
1508 MemoryLocation(V2, V2Size, V2AAInfo));
1509 return AliasCache[Locs] = Result;
1512 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1517 const Instruction *Inst = dyn_cast<Instruction>(V);
1521 if (VisitedPhiBBs.empty())
1524 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1527 // Use dominance or loop info if available.
1528 DominatorTreeWrapperPass *DTWP =
1529 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1530 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1531 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1532 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
1534 // Make sure that the visited phis cannot reach the Value. This ensures that
1535 // the Values cannot come from different iterations of a potential cycle the
1536 // phi nodes could be involved in.
1537 for (auto *P : VisitedPhiBBs)
1538 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
1544 /// GetIndexDifference - Dest and Src are the variable indices from two
1545 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1546 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1547 /// difference between the two pointers.
1548 void BasicAliasAnalysis::GetIndexDifference(
1549 SmallVectorImpl<VariableGEPIndex> &Dest,
1550 const SmallVectorImpl<VariableGEPIndex> &Src) {
1554 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1555 const Value *V = Src[i].V;
1556 ExtensionKind Extension = Src[i].Extension;
1557 int64_t Scale = Src[i].Scale;
1559 // Find V in Dest. This is N^2, but pointer indices almost never have more
1560 // than a few variable indexes.
1561 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1562 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1563 Dest[j].Extension != Extension)
1566 // If we found it, subtract off Scale V's from the entry in Dest. If it
1567 // goes to zero, remove the entry.
1568 if (Dest[j].Scale != Scale)
1569 Dest[j].Scale -= Scale;
1571 Dest.erase(Dest.begin() + j);
1576 // If we didn't consume this entry, add it to the end of the Dest list.
1578 VariableGEPIndex Entry = { V, Extension, -Scale };
1579 Dest.push_back(Entry);