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 MemoryLocation::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 != MemoryLocation::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 != MemoryLocation::UnknownSize && ObjectSize == Size;
160 //===----------------------------------------------------------------------===//
161 // GetElementPtr Instruction Decomposition and Analysis
162 //===----------------------------------------------------------------------===//
166 // A linear transformation of a Value; this class represents ZExt(SExt(V,
167 // SExtBits), ZExtBits) * Scale + Offset.
168 struct VariableGEPIndex {
170 // An opaque Value - we can't decompose this further.
173 // We need to track what extensions we've done as we consider the same Value
174 // with different extensions as different variables in a GEP's linear
176 // e.g.: if V == -1, then sext(x) != zext(x).
182 bool operator==(const VariableGEPIndex &Other) const {
183 return V == Other.V && ZExtBits == Other.ZExtBits &&
184 SExtBits == Other.SExtBits && Scale == Other.Scale;
187 bool operator!=(const VariableGEPIndex &Other) const {
188 return !operator==(Other);
194 /// GetLinearExpression - Analyze the specified value as a linear expression:
195 /// "A*V + B", where A and B are constant integers. Return the scale and offset
196 /// values as APInts and return V as a Value*, and return whether we looked
197 /// through any sign or zero extends. The incoming Value is known to have
198 /// IntegerType and it may already be sign or zero extended.
200 /// Note that this looks through extends, so the high bits may not be
201 /// represented in the result.
202 static const Value *GetLinearExpression(const Value *V, APInt &Scale,
203 APInt &Offset, unsigned &ZExtBits,
205 const DataLayout &DL, unsigned Depth,
206 AssumptionCache *AC, DominatorTree *DT,
207 bool &NSW, bool &NUW) {
208 assert(V->getType()->isIntegerTy() && "Not an integer value");
210 // Limit our recursion depth.
217 if (const ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
218 // if it's a constant, just convert it to an offset and remove the variable.
219 // If we've been called recursively the Offset bit width will be greater
220 // than the constant's (the Offset's always as wide as the outermost call),
221 // so we'll zext here and process any extension in the isa<SExtInst> &
222 // isa<ZExtInst> cases below.
223 Offset += Const->getValue().zextOrSelf(Offset.getBitWidth());
224 assert(Scale == 0 && "Constant values don't have a scale");
228 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
229 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
231 // If we've been called recursively then Offset and Scale will be wider
232 // that the BOp operands. We'll always zext it here as we'll process sign
233 // extensions below (see the isa<SExtInst> / isa<ZExtInst> cases).
234 APInt RHS = RHSC->getValue().zextOrSelf(Offset.getBitWidth());
236 switch (BOp->getOpcode()) {
238 // We don't understand this instruction, so we can't decompose it any
243 case Instruction::Or:
244 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
246 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
250 case Instruction::Add:
251 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
252 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
255 case Instruction::Sub:
256 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
257 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
260 case Instruction::Mul:
261 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
262 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
266 case Instruction::Shl:
267 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
268 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
269 Offset <<= RHS.getLimitedValue();
270 Scale <<= RHS.getLimitedValue();
271 // the semantics of nsw and nuw for left shifts don't match those of
272 // multiplications, so we won't propagate them.
277 if (isa<OverflowingBinaryOperator>(BOp)) {
278 NUW &= BOp->hasNoUnsignedWrap();
279 NSW &= BOp->hasNoSignedWrap();
285 // Since GEP indices are sign extended anyway, we don't care about the high
286 // bits of a sign or zero extended value - just scales and offsets. The
287 // extensions have to be consistent though.
288 if (isa<SExtInst>(V) || isa<ZExtInst>(V)) {
289 Value *CastOp = cast<CastInst>(V)->getOperand(0);
290 unsigned NewWidth = V->getType()->getPrimitiveSizeInBits();
291 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
292 unsigned OldZExtBits = ZExtBits, OldSExtBits = SExtBits;
293 const Value *Result =
294 GetLinearExpression(CastOp, Scale, Offset, ZExtBits, SExtBits, DL,
295 Depth + 1, AC, DT, NSW, NUW);
297 // zext(zext(%x)) == zext(%x), and similiarly for sext; we'll handle this
298 // by just incrementing the number of bits we've extended by.
299 unsigned ExtendedBy = NewWidth - SmallWidth;
301 if (isa<SExtInst>(V) && ZExtBits == 0) {
302 // sext(sext(%x, a), b) == sext(%x, a + b)
305 // We haven't sign-wrapped, so it's valid to decompose sext(%x + c)
306 // into sext(%x) + sext(c). We'll sext the Offset ourselves:
307 unsigned OldWidth = Offset.getBitWidth();
308 Offset = Offset.trunc(SmallWidth).sext(NewWidth).zextOrSelf(OldWidth);
310 // We may have signed-wrapped, so don't decompose sext(%x + c) into
311 // sext(%x) + sext(c)
315 ZExtBits = OldZExtBits;
316 SExtBits = OldSExtBits;
318 SExtBits += ExtendedBy;
320 // sext(zext(%x, a), b) = zext(zext(%x, a), b) = zext(%x, a + b)
323 // We may have unsigned-wrapped, so don't decompose zext(%x + c) into
324 // zext(%x) + zext(c)
328 ZExtBits = OldZExtBits;
329 SExtBits = OldSExtBits;
331 ZExtBits += ExtendedBy;
342 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
343 /// into a base pointer with a constant offset and a number of scaled symbolic
346 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
347 /// the VarIndices vector) are Value*'s that are known to be scaled by the
348 /// specified amount, but which may have other unrepresented high bits. As such,
349 /// the gep cannot necessarily be reconstructed from its decomposed form.
351 /// When DataLayout is around, this function is capable of analyzing everything
352 /// that GetUnderlyingObject can look through. To be able to do that
353 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
354 /// depth (MaxLookupSearchDepth).
355 /// When DataLayout not is around, it just looks through pointer casts.
358 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
359 SmallVectorImpl<VariableGEPIndex> &VarIndices,
360 bool &MaxLookupReached, const DataLayout &DL,
361 AssumptionCache *AC, DominatorTree *DT) {
362 // Limit recursion depth to limit compile time in crazy cases.
363 unsigned MaxLookup = MaxLookupSearchDepth;
364 MaxLookupReached = false;
368 // See if this is a bitcast or GEP.
369 const Operator *Op = dyn_cast<Operator>(V);
371 // The only non-operator case we can handle are GlobalAliases.
372 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
373 if (!GA->mayBeOverridden()) {
374 V = GA->getAliasee();
381 if (Op->getOpcode() == Instruction::BitCast ||
382 Op->getOpcode() == Instruction::AddrSpaceCast) {
383 V = Op->getOperand(0);
387 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
389 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
390 // can come up with something. This matches what GetUnderlyingObject does.
391 if (const Instruction *I = dyn_cast<Instruction>(V))
392 // TODO: Get a DominatorTree and AssumptionCache and use them here
393 // (these are both now available in this function, but this should be
394 // updated when GetUnderlyingObject is updated). TLI should be
396 if (const Value *Simplified =
397 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
405 // Don't attempt to analyze GEPs over unsized objects.
406 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
409 unsigned AS = GEPOp->getPointerAddressSpace();
410 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
411 gep_type_iterator GTI = gep_type_begin(GEPOp);
412 for (User::const_op_iterator I = GEPOp->op_begin()+1,
413 E = GEPOp->op_end(); I != E; ++I) {
414 const Value *Index = *I;
415 // Compute the (potentially symbolic) offset in bytes for this index.
416 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
417 // For a struct, add the member offset.
418 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
419 if (FieldNo == 0) continue;
421 BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
425 // For an array/pointer, add the element offset, explicitly scaled.
426 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
427 if (CIdx->isZero()) continue;
428 BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
432 uint64_t Scale = DL.getTypeAllocSize(*GTI);
433 unsigned ZExtBits = 0, SExtBits = 0;
435 // If the integer type is smaller than the pointer size, it is implicitly
436 // sign extended to pointer size.
437 unsigned Width = Index->getType()->getIntegerBitWidth();
438 unsigned PointerSize = DL.getPointerSizeInBits(AS);
439 if (PointerSize > Width)
440 SExtBits += PointerSize - Width;
442 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
443 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
444 bool NSW = true, NUW = true;
445 Index = GetLinearExpression(Index, IndexScale, IndexOffset, ZExtBits,
446 SExtBits, DL, 0, AC, DT, NSW, NUW);
448 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
449 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
450 BaseOffs += IndexOffset.getSExtValue()*Scale;
451 Scale *= IndexScale.getSExtValue();
453 // If we already had an occurrence of this index variable, merge this
454 // scale into it. For example, we want to handle:
455 // A[x][x] -> x*16 + x*4 -> x*20
456 // This also ensures that 'x' only appears in the index list once.
457 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
458 if (VarIndices[i].V == Index && VarIndices[i].ZExtBits == ZExtBits &&
459 VarIndices[i].SExtBits == SExtBits) {
460 Scale += VarIndices[i].Scale;
461 VarIndices.erase(VarIndices.begin()+i);
466 // Make sure that we have a scale that makes sense for this target's
468 if (unsigned ShiftBits = 64 - PointerSize) {
470 Scale = (int64_t)Scale >> ShiftBits;
474 VariableGEPIndex Entry = {Index, ZExtBits, SExtBits,
475 static_cast<int64_t>(Scale)};
476 VarIndices.push_back(Entry);
480 // Analyze the base pointer next.
481 V = GEPOp->getOperand(0);
482 } while (--MaxLookup);
484 // If the chain of expressions is too deep, just return early.
485 MaxLookupReached = true;
489 //===----------------------------------------------------------------------===//
490 // BasicAliasAnalysis Pass
491 //===----------------------------------------------------------------------===//
494 static const Function *getParent(const Value *V) {
495 if (const Instruction *inst = dyn_cast<Instruction>(V))
496 return inst->getParent()->getParent();
498 if (const Argument *arg = dyn_cast<Argument>(V))
499 return arg->getParent();
504 static bool notDifferentParent(const Value *O1, const Value *O2) {
506 const Function *F1 = getParent(O1);
507 const Function *F2 = getParent(O2);
509 return !F1 || !F2 || F1 == F2;
514 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
515 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
516 static char ID; // Class identification, replacement for typeinfo
517 BasicAliasAnalysis() : ImmutablePass(ID) {
518 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
521 bool doInitialization(Module &M) override;
523 void getAnalysisUsage(AnalysisUsage &AU) const override {
524 AU.addRequired<AliasAnalysis>();
525 AU.addRequired<AssumptionCacheTracker>();
526 AU.addRequired<TargetLibraryInfoWrapperPass>();
529 AliasResult alias(const MemoryLocation &LocA,
530 const MemoryLocation &LocB) override {
531 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
532 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
533 "BasicAliasAnalysis doesn't support interprocedural queries.");
534 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
535 LocB.Ptr, LocB.Size, LocB.AATags);
536 // AliasCache rarely has more than 1 or 2 elements, always use
537 // shrink_and_clear so it quickly returns to the inline capacity of the
538 // SmallDenseMap if it ever grows larger.
539 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
540 AliasCache.shrink_and_clear();
541 VisitedPhiBBs.clear();
545 ModRefResult getModRefInfo(ImmutableCallSite CS,
546 const MemoryLocation &Loc) override;
548 ModRefResult getModRefInfo(ImmutableCallSite CS1,
549 ImmutableCallSite CS2) override;
551 /// pointsToConstantMemory - Chase pointers until we find a (constant
553 bool pointsToConstantMemory(const MemoryLocation &Loc,
554 bool OrLocal) override;
556 /// Get the location associated with a pointer argument of a callsite.
557 ModRefResult getArgModRefInfo(ImmutableCallSite CS,
558 unsigned ArgIdx) override;
560 /// getModRefBehavior - Return the behavior when calling the given
562 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
564 /// getModRefBehavior - Return the behavior when calling the given function.
565 /// For use when the call site is not known.
566 ModRefBehavior getModRefBehavior(const Function *F) override;
568 /// getAdjustedAnalysisPointer - This method is used when a pass implements
569 /// an analysis interface through multiple inheritance. If needed, it
570 /// should override this to adjust the this pointer as needed for the
571 /// specified pass info.
572 void *getAdjustedAnalysisPointer(const void *ID) override {
573 if (ID == &AliasAnalysis::ID)
574 return (AliasAnalysis*)this;
579 // AliasCache - Track alias queries to guard against recursion.
580 typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
581 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
582 AliasCacheTy AliasCache;
584 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
585 /// equality as value equality we need to make sure that the "Value" is not
586 /// part of a cycle. Otherwise, two uses could come from different
587 /// "iterations" of a cycle and see different values for the same "Value"
589 /// The following example shows the problem:
590 /// %p = phi(%alloca1, %addr2)
592 /// %addr1 = gep, %alloca2, 0, %l
593 /// %addr2 = gep %alloca2, 0, (%l + 1)
594 /// alias(%p, %addr1) -> MayAlias !
596 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
598 // Visited - Track instructions visited by pointsToConstantMemory.
599 SmallPtrSet<const Value*, 16> Visited;
601 /// \brief Check whether two Values can be considered equivalent.
603 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
604 /// whether they can not be part of a cycle in the value graph by looking at
605 /// all visited phi nodes an making sure that the phis cannot reach the
606 /// value. We have to do this because we are looking through phi nodes (That
607 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
608 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
610 /// \brief A Heuristic for aliasGEP that searches for a constant offset
611 /// between the variables.
613 /// GetLinearExpression has some limitations, as generally zext(%x + 1)
614 /// != zext(%x) + zext(1) if the arithmetic overflows. GetLinearExpression
615 /// will therefore conservatively refuse to decompose these expressions.
616 /// However, we know that, for all %x, zext(%x) != zext(%x + 1), even if
617 /// the addition overflows.
619 constantOffsetHeuristic(const SmallVectorImpl<VariableGEPIndex> &VarIndices,
620 uint64_t V1Size, uint64_t V2Size,
621 int64_t BaseOffset, const DataLayout *DL,
622 AssumptionCache *AC, DominatorTree *DT);
624 /// \brief Dest and Src are the variable indices from two decomposed
625 /// GetElementPtr instructions GEP1 and GEP2 which have common base
626 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
627 /// difference between the two pointers.
628 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
629 const SmallVectorImpl<VariableGEPIndex> &Src);
631 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
632 // instruction against another.
633 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
634 const AAMDNodes &V1AAInfo,
635 const Value *V2, uint64_t V2Size,
636 const AAMDNodes &V2AAInfo,
637 const Value *UnderlyingV1, const Value *UnderlyingV2);
639 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
640 // instruction against another.
641 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
642 const AAMDNodes &PNAAInfo,
643 const Value *V2, uint64_t V2Size,
644 const AAMDNodes &V2AAInfo);
646 /// aliasSelect - Disambiguate a Select instruction against another value.
647 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
648 const AAMDNodes &SIAAInfo,
649 const Value *V2, uint64_t V2Size,
650 const AAMDNodes &V2AAInfo);
652 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
654 const Value *V2, uint64_t V2Size,
657 } // End of anonymous namespace
659 // Register this pass...
660 char BasicAliasAnalysis::ID = 0;
661 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
662 "Basic Alias Analysis (stateless AA impl)",
664 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
665 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
666 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
667 "Basic Alias Analysis (stateless AA impl)",
671 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
672 return new BasicAliasAnalysis();
675 /// pointsToConstantMemory - Returns whether the given pointer value
676 /// points to memory that is local to the function, with global constants being
677 /// considered local to all functions.
678 bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
680 assert(Visited.empty() && "Visited must be cleared after use!");
682 unsigned MaxLookup = 8;
683 SmallVector<const Value *, 16> Worklist;
684 Worklist.push_back(Loc.Ptr);
686 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
687 if (!Visited.insert(V).second) {
689 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
692 // An alloca instruction defines local memory.
693 if (OrLocal && isa<AllocaInst>(V))
696 // A global constant counts as local memory for our purposes.
697 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
698 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
699 // global to be marked constant in some modules and non-constant in
700 // others. GV may even be a declaration, not a definition.
701 if (!GV->isConstant()) {
703 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
708 // If both select values point to local memory, then so does the select.
709 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
710 Worklist.push_back(SI->getTrueValue());
711 Worklist.push_back(SI->getFalseValue());
715 // If all values incoming to a phi node point to local memory, then so does
717 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
718 // Don't bother inspecting phi nodes with many operands.
719 if (PN->getNumIncomingValues() > MaxLookup) {
721 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
723 for (Value *IncValue : PN->incoming_values())
724 Worklist.push_back(IncValue);
728 // Otherwise be conservative.
730 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
732 } while (!Worklist.empty() && --MaxLookup);
735 return Worklist.empty();
738 // FIXME: This code is duplicated with MemoryLocation and should be hoisted to
739 // some common utility location.
740 static bool isMemsetPattern16(const Function *MS,
741 const TargetLibraryInfo &TLI) {
742 if (TLI.has(LibFunc::memset_pattern16) &&
743 MS->getName() == "memset_pattern16") {
744 FunctionType *MemsetType = MS->getFunctionType();
745 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
746 isa<PointerType>(MemsetType->getParamType(0)) &&
747 isa<PointerType>(MemsetType->getParamType(1)) &&
748 isa<IntegerType>(MemsetType->getParamType(2)))
755 /// getModRefBehavior - Return the behavior when calling the given call site.
756 AliasAnalysis::ModRefBehavior
757 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
758 if (CS.doesNotAccessMemory())
759 // Can't do better than this.
760 return DoesNotAccessMemory;
762 ModRefBehavior Min = UnknownModRefBehavior;
764 // If the callsite knows it only reads memory, don't return worse
766 if (CS.onlyReadsMemory())
767 Min = OnlyReadsMemory;
769 if (CS.onlyAccessesArgMemory())
770 Min = ModRefBehavior(Min & OnlyAccessesArgumentPointees);
772 // The AliasAnalysis base class has some smarts, lets use them.
773 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
776 /// getModRefBehavior - Return the behavior when calling the given function.
777 /// For use when the call site is not known.
778 AliasAnalysis::ModRefBehavior
779 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
780 // If the function declares it doesn't access memory, we can't do better.
781 if (F->doesNotAccessMemory())
782 return DoesNotAccessMemory;
784 // For intrinsics, we can check the table.
785 if (Intrinsic::ID iid = F->getIntrinsicID()) {
786 #define GET_INTRINSIC_MODREF_BEHAVIOR
787 #include "llvm/IR/Intrinsics.gen"
788 #undef GET_INTRINSIC_MODREF_BEHAVIOR
791 ModRefBehavior Min = UnknownModRefBehavior;
793 // If the function declares it only reads memory, go with that.
794 if (F->onlyReadsMemory())
795 Min = OnlyReadsMemory;
797 if (F->onlyAccessesArgMemory())
798 Min = ModRefBehavior(Min & OnlyAccessesArgumentPointees);
800 const TargetLibraryInfo &TLI =
801 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
802 if (isMemsetPattern16(F, TLI))
803 Min = OnlyAccessesArgumentPointees;
805 // Otherwise be conservative.
806 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
809 AliasAnalysis::ModRefResult
810 BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
811 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()))
812 switch (II->getIntrinsicID()) {
815 case Intrinsic::memset:
816 case Intrinsic::memcpy:
817 case Intrinsic::memmove:
818 assert((ArgIdx == 0 || ArgIdx == 1) &&
819 "Invalid argument index for memory intrinsic");
820 return ArgIdx ? Ref : Mod;
823 // We can bound the aliasing properties of memset_pattern16 just as we can
824 // for memcpy/memset. This is particularly important because the
825 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
826 // whenever possible.
827 if (CS.getCalledFunction() &&
828 isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
829 assert((ArgIdx == 0 || ArgIdx == 1) &&
830 "Invalid argument index for memset_pattern16");
831 return ArgIdx ? Ref : Mod;
833 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
835 return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
838 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
839 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
840 if (II && II->getIntrinsicID() == Intrinsic::assume)
846 bool BasicAliasAnalysis::doInitialization(Module &M) {
847 InitializeAliasAnalysis(this, &M.getDataLayout());
851 /// getModRefInfo - Check to see if the specified callsite can clobber the
852 /// specified memory object. Since we only look at local properties of this
853 /// function, we really can't say much about this query. We do, however, use
854 /// simple "address taken" analysis on local objects.
855 AliasAnalysis::ModRefResult
856 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
857 const MemoryLocation &Loc) {
858 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
859 "AliasAnalysis query involving multiple functions!");
861 const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
863 // If this is a tail call and Loc.Ptr points to a stack location, we know that
864 // the tail call cannot access or modify the local stack.
865 // We cannot exclude byval arguments here; these belong to the caller of
866 // the current function not to the current function, and a tail callee
867 // may reference them.
868 if (isa<AllocaInst>(Object))
869 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
870 if (CI->isTailCall())
873 // If the pointer is to a locally allocated object that does not escape,
874 // then the call can not mod/ref the pointer unless the call takes the pointer
875 // as an argument, and itself doesn't capture it.
876 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
877 isNonEscapingLocalObject(Object)) {
878 bool PassedAsArg = false;
880 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
881 CI != CE; ++CI, ++ArgNo) {
882 // Only look at the no-capture or byval pointer arguments. If this
883 // pointer were passed to arguments that were neither of these, then it
884 // couldn't be no-capture.
885 if (!(*CI)->getType()->isPointerTy() ||
886 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
889 // If this is a no-capture pointer argument, see if we can tell that it
890 // is impossible to alias the pointer we're checking. If not, we have to
891 // assume that the call could touch the pointer, even though it doesn't
893 if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
903 // While the assume intrinsic is marked as arbitrarily writing so that
904 // proper control dependencies will be maintained, it never aliases any
905 // particular memory location.
906 if (isAssumeIntrinsic(CS))
909 // The AliasAnalysis base class has some smarts, lets use them.
910 return AliasAnalysis::getModRefInfo(CS, Loc);
913 AliasAnalysis::ModRefResult
914 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
915 ImmutableCallSite CS2) {
916 // While the assume intrinsic is marked as arbitrarily writing so that
917 // proper control dependencies will be maintained, it never aliases any
918 // particular memory location.
919 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
922 // The AliasAnalysis base class has some smarts, lets use them.
923 return AliasAnalysis::getModRefInfo(CS1, CS2);
926 /// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
927 /// operators, both having the exact same pointer operand.
928 static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
930 const GEPOperator *GEP2,
932 const DataLayout &DL) {
934 assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
935 "Expected GEPs with the same pointer operand");
937 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
938 // such that the struct field accesses provably cannot alias.
939 // We also need at least two indices (the pointer, and the struct field).
940 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
941 GEP1->getNumIndices() < 2)
944 // If we don't know the size of the accesses through both GEPs, we can't
945 // determine whether the struct fields accessed can't alias.
946 if (V1Size == MemoryLocation::UnknownSize ||
947 V2Size == MemoryLocation::UnknownSize)
951 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
953 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
955 // If the last (struct) indices aren't constants, we can't say anything.
956 // If they're identical, the other indices might be also be dynamically
957 // equal, so the GEPs can alias.
958 if (!C1 || !C2 || C1 == C2)
961 // Find the last-indexed type of the GEP, i.e., the type you'd get if
962 // you stripped the last index.
963 // On the way, look at each indexed type. If there's something other
964 // than an array, different indices can lead to different final types.
965 SmallVector<Value *, 8> IntermediateIndices;
967 // Insert the first index; we don't need to check the type indexed
968 // through it as it only drops the pointer indirection.
969 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
970 IntermediateIndices.push_back(GEP1->getOperand(1));
972 // Insert all the remaining indices but the last one.
973 // Also, check that they all index through arrays.
974 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
975 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
976 GEP1->getSourceElementType(), IntermediateIndices)))
978 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
981 StructType *LastIndexedStruct =
982 dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
983 GEP1->getSourceElementType(), IntermediateIndices));
985 if (!LastIndexedStruct)
989 // - both GEPs begin indexing from the exact same pointer;
990 // - the last indices in both GEPs are constants, indexing into a struct;
991 // - said indices are different, hence, the pointed-to fields are different;
992 // - both GEPs only index through arrays prior to that.
994 // This lets us determine that the struct that GEP1 indexes into and the
995 // struct that GEP2 indexes into must either precisely overlap or be
996 // completely disjoint. Because they cannot partially overlap, indexing into
997 // different non-overlapping fields of the struct will never alias.
999 // Therefore, the only remaining thing needed to show that both GEPs can't
1000 // alias is that the fields are not overlapping.
1001 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
1002 const uint64_t StructSize = SL->getSizeInBytes();
1003 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
1004 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
1006 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
1007 uint64_t V2Off, uint64_t V2Size) {
1008 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
1009 ((V2Off + V2Size <= StructSize) ||
1010 (V2Off + V2Size - StructSize <= V1Off));
1013 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
1014 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
1020 bool BasicAliasAnalysis::constantOffsetHeuristic(
1021 const SmallVectorImpl<VariableGEPIndex> &VarIndices, uint64_t V1Size,
1022 uint64_t V2Size, int64_t BaseOffset, const DataLayout *DL,
1023 AssumptionCache *AC, DominatorTree *DT) {
1024 if (VarIndices.size() != 2 || V1Size == MemoryLocation::UnknownSize ||
1025 V2Size == MemoryLocation::UnknownSize || !DL)
1028 const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
1030 if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits ||
1031 Var0.Scale != -Var1.Scale)
1034 unsigned Width = Var1.V->getType()->getIntegerBitWidth();
1036 // We'll strip off the Extensions of Var0 and Var1 and do another round
1037 // of GetLinearExpression decomposition. In the example above, if Var0
1038 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
1040 APInt V0Scale(Width, 0), V0Offset(Width, 0), V1Scale(Width, 0),
1042 bool NSW = true, NUW = true;
1043 unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
1044 const Value *V0 = GetLinearExpression(Var0.V, V0Scale, V0Offset, V0ZExtBits,
1045 V0SExtBits, *DL, 0, AC, DT, NSW, NUW);
1046 NSW = true, NUW = true;
1047 const Value *V1 = GetLinearExpression(Var1.V, V1Scale, V1Offset, V1ZExtBits,
1048 V1SExtBits, *DL, 0, AC, DT, NSW, NUW);
1050 if (V0Scale != V1Scale || V0ZExtBits != V1ZExtBits ||
1051 V0SExtBits != V1SExtBits || !isValueEqualInPotentialCycles(V0, V1))
1054 // We have a hit - Var0 and Var1 only differ by a constant offset!
1056 // If we've been sext'ed then zext'd the maximum difference between Var0 and
1057 // Var1 is possible to calculate, but we're just interested in the absolute
1058 // minumum difference between the two. The minimum distance may occur due to
1059 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
1060 // the minimum distance between %i and %i + 5 is 3.
1061 APInt MinDiff = V0Offset - V1Offset,
1062 Wrapped = APInt::getMaxValue(Width) - MinDiff + APInt(Width, 1);
1063 MinDiff = APIntOps::umin(MinDiff, Wrapped);
1064 uint64_t MinDiffBytes = MinDiff.getZExtValue() * std::abs(Var0.Scale);
1066 // We can't definitely say whether GEP1 is before or after V2 due to wrapping
1067 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
1068 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
1069 // V2Size can fit in the MinDiffBytes gap.
1070 return V1Size + std::abs(BaseOffset) <= MinDiffBytes &&
1071 V2Size + std::abs(BaseOffset) <= MinDiffBytes;
1074 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
1075 /// against another pointer. We know that V1 is a GEP, but we don't know
1076 /// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
1077 /// UnderlyingV2 is the same for V2.
1079 AliasResult BasicAliasAnalysis::aliasGEP(
1080 const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
1081 const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
1082 const Value *UnderlyingV1, const Value *UnderlyingV2) {
1083 int64_t GEP1BaseOffset;
1084 bool GEP1MaxLookupReached;
1085 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
1087 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
1088 // different functions.
1089 // FIXME: This really doesn't make any sense. We get a dominator tree below
1090 // that can only refer to a single function. But this function (aliasGEP) is
1091 // a method on an immutable pass that can be called when there *isn't*
1092 // a single function. The old pass management layer makes this "work", but
1093 // this isn't really a clean solution.
1094 AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
1095 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
1096 if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
1097 AC1 = &ACT.getAssumptionCache(
1098 const_cast<Function &>(*GEP1I->getParent()->getParent()));
1099 if (auto *I2 = dyn_cast<Instruction>(V2))
1100 AC2 = &ACT.getAssumptionCache(
1101 const_cast<Function &>(*I2->getParent()->getParent()));
1103 DominatorTreeWrapperPass *DTWP =
1104 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1105 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1107 // If we have two gep instructions with must-alias or not-alias'ing base
1108 // pointers, figure out if the indexes to the GEP tell us anything about the
1110 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
1111 // Do the base pointers alias?
1112 AliasResult BaseAlias =
1113 aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
1114 UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
1116 // Check for geps of non-aliasing underlying pointers where the offsets are
1118 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
1119 // Do the base pointers alias assuming type and size.
1120 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
1121 V1AAInfo, UnderlyingV2,
1123 if (PreciseBaseAlias == NoAlias) {
1124 // See if the computed offset from the common pointer tells us about the
1125 // relation of the resulting pointer.
1126 int64_t GEP2BaseOffset;
1127 bool GEP2MaxLookupReached;
1128 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
1129 const Value *GEP2BasePtr =
1130 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
1131 GEP2MaxLookupReached, *DL, AC2, DT);
1132 const Value *GEP1BasePtr =
1133 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1134 GEP1MaxLookupReached, *DL, AC1, DT);
1135 // DecomposeGEPExpression and GetUnderlyingObject should return the
1136 // same result except when DecomposeGEPExpression has no DataLayout.
1137 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
1139 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1142 // If the max search depth is reached the result is undefined
1143 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1147 if (GEP1BaseOffset == GEP2BaseOffset &&
1148 GEP1VariableIndices == GEP2VariableIndices)
1150 GEP1VariableIndices.clear();
1154 // If we get a No or May, then return it immediately, no amount of analysis
1155 // will improve this situation.
1156 if (BaseAlias != MustAlias) return BaseAlias;
1158 // Otherwise, we have a MustAlias. Since the base pointers alias each other
1159 // exactly, see if the computed offset from the common pointer tells us
1160 // about the relation of the resulting pointer.
1161 const Value *GEP1BasePtr =
1162 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1163 GEP1MaxLookupReached, *DL, AC1, DT);
1165 int64_t GEP2BaseOffset;
1166 bool GEP2MaxLookupReached;
1167 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
1168 const Value *GEP2BasePtr =
1169 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
1170 GEP2MaxLookupReached, *DL, AC2, DT);
1172 // DecomposeGEPExpression and GetUnderlyingObject should return the
1173 // same result except when DecomposeGEPExpression has no DataLayout.
1174 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
1176 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1180 // If we know the two GEPs are based off of the exact same pointer (and not
1181 // just the same underlying object), see if that tells us anything about
1182 // the resulting pointers.
1183 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
1184 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
1185 // If we couldn't find anything interesting, don't abandon just yet.
1190 // If the max search depth is reached the result is undefined
1191 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1194 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1195 // symbolic difference.
1196 GEP1BaseOffset -= GEP2BaseOffset;
1197 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
1200 // Check to see if these two pointers are related by the getelementptr
1201 // instruction. If one pointer is a GEP with a non-zero index of the other
1202 // pointer, we know they cannot alias.
1204 // If both accesses are unknown size, we can't do anything useful here.
1205 if (V1Size == MemoryLocation::UnknownSize &&
1206 V2Size == MemoryLocation::UnknownSize)
1209 AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
1210 AAMDNodes(), V2, V2Size, V2AAInfo);
1212 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1213 // If V2 is known not to alias GEP base pointer, then the two values
1214 // cannot alias per GEP semantics: "A pointer value formed from a
1215 // getelementptr instruction is associated with the addresses associated
1216 // with the first operand of the getelementptr".
1219 const Value *GEP1BasePtr =
1220 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1221 GEP1MaxLookupReached, *DL, AC1, DT);
1223 // DecomposeGEPExpression and GetUnderlyingObject should return the
1224 // same result except when DecomposeGEPExpression has no DataLayout.
1225 if (GEP1BasePtr != UnderlyingV1) {
1227 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1230 // If the max search depth is reached the result is undefined
1231 if (GEP1MaxLookupReached)
1235 // In the two GEP Case, if there is no difference in the offsets of the
1236 // computed pointers, the resultant pointers are a must alias. This
1237 // hapens when we have two lexically identical GEP's (for example).
1239 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1240 // must aliases the GEP, the end result is a must alias also.
1241 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
1244 // If there is a constant difference between the pointers, but the difference
1245 // is less than the size of the associated memory object, then we know
1246 // that the objects are partially overlapping. If the difference is
1247 // greater, we know they do not overlap.
1248 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
1249 if (GEP1BaseOffset >= 0) {
1250 if (V2Size != MemoryLocation::UnknownSize) {
1251 if ((uint64_t)GEP1BaseOffset < V2Size)
1252 return PartialAlias;
1256 // We have the situation where:
1259 // ---------------->|
1260 // |-->V1Size |-------> V2Size
1262 // We need to know that V2Size is not unknown, otherwise we might have
1263 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1264 if (V1Size != MemoryLocation::UnknownSize &&
1265 V2Size != MemoryLocation::UnknownSize) {
1266 if (-(uint64_t)GEP1BaseOffset < V1Size)
1267 return PartialAlias;
1273 if (!GEP1VariableIndices.empty()) {
1274 uint64_t Modulo = 0;
1275 bool AllPositive = true;
1276 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
1278 // Try to distinguish something like &A[i][1] against &A[42][0].
1279 // Grab the least significant bit set in any of the scales. We
1280 // don't need std::abs here (even if the scale's negative) as we'll
1281 // be ^'ing Modulo with itself later.
1282 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
1285 // If the Value could change between cycles, then any reasoning about
1286 // the Value this cycle may not hold in the next cycle. We'll just
1287 // give up if we can't determine conditions that hold for every cycle:
1288 const Value *V = GEP1VariableIndices[i].V;
1290 bool SignKnownZero, SignKnownOne;
1291 ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
1292 0, AC1, nullptr, DT);
1294 // Zero-extension widens the variable, and so forces the sign
1296 bool IsZExt = GEP1VariableIndices[i].ZExtBits > 0 || isa<ZExtInst>(V);
1297 SignKnownZero |= IsZExt;
1298 SignKnownOne &= !IsZExt;
1300 // If the variable begins with a zero then we know it's
1301 // positive, regardless of whether the value is signed or
1303 int64_t Scale = GEP1VariableIndices[i].Scale;
1305 (SignKnownZero && Scale >= 0) ||
1306 (SignKnownOne && Scale < 0);
1310 Modulo = Modulo ^ (Modulo & (Modulo - 1));
1312 // We can compute the difference between the two addresses
1313 // mod Modulo. Check whether that difference guarantees that the
1314 // two locations do not alias.
1315 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1316 if (V1Size != MemoryLocation::UnknownSize &&
1317 V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1318 V1Size <= Modulo - ModOffset)
1321 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1322 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1323 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1324 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1327 if (constantOffsetHeuristic(GEP1VariableIndices, V1Size, V2Size,
1328 GEP1BaseOffset, DL, AC1, DT))
1332 // Statically, we can see that the base objects are the same, but the
1333 // pointers have dynamic offsets which we can't resolve. And none of our
1334 // little tricks above worked.
1336 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1337 // practical effect of this is protecting TBAA in the case of dynamic
1338 // indices into arrays of unions or malloc'd memory.
1339 return PartialAlias;
1342 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1343 // If the results agree, take it.
1346 // A mix of PartialAlias and MustAlias is PartialAlias.
1347 if ((A == PartialAlias && B == MustAlias) ||
1348 (B == PartialAlias && A == MustAlias))
1349 return PartialAlias;
1350 // Otherwise, we don't know anything.
1354 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1355 /// instruction against another.
1356 AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
1358 const AAMDNodes &SIAAInfo,
1359 const Value *V2, uint64_t V2Size,
1360 const AAMDNodes &V2AAInfo) {
1361 // If the values are Selects with the same condition, we can do a more precise
1362 // check: just check for aliases between the values on corresponding arms.
1363 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1364 if (SI->getCondition() == SI2->getCondition()) {
1366 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1367 SI2->getTrueValue(), V2Size, V2AAInfo);
1368 if (Alias == MayAlias)
1370 AliasResult ThisAlias =
1371 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1372 SI2->getFalseValue(), V2Size, V2AAInfo);
1373 return MergeAliasResults(ThisAlias, Alias);
1376 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1377 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1379 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
1380 if (Alias == MayAlias)
1383 AliasResult ThisAlias =
1384 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
1385 return MergeAliasResults(ThisAlias, Alias);
1388 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
1390 AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1391 const AAMDNodes &PNAAInfo,
1392 const Value *V2, uint64_t V2Size,
1393 const AAMDNodes &V2AAInfo) {
1394 // Track phi nodes we have visited. We use this information when we determine
1395 // value equivalence.
1396 VisitedPhiBBs.insert(PN->getParent());
1398 // If the values are PHIs in the same block, we can do a more precise
1399 // as well as efficient check: just check for aliases between the values
1400 // on corresponding edges.
1401 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1402 if (PN2->getParent() == PN->getParent()) {
1403 LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1404 MemoryLocation(V2, V2Size, V2AAInfo));
1406 std::swap(Locs.first, Locs.second);
1407 // Analyse the PHIs' inputs under the assumption that the PHIs are
1409 // If the PHIs are May/MustAlias there must be (recursively) an input
1410 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1411 // there must be an operation on the PHIs within the PHIs' value cycle
1412 // that causes a MayAlias.
1413 // Pretend the phis do not alias.
1414 AliasResult Alias = NoAlias;
1415 assert(AliasCache.count(Locs) &&
1416 "There must exist an entry for the phi node");
1417 AliasResult OrigAliasResult = AliasCache[Locs];
1418 AliasCache[Locs] = NoAlias;
1420 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1421 AliasResult ThisAlias =
1422 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1423 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1425 Alias = MergeAliasResults(ThisAlias, Alias);
1426 if (Alias == MayAlias)
1430 // Reset if speculation failed.
1431 if (Alias != NoAlias)
1432 AliasCache[Locs] = OrigAliasResult;
1437 SmallPtrSet<Value*, 4> UniqueSrc;
1438 SmallVector<Value*, 4> V1Srcs;
1439 for (Value *PV1 : PN->incoming_values()) {
1440 if (isa<PHINode>(PV1))
1441 // If any of the source itself is a PHI, return MayAlias conservatively
1442 // to avoid compile time explosion. The worst possible case is if both
1443 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1444 // and 'n' are the number of PHI sources.
1446 if (UniqueSrc.insert(PV1).second)
1447 V1Srcs.push_back(PV1);
1450 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1451 V1Srcs[0], PNSize, PNAAInfo);
1452 // Early exit if the check of the first PHI source against V2 is MayAlias.
1453 // Other results are not possible.
1454 if (Alias == MayAlias)
1457 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1458 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1459 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1460 Value *V = V1Srcs[i];
1462 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1463 V, PNSize, PNAAInfo);
1464 Alias = MergeAliasResults(ThisAlias, Alias);
1465 if (Alias == MayAlias)
1472 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1473 // such as array references.
1475 AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1476 AAMDNodes V1AAInfo, const Value *V2,
1478 AAMDNodes V2AAInfo) {
1479 // If either of the memory references is empty, it doesn't matter what the
1480 // pointer values are.
1481 if (V1Size == 0 || V2Size == 0)
1484 // Strip off any casts if they exist.
1485 V1 = V1->stripPointerCasts();
1486 V2 = V2->stripPointerCasts();
1488 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1489 // value for undef that aliases nothing in the program.
1490 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1493 // Are we checking for alias of the same value?
1494 // Because we look 'through' phi nodes we could look at "Value" pointers from
1495 // different iterations. We must therefore make sure that this is not the
1496 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1497 // happen by looking at the visited phi nodes and making sure they cannot
1499 if (isValueEqualInPotentialCycles(V1, V2))
1502 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1503 return NoAlias; // Scalars cannot alias each other
1505 // Figure out what objects these things are pointing to if we can.
1506 const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
1507 const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
1509 // Null values in the default address space don't point to any object, so they
1510 // don't alias any other pointer.
1511 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1512 if (CPN->getType()->getAddressSpace() == 0)
1514 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1515 if (CPN->getType()->getAddressSpace() == 0)
1519 // If V1/V2 point to two different objects we know that we have no alias.
1520 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1523 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1524 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1525 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1528 // Function arguments can't alias with things that are known to be
1529 // unambigously identified at the function level.
1530 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1531 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1534 // Most objects can't alias null.
1535 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1536 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1539 // If one pointer is the result of a call/invoke or load and the other is a
1540 // non-escaping local object within the same function, then we know the
1541 // object couldn't escape to a point where the call could return it.
1543 // Note that if the pointers are in different functions, there are a
1544 // variety of complications. A call with a nocapture argument may still
1545 // temporary store the nocapture argument's value in a temporary memory
1546 // location if that memory location doesn't escape. Or it may pass a
1547 // nocapture value to other functions as long as they don't capture it.
1548 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1550 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1554 // If the size of one access is larger than the entire object on the other
1555 // side, then we know such behavior is undefined and can assume no alias.
1557 if ((V1Size != MemoryLocation::UnknownSize &&
1558 isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1559 (V2Size != MemoryLocation::UnknownSize &&
1560 isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1563 // Check the cache before climbing up use-def chains. This also terminates
1564 // otherwise infinitely recursive queries.
1565 LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1566 MemoryLocation(V2, V2Size, V2AAInfo));
1568 std::swap(Locs.first, Locs.second);
1569 std::pair<AliasCacheTy::iterator, bool> Pair =
1570 AliasCache.insert(std::make_pair(Locs, MayAlias));
1572 return Pair.first->second;
1574 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1575 // GEP can't simplify, we don't even look at the PHI cases.
1576 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1578 std::swap(V1Size, V2Size);
1580 std::swap(V1AAInfo, V2AAInfo);
1582 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1583 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
1584 if (Result != MayAlias) return AliasCache[Locs] = Result;
1587 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1589 std::swap(V1Size, V2Size);
1590 std::swap(V1AAInfo, V2AAInfo);
1592 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1593 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1594 V2, V2Size, V2AAInfo);
1595 if (Result != MayAlias) return AliasCache[Locs] = Result;
1598 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1600 std::swap(V1Size, V2Size);
1601 std::swap(V1AAInfo, V2AAInfo);
1603 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1604 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1605 V2, V2Size, V2AAInfo);
1606 if (Result != MayAlias) return AliasCache[Locs] = Result;
1609 // If both pointers are pointing into the same object and one of them
1610 // accesses is accessing the entire object, then the accesses must
1611 // overlap in some way.
1613 if ((V1Size != MemoryLocation::UnknownSize &&
1614 isObjectSize(O1, V1Size, *DL, *TLI)) ||
1615 (V2Size != MemoryLocation::UnknownSize &&
1616 isObjectSize(O2, V2Size, *DL, *TLI)))
1617 return AliasCache[Locs] = PartialAlias;
1619 AliasResult Result =
1620 AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
1621 MemoryLocation(V2, V2Size, V2AAInfo));
1622 return AliasCache[Locs] = Result;
1625 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1630 const Instruction *Inst = dyn_cast<Instruction>(V);
1634 if (VisitedPhiBBs.empty())
1637 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1640 // Use dominance or loop info if available.
1641 DominatorTreeWrapperPass *DTWP =
1642 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1643 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1644 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1645 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
1647 // Make sure that the visited phis cannot reach the Value. This ensures that
1648 // the Values cannot come from different iterations of a potential cycle the
1649 // phi nodes could be involved in.
1650 for (auto *P : VisitedPhiBBs)
1651 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
1657 /// GetIndexDifference - Dest and Src are the variable indices from two
1658 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1659 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1660 /// difference between the two pointers.
1661 void BasicAliasAnalysis::GetIndexDifference(
1662 SmallVectorImpl<VariableGEPIndex> &Dest,
1663 const SmallVectorImpl<VariableGEPIndex> &Src) {
1667 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1668 const Value *V = Src[i].V;
1669 unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits;
1670 int64_t Scale = Src[i].Scale;
1672 // Find V in Dest. This is N^2, but pointer indices almost never have more
1673 // than a few variable indexes.
1674 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1675 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1676 Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits)
1679 // If we found it, subtract off Scale V's from the entry in Dest. If it
1680 // goes to zero, remove the entry.
1681 if (Dest[j].Scale != Scale)
1682 Dest[j].Scale -= Scale;
1684 Dest.erase(Dest.begin() + j);
1689 // If we didn't consume this entry, add it to the end of the Dest list.
1691 VariableGEPIndex Entry = {V, ZExtBits, SExtBits, -Scale};
1692 Dest.push_back(Entry);