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/BasicAliasAnalysis.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/Analysis/CaptureTracking.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/ErrorHandling.h"
41 /// Enable analysis of recursive PHI nodes.
42 static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi", cl::Hidden,
45 /// SearchLimitReached / SearchTimes shows how often the limit of
46 /// to decompose GEPs is reached. It will affect the precision
47 /// of basic alias analysis.
48 #define DEBUG_TYPE "basicaa"
49 STATISTIC(SearchLimitReached, "Number of times the limit to "
50 "decompose GEPs is reached");
51 STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
53 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
54 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
55 /// careful with value equivalence. We use reachability to make sure a value
56 /// cannot be involved in a cycle.
57 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
59 // The max limit of the search depth in DecomposeGEPExpression() and
60 // GetUnderlyingObject(), both functions need to use the same search
61 // depth otherwise the algorithm in aliasGEP will assert.
62 static const unsigned MaxLookupSearchDepth = 6;
64 //===----------------------------------------------------------------------===//
66 //===----------------------------------------------------------------------===//
68 /// Returns true if the pointer is to a function-local object that never
69 /// escapes from the function.
70 static bool isNonEscapingLocalObject(const Value *V) {
71 // If this is a local allocation, check to see if it escapes.
72 if (isa<AllocaInst>(V) || isNoAliasCall(V))
73 // Set StoreCaptures to True so that we can assume in our callers that the
74 // pointer is not the result of a load instruction. Currently
75 // PointerMayBeCaptured doesn't have any special analysis for the
76 // StoreCaptures=false case; if it did, our callers could be refined to be
78 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
80 // If this is an argument that corresponds to a byval or noalias argument,
81 // then it has not escaped before entering the function. Check if it escapes
82 // inside the function.
83 if (const Argument *A = dyn_cast<Argument>(V))
84 if (A->hasByValAttr() || A->hasNoAliasAttr())
85 // Note even if the argument is marked nocapture we still need to check
86 // for copies made inside the function. The nocapture attribute only
87 // specifies that there are no copies made that outlive the function.
88 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
93 /// Returns true if the pointer is one which would have been considered an
94 /// escape by isNonEscapingLocalObject.
95 static bool isEscapeSource(const Value *V) {
96 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
99 // The load case works because isNonEscapingLocalObject considers all
100 // stores to be escapes (it passes true for the StoreCaptures argument
101 // to PointerMayBeCaptured).
102 if (isa<LoadInst>(V))
108 /// Returns the size of the object specified by V, or UnknownSize if unknown.
109 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
110 const TargetLibraryInfo &TLI,
111 bool RoundToAlign = false) {
113 if (getObjectSize(V, Size, DL, &TLI, RoundToAlign))
115 return MemoryLocation::UnknownSize;
118 /// Returns true if we can prove that the object specified by V is smaller than
120 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
121 const DataLayout &DL,
122 const TargetLibraryInfo &TLI) {
123 // Note that the meanings of the "object" are slightly different in the
124 // following contexts:
125 // c1: llvm::getObjectSize()
126 // c2: llvm.objectsize() intrinsic
127 // c3: isObjectSmallerThan()
128 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
129 // refers to the "entire object".
131 // Consider this example:
132 // char *p = (char*)malloc(100)
135 // In the context of c1 and c2, the "object" pointed by q refers to the
136 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
138 // However, in the context of c3, the "object" refers to the chunk of memory
139 // being allocated. So, the "object" has 100 bytes, and q points to the middle
140 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
141 // parameter, before the llvm::getObjectSize() is called to get the size of
142 // entire object, we should:
143 // - either rewind the pointer q to the base-address of the object in
144 // question (in this case rewind to p), or
145 // - just give up. It is up to caller to make sure the pointer is pointing
146 // to the base address the object.
148 // We go for 2nd option for simplicity.
149 if (!isIdentifiedObject(V))
152 // This function needs to use the aligned object size because we allow
153 // reads a bit past the end given sufficient alignment.
154 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/ true);
156 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
159 /// Returns true if we can prove that the object specified by V has size Size.
160 static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
161 const TargetLibraryInfo &TLI) {
162 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
163 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
166 //===----------------------------------------------------------------------===//
167 // GetElementPtr Instruction Decomposition and Analysis
168 //===----------------------------------------------------------------------===//
170 /// Analyzes the specified value as a linear expression: "A*V + B", where A and
171 /// B are constant integers.
173 /// Returns the scale and offset values as APInts and return V as a Value*, and
174 /// return whether we looked through any sign or zero extends. The incoming
175 /// Value is known to have IntegerType and it may already be sign or zero
178 /// Note that this looks through extends, so the high bits may not be
179 /// represented in the result.
180 /*static*/ Value *BasicAliasAnalysis::GetLinearExpression(
181 Value *V, APInt &Scale, APInt &Offset, ExtensionKind &Extension,
182 const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
184 assert(V->getType()->isIntegerTy() && "Not an integer value");
186 // Limit our recursion depth.
193 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
194 // if it's a constant, just convert it to an offset
195 // and remove the variable.
196 Offset += Const->getValue();
197 assert(Scale == 0 && "Constant values don't have a scale");
201 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
202 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
203 switch (BOp->getOpcode()) {
206 case Instruction::Or:
207 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
209 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
213 case Instruction::Add:
214 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
215 DL, Depth + 1, AC, DT);
216 Offset += RHSC->getValue();
218 case Instruction::Mul:
219 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
220 DL, Depth + 1, AC, DT);
221 Offset *= RHSC->getValue();
222 Scale *= RHSC->getValue();
224 case Instruction::Shl:
225 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
226 DL, Depth + 1, AC, DT);
227 Offset <<= RHSC->getValue().getLimitedValue();
228 Scale <<= RHSC->getValue().getLimitedValue();
234 // Since GEP indices are sign extended anyway, we don't care about the high
235 // bits of a sign or zero extended value - just scales and offsets. The
236 // extensions have to be consistent though.
237 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
238 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
239 Value *CastOp = cast<CastInst>(V)->getOperand(0);
240 unsigned OldWidth = Scale.getBitWidth();
241 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
242 Scale = Scale.trunc(SmallWidth);
243 Offset = Offset.trunc(SmallWidth);
244 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
246 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
248 Scale = Scale.zext(OldWidth);
250 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
251 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
252 Offset = Offset.sext(OldWidth);
262 /// If V is a symbolic pointer expression, decompose it into a base pointer
263 /// with a constant offset and a number of scaled symbolic offsets.
265 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
266 /// in the VarIndices vector) are Value*'s that are known to be scaled by the
267 /// specified amount, but which may have other unrepresented high bits. As
268 /// such, the gep cannot necessarily be reconstructed from its decomposed form.
270 /// When DataLayout is around, this function is capable of analyzing everything
271 /// that GetUnderlyingObject can look through. To be able to do that
272 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
273 /// depth (MaxLookupSearchDepth). When DataLayout not is around, it just looks
274 /// through pointer casts.
275 /*static*/ const Value *BasicAliasAnalysis::DecomposeGEPExpression(
276 const Value *V, int64_t &BaseOffs,
277 SmallVectorImpl<VariableGEPIndex> &VarIndices, bool &MaxLookupReached,
278 const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT) {
279 // Limit recursion depth to limit compile time in crazy cases.
280 unsigned MaxLookup = MaxLookupSearchDepth;
281 MaxLookupReached = false;
286 // See if this is a bitcast or GEP.
287 const Operator *Op = dyn_cast<Operator>(V);
289 // The only non-operator case we can handle are GlobalAliases.
290 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
291 if (!GA->mayBeOverridden()) {
292 V = GA->getAliasee();
299 if (Op->getOpcode() == Instruction::BitCast ||
300 Op->getOpcode() == Instruction::AddrSpaceCast) {
301 V = Op->getOperand(0);
305 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
307 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
308 // can come up with something. This matches what GetUnderlyingObject does.
309 if (const Instruction *I = dyn_cast<Instruction>(V))
310 // TODO: Get a DominatorTree and AssumptionCache and use them here
311 // (these are both now available in this function, but this should be
312 // updated when GetUnderlyingObject is updated). TLI should be
314 if (const Value *Simplified =
315 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
323 // Don't attempt to analyze GEPs over unsized objects.
324 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
327 unsigned AS = GEPOp->getPointerAddressSpace();
328 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
329 gep_type_iterator GTI = gep_type_begin(GEPOp);
330 for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
333 // Compute the (potentially symbolic) offset in bytes for this index.
334 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
335 // For a struct, add the member offset.
336 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
340 BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
344 // For an array/pointer, add the element offset, explicitly scaled.
345 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
348 BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
352 uint64_t Scale = DL.getTypeAllocSize(*GTI);
353 ExtensionKind Extension = EK_NotExtended;
355 // If the integer type is smaller than the pointer size, it is implicitly
356 // sign extended to pointer size.
357 unsigned Width = Index->getType()->getIntegerBitWidth();
358 if (DL.getPointerSizeInBits(AS) > Width)
359 Extension = EK_SignExt;
361 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
362 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
363 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, DL,
366 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
367 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
368 BaseOffs += IndexOffset.getSExtValue() * Scale;
369 Scale *= IndexScale.getSExtValue();
371 // If we already had an occurrence of this index variable, merge this
372 // scale into it. For example, we want to handle:
373 // A[x][x] -> x*16 + x*4 -> x*20
374 // This also ensures that 'x' only appears in the index list once.
375 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
376 if (VarIndices[i].V == Index && VarIndices[i].Extension == Extension) {
377 Scale += VarIndices[i].Scale;
378 VarIndices.erase(VarIndices.begin() + i);
383 // Make sure that we have a scale that makes sense for this target's
385 if (unsigned ShiftBits = 64 - DL.getPointerSizeInBits(AS)) {
387 Scale = (int64_t)Scale >> ShiftBits;
391 VariableGEPIndex Entry = {Index, Extension,
392 static_cast<int64_t>(Scale)};
393 VarIndices.push_back(Entry);
397 // Analyze the base pointer next.
398 V = GEPOp->getOperand(0);
399 } while (--MaxLookup);
401 // If the chain of expressions is too deep, just return early.
402 MaxLookupReached = true;
403 SearchLimitReached++;
407 //===----------------------------------------------------------------------===//
408 // BasicAliasAnalysis Pass
409 //===----------------------------------------------------------------------===//
411 // Register the pass...
412 char BasicAliasAnalysis::ID = 0;
413 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
414 "Basic Alias Analysis (stateless AA impl)", false,
416 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
417 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
418 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
419 "Basic Alias Analysis (stateless AA impl)", false, true,
422 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
423 return new BasicAliasAnalysis();
426 /// Returns whether the given pointer value points to memory that is local to
427 /// the function, with global constants being considered local to all
429 bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
431 assert(Visited.empty() && "Visited must be cleared after use!");
433 unsigned MaxLookup = 8;
434 SmallVector<const Value *, 16> Worklist;
435 Worklist.push_back(Loc.Ptr);
437 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
438 if (!Visited.insert(V).second) {
440 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
443 // An alloca instruction defines local memory.
444 if (OrLocal && isa<AllocaInst>(V))
447 // A global constant counts as local memory for our purposes.
448 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
449 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
450 // global to be marked constant in some modules and non-constant in
451 // others. GV may even be a declaration, not a definition.
452 if (!GV->isConstant()) {
454 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
459 // If both select values point to local memory, then so does the select.
460 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
461 Worklist.push_back(SI->getTrueValue());
462 Worklist.push_back(SI->getFalseValue());
466 // If all values incoming to a phi node point to local memory, then so does
468 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
469 // Don't bother inspecting phi nodes with many operands.
470 if (PN->getNumIncomingValues() > MaxLookup) {
472 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
474 for (Value *IncValue : PN->incoming_values())
475 Worklist.push_back(IncValue);
479 // Otherwise be conservative.
481 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
483 } while (!Worklist.empty() && --MaxLookup);
486 return Worklist.empty();
489 // FIXME: This code is duplicated with MemoryLocation and should be hoisted to
490 // some common utility location.
491 static bool isMemsetPattern16(const Function *MS,
492 const TargetLibraryInfo &TLI) {
493 if (TLI.has(LibFunc::memset_pattern16) &&
494 MS->getName() == "memset_pattern16") {
495 FunctionType *MemsetType = MS->getFunctionType();
496 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
497 isa<PointerType>(MemsetType->getParamType(0)) &&
498 isa<PointerType>(MemsetType->getParamType(1)) &&
499 isa<IntegerType>(MemsetType->getParamType(2)))
506 /// Returns the behavior when calling the given call site.
507 FunctionModRefBehavior
508 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
509 if (CS.doesNotAccessMemory())
510 // Can't do better than this.
511 return FMRB_DoesNotAccessMemory;
513 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
515 // If the callsite knows it only reads memory, don't return worse
517 if (CS.onlyReadsMemory())
518 Min = FMRB_OnlyReadsMemory;
520 if (CS.onlyAccessesArgMemory())
521 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
523 // The AliasAnalysis base class has some smarts, lets use them.
524 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
527 /// Returns the behavior when calling the given function. For use when the call
528 /// site is not known.
529 FunctionModRefBehavior
530 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
531 // If the function declares it doesn't access memory, we can't do better.
532 if (F->doesNotAccessMemory())
533 return FMRB_DoesNotAccessMemory;
535 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
537 // If the function declares it only reads memory, go with that.
538 if (F->onlyReadsMemory())
539 Min = FMRB_OnlyReadsMemory;
541 if (F->onlyAccessesArgMemory())
542 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
544 const TargetLibraryInfo &TLI =
545 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
546 if (isMemsetPattern16(F, TLI))
547 Min = FMRB_OnlyAccessesArgumentPointees;
549 // Otherwise be conservative.
550 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
553 ModRefInfo BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS,
555 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()))
556 switch (II->getIntrinsicID()) {
559 case Intrinsic::memset:
560 case Intrinsic::memcpy:
561 case Intrinsic::memmove:
562 assert((ArgIdx == 0 || ArgIdx == 1) &&
563 "Invalid argument index for memory intrinsic");
564 return ArgIdx ? MRI_Ref : MRI_Mod;
567 // We can bound the aliasing properties of memset_pattern16 just as we can
568 // for memcpy/memset. This is particularly important because the
569 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
570 // whenever possible.
571 if (CS.getCalledFunction() &&
572 isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
573 assert((ArgIdx == 0 || ArgIdx == 1) &&
574 "Invalid argument index for memset_pattern16");
575 return ArgIdx ? MRI_Ref : MRI_Mod;
577 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
579 return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
582 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
583 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
584 if (II && II->getIntrinsicID() == Intrinsic::assume)
590 bool BasicAliasAnalysis::doInitialization(Module &M) {
591 InitializeAliasAnalysis(this, &M.getDataLayout());
595 /// Checks to see if the specified callsite can clobber the specified memory
598 /// Since we only look at local properties of this function, we really can't
599 /// say much about this query. We do, however, use simple "address taken"
600 /// analysis on local objects.
601 ModRefInfo BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
602 const MemoryLocation &Loc) {
603 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
604 "AliasAnalysis query involving multiple functions!");
606 const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
608 // If this is a tail call and Loc.Ptr points to a stack location, we know that
609 // the tail call cannot access or modify the local stack.
610 // We cannot exclude byval arguments here; these belong to the caller of
611 // the current function not to the current function, and a tail callee
612 // may reference them.
613 if (isa<AllocaInst>(Object))
614 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
615 if (CI->isTailCall())
618 // If the pointer is to a locally allocated object that does not escape,
619 // then the call can not mod/ref the pointer unless the call takes the pointer
620 // as an argument, and itself doesn't capture it.
621 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
622 isNonEscapingLocalObject(Object)) {
623 bool PassedAsArg = false;
625 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
626 CI != CE; ++CI, ++ArgNo) {
627 // Only look at the no-capture or byval pointer arguments. If this
628 // pointer were passed to arguments that were neither of these, then it
629 // couldn't be no-capture.
630 if (!(*CI)->getType()->isPointerTy() ||
631 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
634 // If this is a no-capture pointer argument, see if we can tell that it
635 // is impossible to alias the pointer we're checking. If not, we have to
636 // assume that the call could touch the pointer, even though it doesn't
638 if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
648 // While the assume intrinsic is marked as arbitrarily writing so that
649 // proper control dependencies will be maintained, it never aliases any
650 // particular memory location.
651 if (isAssumeIntrinsic(CS))
654 // The AliasAnalysis base class has some smarts, lets use them.
655 return AliasAnalysis::getModRefInfo(CS, Loc);
658 ModRefInfo BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
659 ImmutableCallSite CS2) {
660 // While the assume intrinsic is marked as arbitrarily writing so that
661 // proper control dependencies will be maintained, it never aliases any
662 // particular memory location.
663 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
666 // The AliasAnalysis base class has some smarts, lets use them.
667 return AliasAnalysis::getModRefInfo(CS1, CS2);
670 /// Provide ad-hoc rules to disambiguate accesses through two GEP operators,
671 /// both having the exact same pointer operand.
672 static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
674 const GEPOperator *GEP2,
676 const DataLayout &DL) {
678 assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
679 "Expected GEPs with the same pointer operand");
681 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
682 // such that the struct field accesses provably cannot alias.
683 // We also need at least two indices (the pointer, and the struct field).
684 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
685 GEP1->getNumIndices() < 2)
688 // If we don't know the size of the accesses through both GEPs, we can't
689 // determine whether the struct fields accessed can't alias.
690 if (V1Size == MemoryLocation::UnknownSize ||
691 V2Size == MemoryLocation::UnknownSize)
695 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
697 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
699 // If the last (struct) indices aren't constants, we can't say anything.
700 // If they're identical, the other indices might be also be dynamically
701 // equal, so the GEPs can alias.
702 if (!C1 || !C2 || C1 == C2)
705 // Find the last-indexed type of the GEP, i.e., the type you'd get if
706 // you stripped the last index.
707 // On the way, look at each indexed type. If there's something other
708 // than an array, different indices can lead to different final types.
709 SmallVector<Value *, 8> IntermediateIndices;
711 // Insert the first index; we don't need to check the type indexed
712 // through it as it only drops the pointer indirection.
713 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
714 IntermediateIndices.push_back(GEP1->getOperand(1));
716 // Insert all the remaining indices but the last one.
717 // Also, check that they all index through arrays.
718 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
719 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
720 GEP1->getSourceElementType(), IntermediateIndices)))
722 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
725 StructType *LastIndexedStruct =
726 dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
727 GEP1->getSourceElementType(), IntermediateIndices));
729 if (!LastIndexedStruct)
733 // - both GEPs begin indexing from the exact same pointer;
734 // - the last indices in both GEPs are constants, indexing into a struct;
735 // - said indices are different, hence, the pointed-to fields are different;
736 // - both GEPs only index through arrays prior to that.
738 // This lets us determine that the struct that GEP1 indexes into and the
739 // struct that GEP2 indexes into must either precisely overlap or be
740 // completely disjoint. Because they cannot partially overlap, indexing into
741 // different non-overlapping fields of the struct will never alias.
743 // Therefore, the only remaining thing needed to show that both GEPs can't
744 // alias is that the fields are not overlapping.
745 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
746 const uint64_t StructSize = SL->getSizeInBytes();
747 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
748 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
750 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
751 uint64_t V2Off, uint64_t V2Size) {
752 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
753 ((V2Off + V2Size <= StructSize) ||
754 (V2Off + V2Size - StructSize <= V1Off));
757 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
758 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
764 /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
767 /// We know that V1 is a GEP, but we don't know anything about V2.
768 /// UnderlyingV1 is GetUnderlyingObject(GEP1, DL), UnderlyingV2 is the same for
770 AliasResult BasicAliasAnalysis::aliasGEP(
771 const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
772 const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
773 const Value *UnderlyingV1, const Value *UnderlyingV2) {
774 int64_t GEP1BaseOffset;
775 bool GEP1MaxLookupReached;
776 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
778 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
779 // different functions.
780 // FIXME: This really doesn't make any sense. We get a dominator tree below
781 // that can only refer to a single function. But this function (aliasGEP) is
782 // a method on an immutable pass that can be called when there *isn't*
783 // a single function. The old pass management layer makes this "work", but
784 // this isn't really a clean solution.
785 AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
786 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
787 if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
788 AC1 = &ACT.getAssumptionCache(
789 const_cast<Function &>(*GEP1I->getParent()->getParent()));
790 if (auto *I2 = dyn_cast<Instruction>(V2))
791 AC2 = &ACT.getAssumptionCache(
792 const_cast<Function &>(*I2->getParent()->getParent()));
794 DominatorTreeWrapperPass *DTWP =
795 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
796 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
798 // If we have two gep instructions with must-alias or not-alias'ing base
799 // pointers, figure out if the indexes to the GEP tell us anything about the
801 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
802 // Do the base pointers alias?
803 AliasResult BaseAlias =
804 aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
805 UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
807 // Check for geps of non-aliasing underlying pointers where the offsets are
809 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
810 // Do the base pointers alias assuming type and size.
811 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size, V1AAInfo,
812 UnderlyingV2, V2Size, V2AAInfo);
813 if (PreciseBaseAlias == NoAlias) {
814 // See if the computed offset from the common pointer tells us about the
815 // relation of the resulting pointer.
816 int64_t GEP2BaseOffset;
817 bool GEP2MaxLookupReached;
818 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
819 const Value *GEP2BasePtr =
820 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
821 GEP2MaxLookupReached, *DL, AC2, DT);
822 const Value *GEP1BasePtr =
823 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
824 GEP1MaxLookupReached, *DL, AC1, DT);
825 // DecomposeGEPExpression and GetUnderlyingObject should return the
826 // same result except when DecomposeGEPExpression has no DataLayout.
827 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
829 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
832 // If the max search depth is reached the result is undefined
833 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
837 if (GEP1BaseOffset == GEP2BaseOffset &&
838 GEP1VariableIndices == GEP2VariableIndices)
840 GEP1VariableIndices.clear();
844 // If we get a No or May, then return it immediately, no amount of analysis
845 // will improve this situation.
846 if (BaseAlias != MustAlias)
849 // Otherwise, we have a MustAlias. Since the base pointers alias each other
850 // exactly, see if the computed offset from the common pointer tells us
851 // about the relation of the resulting pointer.
852 const Value *GEP1BasePtr =
853 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
854 GEP1MaxLookupReached, *DL, AC1, DT);
856 int64_t GEP2BaseOffset;
857 bool GEP2MaxLookupReached;
858 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
859 const Value *GEP2BasePtr =
860 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
861 GEP2MaxLookupReached, *DL, AC2, DT);
863 // DecomposeGEPExpression and GetUnderlyingObject should return the
864 // same result except when DecomposeGEPExpression has no DataLayout.
865 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
866 assert(!DL && "DecomposeGEPExpression and GetUnderlyingObject disagree!");
870 // If we know the two GEPs are based off of the exact same pointer (and not
871 // just the same underlying object), see if that tells us anything about
872 // the resulting pointers.
873 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
874 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
875 // If we couldn't find anything interesting, don't abandon just yet.
880 // If the max search depth is reached the result is undefined
881 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
884 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
885 // symbolic difference.
886 GEP1BaseOffset -= GEP2BaseOffset;
887 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
890 // Check to see if these two pointers are related by the getelementptr
891 // instruction. If one pointer is a GEP with a non-zero index of the other
892 // pointer, we know they cannot alias.
894 // If both accesses are unknown size, we can't do anything useful here.
895 if (V1Size == MemoryLocation::UnknownSize &&
896 V2Size == MemoryLocation::UnknownSize)
899 AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
900 AAMDNodes(), V2, V2Size, V2AAInfo);
902 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
903 // If V2 is known not to alias GEP base pointer, then the two values
904 // cannot alias per GEP semantics: "A pointer value formed from a
905 // getelementptr instruction is associated with the addresses associated
906 // with the first operand of the getelementptr".
909 const Value *GEP1BasePtr =
910 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
911 GEP1MaxLookupReached, *DL, AC1, DT);
913 // DecomposeGEPExpression and GetUnderlyingObject should return the
914 // same result except when DecomposeGEPExpression has no DataLayout.
915 if (GEP1BasePtr != UnderlyingV1) {
916 assert(!DL && "DecomposeGEPExpression and GetUnderlyingObject disagree!");
919 // If the max search depth is reached the result is undefined
920 if (GEP1MaxLookupReached)
924 // In the two GEP Case, if there is no difference in the offsets of the
925 // computed pointers, the resultant pointers are a must alias. This
926 // hapens when we have two lexically identical GEP's (for example).
928 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
929 // must aliases the GEP, the end result is a must alias also.
930 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
933 // If there is a constant difference between the pointers, but the difference
934 // is less than the size of the associated memory object, then we know
935 // that the objects are partially overlapping. If the difference is
936 // greater, we know they do not overlap.
937 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
938 if (GEP1BaseOffset >= 0) {
939 if (V2Size != MemoryLocation::UnknownSize) {
940 if ((uint64_t)GEP1BaseOffset < V2Size)
945 // We have the situation where:
948 // ---------------->|
949 // |-->V1Size |-------> V2Size
951 // We need to know that V2Size is not unknown, otherwise we might have
952 // stripped a gep with negative index ('gep <ptr>, -1, ...).
953 if (V1Size != MemoryLocation::UnknownSize &&
954 V2Size != MemoryLocation::UnknownSize) {
955 if (-(uint64_t)GEP1BaseOffset < V1Size)
962 if (!GEP1VariableIndices.empty()) {
964 bool AllPositive = true;
965 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
967 // Try to distinguish something like &A[i][1] against &A[42][0].
968 // Grab the least significant bit set in any of the scales. We
969 // don't need std::abs here (even if the scale's negative) as we'll
970 // be ^'ing Modulo with itself later.
971 Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
974 // If the Value could change between cycles, then any reasoning about
975 // the Value this cycle may not hold in the next cycle. We'll just
976 // give up if we can't determine conditions that hold for every cycle:
977 const Value *V = GEP1VariableIndices[i].V;
979 bool SignKnownZero, SignKnownOne;
980 ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
981 0, AC1, nullptr, DT);
983 // Zero-extension widens the variable, and so forces the sign
985 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
986 SignKnownZero |= IsZExt;
987 SignKnownOne &= !IsZExt;
989 // If the variable begins with a zero then we know it's
990 // positive, regardless of whether the value is signed or
992 int64_t Scale = GEP1VariableIndices[i].Scale;
994 (SignKnownZero && Scale >= 0) || (SignKnownOne && Scale < 0);
998 Modulo = Modulo ^ (Modulo & (Modulo - 1));
1000 // We can compute the difference between the two addresses
1001 // mod Modulo. Check whether that difference guarantees that the
1002 // two locations do not alias.
1003 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1004 if (V1Size != MemoryLocation::UnknownSize &&
1005 V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1006 V1Size <= Modulo - ModOffset)
1009 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1010 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1011 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1012 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t)GEP1BaseOffset)
1016 // Statically, we can see that the base objects are the same, but the
1017 // pointers have dynamic offsets which we can't resolve. And none of our
1018 // little tricks above worked.
1020 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1021 // practical effect of this is protecting TBAA in the case of dynamic
1022 // indices into arrays of unions or malloc'd memory.
1023 return PartialAlias;
1026 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1027 // If the results agree, take it.
1030 // A mix of PartialAlias and MustAlias is PartialAlias.
1031 if ((A == PartialAlias && B == MustAlias) ||
1032 (B == PartialAlias && A == MustAlias))
1033 return PartialAlias;
1034 // Otherwise, we don't know anything.
1038 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1039 /// against another.
1040 AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
1042 const AAMDNodes &SIAAInfo,
1043 const Value *V2, uint64_t V2Size,
1044 const AAMDNodes &V2AAInfo) {
1045 // If the values are Selects with the same condition, we can do a more precise
1046 // check: just check for aliases between the values on corresponding arms.
1047 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1048 if (SI->getCondition() == SI2->getCondition()) {
1049 AliasResult Alias = aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1050 SI2->getTrueValue(), V2Size, V2AAInfo);
1051 if (Alias == MayAlias)
1053 AliasResult ThisAlias =
1054 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1055 SI2->getFalseValue(), V2Size, V2AAInfo);
1056 return MergeAliasResults(ThisAlias, Alias);
1059 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1060 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1062 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
1063 if (Alias == MayAlias)
1066 AliasResult ThisAlias =
1067 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
1068 return MergeAliasResults(ThisAlias, Alias);
1071 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1073 AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1074 const AAMDNodes &PNAAInfo,
1075 const Value *V2, uint64_t V2Size,
1076 const AAMDNodes &V2AAInfo) {
1077 // Track phi nodes we have visited. We use this information when we determine
1078 // value equivalence.
1079 VisitedPhiBBs.insert(PN->getParent());
1081 // If the values are PHIs in the same block, we can do a more precise
1082 // as well as efficient check: just check for aliases between the values
1083 // on corresponding edges.
1084 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1085 if (PN2->getParent() == PN->getParent()) {
1086 LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1087 MemoryLocation(V2, V2Size, V2AAInfo));
1089 std::swap(Locs.first, Locs.second);
1090 // Analyse the PHIs' inputs under the assumption that the PHIs are
1092 // If the PHIs are May/MustAlias there must be (recursively) an input
1093 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1094 // there must be an operation on the PHIs within the PHIs' value cycle
1095 // that causes a MayAlias.
1096 // Pretend the phis do not alias.
1097 AliasResult Alias = NoAlias;
1098 assert(AliasCache.count(Locs) &&
1099 "There must exist an entry for the phi node");
1100 AliasResult OrigAliasResult = AliasCache[Locs];
1101 AliasCache[Locs] = NoAlias;
1103 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1104 AliasResult ThisAlias =
1105 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1106 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1108 Alias = MergeAliasResults(ThisAlias, Alias);
1109 if (Alias == MayAlias)
1113 // Reset if speculation failed.
1114 if (Alias != NoAlias)
1115 AliasCache[Locs] = OrigAliasResult;
1120 SmallPtrSet<Value *, 4> UniqueSrc;
1121 SmallVector<Value *, 4> V1Srcs;
1122 bool isRecursive = false;
1123 for (Value *PV1 : PN->incoming_values()) {
1124 if (isa<PHINode>(PV1))
1125 // If any of the source itself is a PHI, return MayAlias conservatively
1126 // to avoid compile time explosion. The worst possible case is if both
1127 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1128 // and 'n' are the number of PHI sources.
1131 if (EnableRecPhiAnalysis)
1132 if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
1133 // Check whether the incoming value is a GEP that advances the pointer
1134 // result of this PHI node (e.g. in a loop). If this is the case, we
1135 // would recurse and always get a MayAlias. Handle this case specially
1137 if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
1138 isa<ConstantInt>(PV1GEP->idx_begin())) {
1144 if (UniqueSrc.insert(PV1).second)
1145 V1Srcs.push_back(PV1);
1148 // If this PHI node is recursive, set the size of the accessed memory to
1149 // unknown to represent all the possible values the GEP could advance the
1152 PNSize = MemoryLocation::UnknownSize;
1155 aliasCheck(V2, V2Size, V2AAInfo, V1Srcs[0], PNSize, PNAAInfo);
1157 // Early exit if the check of the first PHI source against V2 is MayAlias.
1158 // Other results are not possible.
1159 if (Alias == MayAlias)
1162 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1163 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1164 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1165 Value *V = V1Srcs[i];
1167 AliasResult ThisAlias =
1168 aliasCheck(V2, V2Size, V2AAInfo, V, PNSize, PNAAInfo);
1169 Alias = MergeAliasResults(ThisAlias, Alias);
1170 if (Alias == MayAlias)
1177 /// Provideis a bunch of ad-hoc rules to disambiguate in common cases, such as
1178 /// array references.
1179 AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1180 AAMDNodes V1AAInfo, const Value *V2,
1182 AAMDNodes V2AAInfo) {
1183 // If either of the memory references is empty, it doesn't matter what the
1184 // pointer values are.
1185 if (V1Size == 0 || V2Size == 0)
1188 // Strip off any casts if they exist.
1189 V1 = V1->stripPointerCasts();
1190 V2 = V2->stripPointerCasts();
1192 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1193 // value for undef that aliases nothing in the program.
1194 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1197 // Are we checking for alias of the same value?
1198 // Because we look 'through' phi nodes we could look at "Value" pointers from
1199 // different iterations. We must therefore make sure that this is not the
1200 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1201 // happen by looking at the visited phi nodes and making sure they cannot
1203 if (isValueEqualInPotentialCycles(V1, V2))
1206 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1207 return NoAlias; // Scalars cannot alias each other
1209 // Figure out what objects these things are pointing to if we can.
1210 const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
1211 const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
1213 // Null values in the default address space don't point to any object, so they
1214 // don't alias any other pointer.
1215 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1216 if (CPN->getType()->getAddressSpace() == 0)
1218 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1219 if (CPN->getType()->getAddressSpace() == 0)
1223 // If V1/V2 point to two different objects we know that we have no alias.
1224 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1227 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1228 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1229 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1232 // Function arguments can't alias with things that are known to be
1233 // unambigously identified at the function level.
1234 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1235 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1238 // Most objects can't alias null.
1239 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1240 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1243 // If one pointer is the result of a call/invoke or load and the other is a
1244 // non-escaping local object within the same function, then we know the
1245 // object couldn't escape to a point where the call could return it.
1247 // Note that if the pointers are in different functions, there are a
1248 // variety of complications. A call with a nocapture argument may still
1249 // temporary store the nocapture argument's value in a temporary memory
1250 // location if that memory location doesn't escape. Or it may pass a
1251 // nocapture value to other functions as long as they don't capture it.
1252 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1254 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1258 // If the size of one access is larger than the entire object on the other
1259 // side, then we know such behavior is undefined and can assume no alias.
1261 if ((V1Size != MemoryLocation::UnknownSize &&
1262 isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1263 (V2Size != MemoryLocation::UnknownSize &&
1264 isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1267 // Check the cache before climbing up use-def chains. This also terminates
1268 // otherwise infinitely recursive queries.
1269 LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1270 MemoryLocation(V2, V2Size, V2AAInfo));
1272 std::swap(Locs.first, Locs.second);
1273 std::pair<AliasCacheTy::iterator, bool> Pair =
1274 AliasCache.insert(std::make_pair(Locs, MayAlias));
1276 return Pair.first->second;
1278 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1279 // GEP can't simplify, we don't even look at the PHI cases.
1280 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1282 std::swap(V1Size, V2Size);
1284 std::swap(V1AAInfo, V2AAInfo);
1286 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1287 AliasResult Result =
1288 aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
1289 if (Result != MayAlias)
1290 return AliasCache[Locs] = Result;
1293 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1295 std::swap(V1Size, V2Size);
1296 std::swap(V1AAInfo, V2AAInfo);
1298 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1299 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo, V2, V2Size, V2AAInfo);
1300 if (Result != MayAlias)
1301 return AliasCache[Locs] = Result;
1304 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1306 std::swap(V1Size, V2Size);
1307 std::swap(V1AAInfo, V2AAInfo);
1309 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1310 AliasResult Result =
1311 aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo);
1312 if (Result != MayAlias)
1313 return AliasCache[Locs] = Result;
1316 // If both pointers are pointing into the same object and one of them
1317 // accesses is accessing the entire object, then the accesses must
1318 // overlap in some way.
1320 if ((V1Size != MemoryLocation::UnknownSize &&
1321 isObjectSize(O1, V1Size, *DL, *TLI)) ||
1322 (V2Size != MemoryLocation::UnknownSize &&
1323 isObjectSize(O2, V2Size, *DL, *TLI)))
1324 return AliasCache[Locs] = PartialAlias;
1326 AliasResult Result =
1327 AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
1328 MemoryLocation(V2, V2Size, V2AAInfo));
1329 return AliasCache[Locs] = Result;
1332 /// Check whether two Values can be considered equivalent.
1334 /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
1335 /// they can not be part of a cycle in the value graph by looking at all
1336 /// visited phi nodes an making sure that the phis cannot reach the value. We
1337 /// have to do this because we are looking through phi nodes (That is we say
1338 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1339 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1344 const Instruction *Inst = dyn_cast<Instruction>(V);
1348 if (VisitedPhiBBs.empty())
1351 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1354 // Use dominance or loop info if available.
1355 DominatorTreeWrapperPass *DTWP =
1356 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1357 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1358 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1359 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
1361 // Make sure that the visited phis cannot reach the Value. This ensures that
1362 // the Values cannot come from different iterations of a potential cycle the
1363 // phi nodes could be involved in.
1364 for (auto *P : VisitedPhiBBs)
1365 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
1371 /// Computes the symbolic difference between two de-composed GEPs.
1373 /// Dest and Src are the variable indices from two decomposed GetElementPtr
1374 /// instructions GEP1 and GEP2 which have common base pointers.
1375 void BasicAliasAnalysis::GetIndexDifference(
1376 SmallVectorImpl<VariableGEPIndex> &Dest,
1377 const SmallVectorImpl<VariableGEPIndex> &Src) {
1381 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1382 const Value *V = Src[i].V;
1383 ExtensionKind Extension = Src[i].Extension;
1384 int64_t Scale = Src[i].Scale;
1386 // Find V in Dest. This is N^2, but pointer indices almost never have more
1387 // than a few variable indexes.
1388 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1389 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1390 Dest[j].Extension != Extension)
1393 // If we found it, subtract off Scale V's from the entry in Dest. If it
1394 // goes to zero, remove the entry.
1395 if (Dest[j].Scale != Scale)
1396 Dest[j].Scale -= Scale;
1398 Dest.erase(Dest.begin() + j);
1403 // If we didn't consume this entry, add it to the end of the Dest list.
1405 VariableGEPIndex Entry = {V, Extension, -Scale};
1406 Dest.push_back(Entry);