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/AssumptionTracker.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/ValueTracking.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
45 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
46 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
47 /// careful with value equivalence. We use reachability to make sure a value
48 /// cannot be involved in a cycle.
49 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
51 // The max limit of the search depth in DecomposeGEPExpression() and
52 // GetUnderlyingObject(), both functions need to use the same search
53 // depth otherwise the algorithm in aliasGEP will assert.
54 static const unsigned MaxLookupSearchDepth = 6;
56 //===----------------------------------------------------------------------===//
58 //===----------------------------------------------------------------------===//
60 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
61 /// object that never escapes from the function.
62 static bool isNonEscapingLocalObject(const Value *V) {
63 // If this is a local allocation, check to see if it escapes.
64 if (isa<AllocaInst>(V) || isNoAliasCall(V))
65 // Set StoreCaptures to True so that we can assume in our callers that the
66 // pointer is not the result of a load instruction. Currently
67 // PointerMayBeCaptured doesn't have any special analysis for the
68 // StoreCaptures=false case; if it did, our callers could be refined to be
70 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
72 // If this is an argument that corresponds to a byval or noalias argument,
73 // then it has not escaped before entering the function. Check if it escapes
74 // inside the function.
75 if (const Argument *A = dyn_cast<Argument>(V))
76 if (A->hasByValAttr() || A->hasNoAliasAttr())
77 // Note even if the argument is marked nocapture we still need to check
78 // for copies made inside the function. The nocapture attribute only
79 // specifies that there are no copies made that outlive the function.
80 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
85 /// isEscapeSource - Return true if the pointer is one which would have
86 /// been considered an escape by isNonEscapingLocalObject.
87 static bool isEscapeSource(const Value *V) {
88 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
91 // The load case works because isNonEscapingLocalObject considers all
92 // stores to be escapes (it passes true for the StoreCaptures argument
93 // to PointerMayBeCaptured).
100 /// getObjectSize - Return the size of the object specified by V, or
101 /// UnknownSize if unknown.
102 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
103 const TargetLibraryInfo &TLI,
104 bool RoundToAlign = false) {
106 if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign))
108 return AliasAnalysis::UnknownSize;
111 /// isObjectSmallerThan - Return true if we can prove that the object specified
112 /// by V is smaller than Size.
113 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
114 const DataLayout &DL,
115 const TargetLibraryInfo &TLI) {
116 // Note that the meanings of the "object" are slightly different in the
117 // following contexts:
118 // c1: llvm::getObjectSize()
119 // c2: llvm.objectsize() intrinsic
120 // c3: isObjectSmallerThan()
121 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
122 // refers to the "entire object".
124 // Consider this example:
125 // char *p = (char*)malloc(100)
128 // In the context of c1 and c2, the "object" pointed by q refers to the
129 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
131 // However, in the context of c3, the "object" refers to the chunk of memory
132 // being allocated. So, the "object" has 100 bytes, and q points to the middle
133 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
134 // parameter, before the llvm::getObjectSize() is called to get the size of
135 // entire object, we should:
136 // - either rewind the pointer q to the base-address of the object in
137 // question (in this case rewind to p), or
138 // - just give up. It is up to caller to make sure the pointer is pointing
139 // to the base address the object.
141 // We go for 2nd option for simplicity.
142 if (!isIdentifiedObject(V))
145 // This function needs to use the aligned object size because we allow
146 // reads a bit past the end given sufficient alignment.
147 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
149 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
152 /// isObjectSize - Return true if we can prove that the object specified
153 /// by V has size Size.
154 static bool isObjectSize(const Value *V, uint64_t Size,
155 const DataLayout &DL, const TargetLibraryInfo &TLI) {
156 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
157 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
160 //===----------------------------------------------------------------------===//
161 // GetElementPtr Instruction Decomposition and Analysis
162 //===----------------------------------------------------------------------===//
171 struct VariableGEPIndex {
173 ExtensionKind Extension;
176 bool operator==(const VariableGEPIndex &Other) const {
177 return V == Other.V && Extension == Other.Extension &&
178 Scale == Other.Scale;
181 bool operator!=(const VariableGEPIndex &Other) const {
182 return !operator==(Other);
188 /// GetLinearExpression - Analyze the specified value as a linear expression:
189 /// "A*V + B", where A and B are constant integers. Return the scale and offset
190 /// values as APInts and return V as a Value*, and return whether we looked
191 /// through any sign or zero extends. The incoming Value is known to have
192 /// IntegerType and it may already be sign or zero extended.
194 /// Note that this looks through extends, so the high bits may not be
195 /// represented in the result.
196 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
197 ExtensionKind &Extension,
198 const DataLayout &DL, unsigned Depth,
199 AssumptionTracker *AT,
201 assert(V->getType()->isIntegerTy() && "Not an integer value");
203 // Limit our recursion depth.
210 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
211 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
212 switch (BOp->getOpcode()) {
214 case Instruction::Or:
215 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
217 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL, 0,
221 case Instruction::Add:
222 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
223 DL, Depth+1, AT, DT);
224 Offset += RHSC->getValue();
226 case Instruction::Mul:
227 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
228 DL, Depth+1, AT, DT);
229 Offset *= RHSC->getValue();
230 Scale *= RHSC->getValue();
232 case Instruction::Shl:
233 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
234 DL, Depth+1, AT, DT);
235 Offset <<= RHSC->getValue().getLimitedValue();
236 Scale <<= RHSC->getValue().getLimitedValue();
242 // Since GEP indices are sign extended anyway, we don't care about the high
243 // bits of a sign or zero extended value - just scales and offsets. The
244 // extensions have to be consistent though.
245 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
246 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
247 Value *CastOp = cast<CastInst>(V)->getOperand(0);
248 unsigned OldWidth = Scale.getBitWidth();
249 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
250 Scale = Scale.trunc(SmallWidth);
251 Offset = Offset.trunc(SmallWidth);
252 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
254 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
255 DL, Depth+1, AT, DT);
256 Scale = Scale.zext(OldWidth);
258 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
259 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
260 Offset = Offset.sext(OldWidth);
270 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
271 /// into a base pointer with a constant offset and a number of scaled symbolic
274 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
275 /// the VarIndices vector) are Value*'s that are known to be scaled by the
276 /// specified amount, but which may have other unrepresented high bits. As such,
277 /// the gep cannot necessarily be reconstructed from its decomposed form.
279 /// When DataLayout is around, this function is capable of analyzing everything
280 /// that GetUnderlyingObject can look through. To be able to do that
281 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
282 /// depth (MaxLookupSearchDepth).
283 /// When DataLayout not is around, it just looks through pointer casts.
286 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
287 SmallVectorImpl<VariableGEPIndex> &VarIndices,
288 bool &MaxLookupReached, const DataLayout *DL,
289 AssumptionTracker *AT, DominatorTree *DT) {
290 // Limit recursion depth to limit compile time in crazy cases.
291 unsigned MaxLookup = MaxLookupSearchDepth;
292 MaxLookupReached = false;
296 // See if this is a bitcast or GEP.
297 const Operator *Op = dyn_cast<Operator>(V);
299 // The only non-operator case we can handle are GlobalAliases.
300 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
301 if (!GA->mayBeOverridden()) {
302 V = GA->getAliasee();
309 if (Op->getOpcode() == Instruction::BitCast ||
310 Op->getOpcode() == Instruction::AddrSpaceCast) {
311 V = Op->getOperand(0);
315 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
317 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
318 // can come up with something. This matches what GetUnderlyingObject does.
319 if (const Instruction *I = dyn_cast<Instruction>(V))
320 // TODO: Get a DominatorTree and AssumptionTracker and use them here
321 // (these are both now available in this function, but this should be
322 // updated when GetUnderlyingObject is updated). TLI should be
324 if (const Value *Simplified =
325 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
333 // Don't attempt to analyze GEPs over unsized objects.
334 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
337 // If we are lacking DataLayout information, we can't compute the offets of
338 // elements computed by GEPs. However, we can handle bitcast equivalent
341 if (!GEPOp->hasAllZeroIndices())
343 V = GEPOp->getOperand(0);
347 unsigned AS = GEPOp->getPointerAddressSpace();
348 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
349 gep_type_iterator GTI = gep_type_begin(GEPOp);
350 for (User::const_op_iterator I = GEPOp->op_begin()+1,
351 E = GEPOp->op_end(); I != E; ++I) {
353 // Compute the (potentially symbolic) offset in bytes for this index.
354 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
355 // For a struct, add the member offset.
356 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
357 if (FieldNo == 0) continue;
359 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
363 // For an array/pointer, add the element offset, explicitly scaled.
364 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
365 if (CIdx->isZero()) continue;
366 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
370 uint64_t Scale = DL->getTypeAllocSize(*GTI);
371 ExtensionKind Extension = EK_NotExtended;
373 // If the integer type is smaller than the pointer size, it is implicitly
374 // sign extended to pointer size.
375 unsigned Width = Index->getType()->getIntegerBitWidth();
376 if (DL->getPointerSizeInBits(AS) > Width)
377 Extension = EK_SignExt;
379 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
380 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
381 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
384 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
385 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
386 BaseOffs += IndexOffset.getSExtValue()*Scale;
387 Scale *= IndexScale.getSExtValue();
389 // If we already had an occurrence of this index variable, merge this
390 // scale into it. For example, we want to handle:
391 // A[x][x] -> x*16 + x*4 -> x*20
392 // This also ensures that 'x' only appears in the index list once.
393 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
394 if (VarIndices[i].V == Index &&
395 VarIndices[i].Extension == Extension) {
396 Scale += VarIndices[i].Scale;
397 VarIndices.erase(VarIndices.begin()+i);
402 // Make sure that we have a scale that makes sense for this target's
404 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
406 Scale = (int64_t)Scale >> ShiftBits;
410 VariableGEPIndex Entry = {Index, Extension,
411 static_cast<int64_t>(Scale)};
412 VarIndices.push_back(Entry);
416 // Analyze the base pointer next.
417 V = GEPOp->getOperand(0);
418 } while (--MaxLookup);
420 // If the chain of expressions is too deep, just return early.
421 MaxLookupReached = true;
425 //===----------------------------------------------------------------------===//
426 // BasicAliasAnalysis Pass
427 //===----------------------------------------------------------------------===//
430 static const Function *getParent(const Value *V) {
431 if (const Instruction *inst = dyn_cast<Instruction>(V))
432 return inst->getParent()->getParent();
434 if (const Argument *arg = dyn_cast<Argument>(V))
435 return arg->getParent();
440 static bool notDifferentParent(const Value *O1, const Value *O2) {
442 const Function *F1 = getParent(O1);
443 const Function *F2 = getParent(O2);
445 return !F1 || !F2 || F1 == F2;
450 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
451 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
452 static char ID; // Class identification, replacement for typeinfo
453 BasicAliasAnalysis() : ImmutablePass(ID) {
454 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
457 void initializePass() override {
458 InitializeAliasAnalysis(this);
461 void getAnalysisUsage(AnalysisUsage &AU) const override {
462 AU.addRequired<AliasAnalysis>();
463 AU.addRequired<AssumptionTracker>();
464 AU.addRequired<TargetLibraryInfo>();
467 AliasResult alias(const Location &LocA, const Location &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 Location &Loc) override;
485 ModRefResult getModRefInfo(ImmutableCallSite CS1,
486 ImmutableCallSite CS2) override;
488 /// pointsToConstantMemory - Chase pointers until we find a (constant
490 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
492 /// Get the location associated with a pointer argument of a callsite.
493 Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
494 ModRefResult &Mask) override;
496 /// getModRefBehavior - Return the behavior when calling the given
498 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
500 /// getModRefBehavior - Return the behavior when calling the given function.
501 /// For use when the call site is not known.
502 ModRefBehavior getModRefBehavior(const Function *F) override;
504 /// getAdjustedAnalysisPointer - This method is used when a pass implements
505 /// an analysis interface through multiple inheritance. If needed, it
506 /// should override this to adjust the this pointer as needed for the
507 /// specified pass info.
508 void *getAdjustedAnalysisPointer(const void *ID) override {
509 if (ID == &AliasAnalysis::ID)
510 return (AliasAnalysis*)this;
515 // AliasCache - Track alias queries to guard against recursion.
516 typedef std::pair<Location, Location> LocPair;
517 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
518 AliasCacheTy AliasCache;
520 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
521 /// equality as value equality we need to make sure that the "Value" is not
522 /// part of a cycle. Otherwise, two uses could come from different
523 /// "iterations" of a cycle and see different values for the same "Value"
525 /// The following example shows the problem:
526 /// %p = phi(%alloca1, %addr2)
528 /// %addr1 = gep, %alloca2, 0, %l
529 /// %addr2 = gep %alloca2, 0, (%l + 1)
530 /// alias(%p, %addr1) -> MayAlias !
532 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
534 // Visited - Track instructions visited by pointsToConstantMemory.
535 SmallPtrSet<const Value*, 16> Visited;
537 /// \brief Check whether two Values can be considered equivalent.
539 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
540 /// whether they can not be part of a cycle in the value graph by looking at
541 /// all visited phi nodes an making sure that the phis cannot reach the
542 /// value. We have to do this because we are looking through phi nodes (That
543 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
544 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
546 /// \brief Dest and Src are the variable indices from two decomposed
547 /// GetElementPtr instructions GEP1 and GEP2 which have common base
548 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
549 /// difference between the two pointers.
550 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
551 const SmallVectorImpl<VariableGEPIndex> &Src);
553 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
554 // instruction against another.
555 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
556 const AAMDNodes &V1AAInfo,
557 const Value *V2, uint64_t V2Size,
558 const AAMDNodes &V2AAInfo,
559 const Value *UnderlyingV1, const Value *UnderlyingV2);
561 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
562 // instruction against another.
563 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
564 const AAMDNodes &PNAAInfo,
565 const Value *V2, uint64_t V2Size,
566 const AAMDNodes &V2AAInfo);
568 /// aliasSelect - Disambiguate a Select instruction against another value.
569 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
570 const AAMDNodes &SIAAInfo,
571 const Value *V2, uint64_t V2Size,
572 const AAMDNodes &V2AAInfo);
574 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
576 const Value *V2, uint64_t V2Size,
579 } // End of anonymous namespace
581 // Register this pass...
582 char BasicAliasAnalysis::ID = 0;
583 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
584 "Basic Alias Analysis (stateless AA impl)",
586 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
587 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
588 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
589 "Basic Alias Analysis (stateless AA impl)",
593 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
594 return new BasicAliasAnalysis();
597 /// pointsToConstantMemory - Returns whether the given pointer value
598 /// points to memory that is local to the function, with global constants being
599 /// considered local to all functions.
601 BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
602 assert(Visited.empty() && "Visited must be cleared after use!");
604 unsigned MaxLookup = 8;
605 SmallVector<const Value *, 16> Worklist;
606 Worklist.push_back(Loc.Ptr);
608 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
609 if (!Visited.insert(V)) {
611 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
614 // An alloca instruction defines local memory.
615 if (OrLocal && isa<AllocaInst>(V))
618 // A global constant counts as local memory for our purposes.
619 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
620 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
621 // global to be marked constant in some modules and non-constant in
622 // others. GV may even be a declaration, not a definition.
623 if (!GV->isConstant()) {
625 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
630 // If both select values point to local memory, then so does the select.
631 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
632 Worklist.push_back(SI->getTrueValue());
633 Worklist.push_back(SI->getFalseValue());
637 // If all values incoming to a phi node point to local memory, then so does
639 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
640 // Don't bother inspecting phi nodes with many operands.
641 if (PN->getNumIncomingValues() > MaxLookup) {
643 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
645 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
646 Worklist.push_back(PN->getIncomingValue(i));
650 // Otherwise be conservative.
652 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
654 } while (!Worklist.empty() && --MaxLookup);
657 return Worklist.empty();
660 static bool isMemsetPattern16(const Function *MS,
661 const TargetLibraryInfo &TLI) {
662 if (TLI.has(LibFunc::memset_pattern16) &&
663 MS->getName() == "memset_pattern16") {
664 FunctionType *MemsetType = MS->getFunctionType();
665 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
666 isa<PointerType>(MemsetType->getParamType(0)) &&
667 isa<PointerType>(MemsetType->getParamType(1)) &&
668 isa<IntegerType>(MemsetType->getParamType(2)))
675 /// getModRefBehavior - Return the behavior when calling the given call site.
676 AliasAnalysis::ModRefBehavior
677 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
678 if (CS.doesNotAccessMemory())
679 // Can't do better than this.
680 return DoesNotAccessMemory;
682 ModRefBehavior Min = UnknownModRefBehavior;
684 // If the callsite knows it only reads memory, don't return worse
686 if (CS.onlyReadsMemory())
687 Min = OnlyReadsMemory;
689 // The AliasAnalysis base class has some smarts, lets use them.
690 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
693 /// getModRefBehavior - Return the behavior when calling the given function.
694 /// For use when the call site is not known.
695 AliasAnalysis::ModRefBehavior
696 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
697 // If the function declares it doesn't access memory, we can't do better.
698 if (F->doesNotAccessMemory())
699 return DoesNotAccessMemory;
701 // For intrinsics, we can check the table.
702 if (unsigned iid = F->getIntrinsicID()) {
703 #define GET_INTRINSIC_MODREF_BEHAVIOR
704 #include "llvm/IR/Intrinsics.gen"
705 #undef GET_INTRINSIC_MODREF_BEHAVIOR
708 ModRefBehavior Min = UnknownModRefBehavior;
710 // If the function declares it only reads memory, go with that.
711 if (F->onlyReadsMemory())
712 Min = OnlyReadsMemory;
714 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
715 if (isMemsetPattern16(F, TLI))
716 Min = OnlyAccessesArgumentPointees;
718 // Otherwise be conservative.
719 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
722 AliasAnalysis::Location
723 BasicAliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
724 ModRefResult &Mask) {
725 Location Loc = AliasAnalysis::getArgLocation(CS, ArgIdx, Mask);
726 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
727 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
729 switch (II->getIntrinsicID()) {
731 case Intrinsic::memset:
732 case Intrinsic::memcpy:
733 case Intrinsic::memmove: {
734 assert((ArgIdx == 0 || ArgIdx == 1) &&
735 "Invalid argument index for memory intrinsic");
736 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
737 Loc.Size = LenCI->getZExtValue();
738 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
739 "Memory intrinsic location pointer not argument?");
740 Mask = ArgIdx ? Ref : Mod;
743 case Intrinsic::lifetime_start:
744 case Intrinsic::lifetime_end:
745 case Intrinsic::invariant_start: {
746 assert(ArgIdx == 1 && "Invalid argument index");
747 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
748 "Intrinsic location pointer not argument?");
749 Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
752 case Intrinsic::invariant_end: {
753 assert(ArgIdx == 2 && "Invalid argument index");
754 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
755 "Intrinsic location pointer not argument?");
756 Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
759 case Intrinsic::arm_neon_vld1: {
760 assert(ArgIdx == 0 && "Invalid argument index");
761 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
762 "Intrinsic location pointer not argument?");
763 // LLVM's vld1 and vst1 intrinsics currently only support a single
766 Loc.Size = DL->getTypeStoreSize(II->getType());
769 case Intrinsic::arm_neon_vst1: {
770 assert(ArgIdx == 0 && "Invalid argument index");
771 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
772 "Intrinsic location pointer not argument?");
774 Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType());
779 // We can bound the aliasing properties of memset_pattern16 just as we can
780 // for memcpy/memset. This is particularly important because the
781 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
782 // whenever possible.
783 else if (CS.getCalledFunction() &&
784 isMemsetPattern16(CS.getCalledFunction(), TLI)) {
785 assert((ArgIdx == 0 || ArgIdx == 1) &&
786 "Invalid argument index for memset_pattern16");
789 else if (const ConstantInt *LenCI =
790 dyn_cast<ConstantInt>(CS.getArgument(2)))
791 Loc.Size = LenCI->getZExtValue();
792 assert(Loc.Ptr == CS.getArgument(ArgIdx) &&
793 "memset_pattern16 location pointer not argument?");
794 Mask = ArgIdx ? Ref : Mod;
796 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
801 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
802 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
803 if (II && II->getIntrinsicID() == Intrinsic::assume)
809 /// getModRefInfo - Check to see if the specified callsite can clobber the
810 /// specified memory object. Since we only look at local properties of this
811 /// function, we really can't say much about this query. We do, however, use
812 /// simple "address taken" analysis on local objects.
813 AliasAnalysis::ModRefResult
814 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
815 const Location &Loc) {
816 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
817 "AliasAnalysis query involving multiple functions!");
819 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
821 // If this is a tail call and Loc.Ptr points to a stack location, we know that
822 // the tail call cannot access or modify the local stack.
823 // We cannot exclude byval arguments here; these belong to the caller of
824 // the current function not to the current function, and a tail callee
825 // may reference them.
826 if (isa<AllocaInst>(Object))
827 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
828 if (CI->isTailCall())
831 // If the pointer is to a locally allocated object that does not escape,
832 // then the call can not mod/ref the pointer unless the call takes the pointer
833 // as an argument, and itself doesn't capture it.
834 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
835 isNonEscapingLocalObject(Object)) {
836 bool PassedAsArg = false;
838 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
839 CI != CE; ++CI, ++ArgNo) {
840 // Only look at the no-capture or byval pointer arguments. If this
841 // pointer were passed to arguments that were neither of these, then it
842 // couldn't be no-capture.
843 if (!(*CI)->getType()->isPointerTy() ||
844 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
847 // If this is a no-capture pointer argument, see if we can tell that it
848 // is impossible to alias the pointer we're checking. If not, we have to
849 // assume that the call could touch the pointer, even though it doesn't
851 if (!isNoAlias(Location(*CI), Location(Object))) {
861 // While the assume intrinsic is marked as arbitrarily writing so that
862 // proper control dependencies will be maintained, it never aliases any
863 // particular memory location.
864 if (isAssumeIntrinsic(CS))
867 // The AliasAnalysis base class has some smarts, lets use them.
868 return AliasAnalysis::getModRefInfo(CS, Loc);
871 AliasAnalysis::ModRefResult
872 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
873 ImmutableCallSite CS2) {
874 // While the assume intrinsic is marked as arbitrarily writing so that
875 // proper control dependencies will be maintained, it never aliases any
876 // particular memory location.
877 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
880 // The AliasAnalysis base class has some smarts, lets use them.
881 return AliasAnalysis::getModRefInfo(CS1, CS2);
884 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
885 /// against another pointer. We know that V1 is a GEP, but we don't know
886 /// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
887 /// UnderlyingV2 is the same for V2.
889 AliasAnalysis::AliasResult
890 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
891 const AAMDNodes &V1AAInfo,
892 const Value *V2, uint64_t V2Size,
893 const AAMDNodes &V2AAInfo,
894 const Value *UnderlyingV1,
895 const Value *UnderlyingV2) {
896 int64_t GEP1BaseOffset;
897 bool GEP1MaxLookupReached;
898 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
900 AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
901 DominatorTreeWrapperPass *DTWP =
902 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
903 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
905 // If we have two gep instructions with must-alias or not-alias'ing base
906 // pointers, figure out if the indexes to the GEP tell us anything about the
908 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
909 // Do the base pointers alias?
910 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
911 UnderlyingV2, UnknownSize, AAMDNodes());
913 // Check for geps of non-aliasing underlying pointers where the offsets are
915 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
916 // Do the base pointers alias assuming type and size.
917 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
918 V1AAInfo, UnderlyingV2,
920 if (PreciseBaseAlias == NoAlias) {
921 // See if the computed offset from the common pointer tells us about the
922 // relation of the resulting pointer.
923 int64_t GEP2BaseOffset;
924 bool GEP2MaxLookupReached;
925 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
926 const Value *GEP2BasePtr =
927 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
928 GEP2MaxLookupReached, DL, AT, DT);
929 const Value *GEP1BasePtr =
930 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
931 GEP1MaxLookupReached, DL, AT, DT);
932 // DecomposeGEPExpression and GetUnderlyingObject should return the
933 // same result except when DecomposeGEPExpression has no DataLayout.
934 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
936 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
939 // If the max search depth is reached the result is undefined
940 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
944 if (GEP1BaseOffset == GEP2BaseOffset &&
945 GEP1VariableIndices == GEP2VariableIndices)
947 GEP1VariableIndices.clear();
951 // If we get a No or May, then return it immediately, no amount of analysis
952 // will improve this situation.
953 if (BaseAlias != MustAlias) return BaseAlias;
955 // Otherwise, we have a MustAlias. Since the base pointers alias each other
956 // exactly, see if the computed offset from the common pointer tells us
957 // about the relation of the resulting pointer.
958 const Value *GEP1BasePtr =
959 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
960 GEP1MaxLookupReached, DL, AT, DT);
962 int64_t GEP2BaseOffset;
963 bool GEP2MaxLookupReached;
964 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
965 const Value *GEP2BasePtr =
966 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
967 GEP2MaxLookupReached, DL, AT, DT);
969 // DecomposeGEPExpression and GetUnderlyingObject should return the
970 // same result except when DecomposeGEPExpression has no DataLayout.
971 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
973 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
976 // If the max search depth is reached the result is undefined
977 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
980 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
981 // symbolic difference.
982 GEP1BaseOffset -= GEP2BaseOffset;
983 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
986 // Check to see if these two pointers are related by the getelementptr
987 // instruction. If one pointer is a GEP with a non-zero index of the other
988 // pointer, we know they cannot alias.
990 // If both accesses are unknown size, we can't do anything useful here.
991 if (V1Size == UnknownSize && V2Size == UnknownSize)
994 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
995 V2, V2Size, V2AAInfo);
997 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
998 // If V2 is known not to alias GEP base pointer, then the two values
999 // cannot alias per GEP semantics: "A pointer value formed from a
1000 // getelementptr instruction is associated with the addresses associated
1001 // with the first operand of the getelementptr".
1004 const Value *GEP1BasePtr =
1005 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1006 GEP1MaxLookupReached, DL, AT, DT);
1008 // DecomposeGEPExpression and GetUnderlyingObject should return the
1009 // same result except when DecomposeGEPExpression has no DataLayout.
1010 if (GEP1BasePtr != UnderlyingV1) {
1012 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
1015 // If the max search depth is reached the result is undefined
1016 if (GEP1MaxLookupReached)
1020 // In the two GEP Case, if there is no difference in the offsets of the
1021 // computed pointers, the resultant pointers are a must alias. This
1022 // hapens when we have two lexically identical GEP's (for example).
1024 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1025 // must aliases the GEP, the end result is a must alias also.
1026 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
1029 // If there is a constant difference between the pointers, but the difference
1030 // is less than the size of the associated memory object, then we know
1031 // that the objects are partially overlapping. If the difference is
1032 // greater, we know they do not overlap.
1033 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
1034 if (GEP1BaseOffset >= 0) {
1035 if (V2Size != UnknownSize) {
1036 if ((uint64_t)GEP1BaseOffset < V2Size)
1037 return PartialAlias;
1041 // We have the situation where:
1044 // ---------------->|
1045 // |-->V1Size |-------> V2Size
1047 // We need to know that V2Size is not unknown, otherwise we might have
1048 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1049 if (V1Size != UnknownSize && V2Size != UnknownSize) {
1050 if (-(uint64_t)GEP1BaseOffset < V1Size)
1051 return PartialAlias;
1057 // Try to distinguish something like &A[i][1] against &A[42][0].
1058 // Grab the least significant bit set in any of the scales.
1059 if (!GEP1VariableIndices.empty()) {
1060 uint64_t Modulo = 0;
1061 bool AllPositive = true;
1062 for (unsigned i = 0, e = GEP1VariableIndices.size();
1063 i != e && AllPositive; ++i) {
1064 const Value *V = GEP1VariableIndices[i].V;
1065 Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
1067 bool SignKnownZero, SignKnownOne;
1069 const_cast<Value *>(V),
1070 SignKnownZero, SignKnownOne,
1071 DL, 0, AT, nullptr, DT);
1073 // Zero-extension widens the variable, and so forces the sign
1075 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
1076 SignKnownZero |= IsZExt;
1077 SignKnownOne &= !IsZExt;
1079 // If the variable begins with a zero then we know it's
1080 // positive, regardless of whether the value is signed or
1082 int64_t Scale = GEP1VariableIndices[i].Scale;
1084 (SignKnownZero && Scale >= 0) ||
1085 (SignKnownOne && Scale < 0);
1087 // If the Value is currently positive but could change in a cycle,
1088 // then we can't guarantee it'll always br positive.
1089 if (AllPositive && !isValueEqualInPotentialCycles(V, V))
1090 AllPositive = false;
1093 Modulo = Modulo ^ (Modulo & (Modulo - 1));
1095 // We can compute the difference between the two addresses
1096 // mod Modulo. Check whether that difference guarantees that the
1097 // two locations do not alias.
1098 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1099 if (V1Size != UnknownSize && V2Size != UnknownSize &&
1100 ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1103 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1104 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1105 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1106 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1110 // Statically, we can see that the base objects are the same, but the
1111 // pointers have dynamic offsets which we can't resolve. And none of our
1112 // little tricks above worked.
1114 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1115 // practical effect of this is protecting TBAA in the case of dynamic
1116 // indices into arrays of unions or malloc'd memory.
1117 return PartialAlias;
1120 static AliasAnalysis::AliasResult
1121 MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1122 // If the results agree, take it.
1125 // A mix of PartialAlias and MustAlias is PartialAlias.
1126 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1127 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1128 return AliasAnalysis::PartialAlias;
1129 // Otherwise, we don't know anything.
1130 return AliasAnalysis::MayAlias;
1133 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1134 /// instruction against another.
1135 AliasAnalysis::AliasResult
1136 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
1137 const AAMDNodes &SIAAInfo,
1138 const Value *V2, uint64_t V2Size,
1139 const AAMDNodes &V2AAInfo) {
1140 // If the values are Selects with the same condition, we can do a more precise
1141 // check: just check for aliases between the values on corresponding arms.
1142 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1143 if (SI->getCondition() == SI2->getCondition()) {
1145 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1146 SI2->getTrueValue(), V2Size, V2AAInfo);
1147 if (Alias == MayAlias)
1149 AliasResult ThisAlias =
1150 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1151 SI2->getFalseValue(), V2Size, V2AAInfo);
1152 return MergeAliasResults(ThisAlias, Alias);
1155 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1156 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1158 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
1159 if (Alias == MayAlias)
1162 AliasResult ThisAlias =
1163 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
1164 return MergeAliasResults(ThisAlias, Alias);
1167 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
1169 AliasAnalysis::AliasResult
1170 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1171 const AAMDNodes &PNAAInfo,
1172 const Value *V2, uint64_t V2Size,
1173 const AAMDNodes &V2AAInfo) {
1174 // Track phi nodes we have visited. We use this information when we determine
1175 // value equivalence.
1176 VisitedPhiBBs.insert(PN->getParent());
1178 // If the values are PHIs in the same block, we can do a more precise
1179 // as well as efficient check: just check for aliases between the values
1180 // on corresponding edges.
1181 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1182 if (PN2->getParent() == PN->getParent()) {
1183 LocPair Locs(Location(PN, PNSize, PNAAInfo),
1184 Location(V2, V2Size, V2AAInfo));
1186 std::swap(Locs.first, Locs.second);
1187 // Analyse the PHIs' inputs under the assumption that the PHIs are
1189 // If the PHIs are May/MustAlias there must be (recursively) an input
1190 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1191 // there must be an operation on the PHIs within the PHIs' value cycle
1192 // that causes a MayAlias.
1193 // Pretend the phis do not alias.
1194 AliasResult Alias = NoAlias;
1195 assert(AliasCache.count(Locs) &&
1196 "There must exist an entry for the phi node");
1197 AliasResult OrigAliasResult = AliasCache[Locs];
1198 AliasCache[Locs] = NoAlias;
1200 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1201 AliasResult ThisAlias =
1202 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1203 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1205 Alias = MergeAliasResults(ThisAlias, Alias);
1206 if (Alias == MayAlias)
1210 // Reset if speculation failed.
1211 if (Alias != NoAlias)
1212 AliasCache[Locs] = OrigAliasResult;
1217 SmallPtrSet<Value*, 4> UniqueSrc;
1218 SmallVector<Value*, 4> V1Srcs;
1219 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1220 Value *PV1 = PN->getIncomingValue(i);
1221 if (isa<PHINode>(PV1))
1222 // If any of the source itself is a PHI, return MayAlias conservatively
1223 // to avoid compile time explosion. The worst possible case is if both
1224 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1225 // and 'n' are the number of PHI sources.
1227 if (UniqueSrc.insert(PV1))
1228 V1Srcs.push_back(PV1);
1231 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1232 V1Srcs[0], PNSize, PNAAInfo);
1233 // Early exit if the check of the first PHI source against V2 is MayAlias.
1234 // Other results are not possible.
1235 if (Alias == MayAlias)
1238 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1239 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1240 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1241 Value *V = V1Srcs[i];
1243 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1244 V, PNSize, PNAAInfo);
1245 Alias = MergeAliasResults(ThisAlias, Alias);
1246 if (Alias == MayAlias)
1253 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1254 // such as array references.
1256 AliasAnalysis::AliasResult
1257 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1259 const Value *V2, uint64_t V2Size,
1260 AAMDNodes V2AAInfo) {
1261 // If either of the memory references is empty, it doesn't matter what the
1262 // pointer values are.
1263 if (V1Size == 0 || V2Size == 0)
1266 // Strip off any casts if they exist.
1267 V1 = V1->stripPointerCasts();
1268 V2 = V2->stripPointerCasts();
1270 // Are we checking for alias of the same value?
1271 // Because we look 'through' phi nodes we could look at "Value" pointers from
1272 // different iterations. We must therefore make sure that this is not the
1273 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1274 // happen by looking at the visited phi nodes and making sure they cannot
1276 if (isValueEqualInPotentialCycles(V1, V2))
1279 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1280 return NoAlias; // Scalars cannot alias each other
1282 // Figure out what objects these things are pointing to if we can.
1283 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1284 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
1286 // Null values in the default address space don't point to any object, so they
1287 // don't alias any other pointer.
1288 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1289 if (CPN->getType()->getAddressSpace() == 0)
1291 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1292 if (CPN->getType()->getAddressSpace() == 0)
1296 // If V1/V2 point to two different objects we know that we have no alias.
1297 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1300 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1301 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1302 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1305 // Function arguments can't alias with things that are known to be
1306 // unambigously identified at the function level.
1307 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1308 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1311 // Most objects can't alias null.
1312 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1313 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1316 // If one pointer is the result of a call/invoke or load and the other is a
1317 // non-escaping local object within the same function, then we know the
1318 // object couldn't escape to a point where the call could return it.
1320 // Note that if the pointers are in different functions, there are a
1321 // variety of complications. A call with a nocapture argument may still
1322 // temporary store the nocapture argument's value in a temporary memory
1323 // location if that memory location doesn't escape. Or it may pass a
1324 // nocapture value to other functions as long as they don't capture it.
1325 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1327 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1331 // If the size of one access is larger than the entire object on the other
1332 // side, then we know such behavior is undefined and can assume no alias.
1334 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1335 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1338 // Check the cache before climbing up use-def chains. This also terminates
1339 // otherwise infinitely recursive queries.
1340 LocPair Locs(Location(V1, V1Size, V1AAInfo),
1341 Location(V2, V2Size, V2AAInfo));
1343 std::swap(Locs.first, Locs.second);
1344 std::pair<AliasCacheTy::iterator, bool> Pair =
1345 AliasCache.insert(std::make_pair(Locs, MayAlias));
1347 return Pair.first->second;
1349 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1350 // GEP can't simplify, we don't even look at the PHI cases.
1351 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1353 std::swap(V1Size, V2Size);
1355 std::swap(V1AAInfo, V2AAInfo);
1357 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1358 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
1359 if (Result != MayAlias) return AliasCache[Locs] = Result;
1362 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1364 std::swap(V1Size, V2Size);
1365 std::swap(V1AAInfo, V2AAInfo);
1367 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1368 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1369 V2, V2Size, V2AAInfo);
1370 if (Result != MayAlias) return AliasCache[Locs] = Result;
1373 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1375 std::swap(V1Size, V2Size);
1376 std::swap(V1AAInfo, V2AAInfo);
1378 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1379 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1380 V2, V2Size, V2AAInfo);
1381 if (Result != MayAlias) return AliasCache[Locs] = Result;
1384 // If both pointers are pointing into the same object and one of them
1385 // accesses is accessing the entire object, then the accesses must
1386 // overlap in some way.
1388 if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1389 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
1390 return AliasCache[Locs] = PartialAlias;
1392 AliasResult Result =
1393 AliasAnalysis::alias(Location(V1, V1Size, V1AAInfo),
1394 Location(V2, V2Size, V2AAInfo));
1395 return AliasCache[Locs] = Result;
1398 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1403 const Instruction *Inst = dyn_cast<Instruction>(V);
1407 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1410 // Use dominance or loop info if available.
1411 DominatorTreeWrapperPass *DTWP =
1412 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1413 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1414 LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
1416 // Make sure that the visited phis cannot reach the Value. This ensures that
1417 // the Values cannot come from different iterations of a potential cycle the
1418 // phi nodes could be involved in.
1419 for (auto *P : VisitedPhiBBs)
1420 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
1426 /// GetIndexDifference - Dest and Src are the variable indices from two
1427 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1428 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1429 /// difference between the two pointers.
1430 void BasicAliasAnalysis::GetIndexDifference(
1431 SmallVectorImpl<VariableGEPIndex> &Dest,
1432 const SmallVectorImpl<VariableGEPIndex> &Src) {
1436 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1437 const Value *V = Src[i].V;
1438 ExtensionKind Extension = Src[i].Extension;
1439 int64_t Scale = Src[i].Scale;
1441 // Find V in Dest. This is N^2, but pointer indices almost never have more
1442 // than a few variable indexes.
1443 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1444 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1445 Dest[j].Extension != Extension)
1448 // If we found it, subtract off Scale V's from the entry in Dest. If it
1449 // goes to zero, remove the entry.
1450 if (Dest[j].Scale != Scale)
1451 Dest[j].Scale -= Scale;
1453 Dest.erase(Dest.begin() + j);
1458 // If we didn't consume this entry, add it to the end of the Dest list.
1460 VariableGEPIndex Entry = { V, Extension, -Scale };
1461 Dest.push_back(Entry);