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/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/Function.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
44 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
45 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
46 /// careful with value equivalence. We use reachability to make sure a value
47 /// cannot be involved in a cycle.
48 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
50 // The max limit of the search depth in DecomposeGEPExpression() and
51 // GetUnderlyingObject(), both functions need to use the same search
52 // depth otherwise the algorithm in aliasGEP will assert.
53 static const unsigned MaxLookupSearchDepth = 6;
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
60 /// object that never escapes from the function.
61 static bool isNonEscapingLocalObject(const Value *V) {
62 // If this is a local allocation, check to see if it escapes.
63 if (isa<AllocaInst>(V) || isNoAliasCall(V))
64 // Set StoreCaptures to True so that we can assume in our callers that the
65 // pointer is not the result of a load instruction. Currently
66 // PointerMayBeCaptured doesn't have any special analysis for the
67 // StoreCaptures=false case; if it did, our callers could be refined to be
69 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
71 // If this is an argument that corresponds to a byval or noalias argument,
72 // then it has not escaped before entering the function. Check if it escapes
73 // inside the function.
74 if (const Argument *A = dyn_cast<Argument>(V))
75 if (A->hasByValAttr() || A->hasNoAliasAttr())
76 // Note even if the argument is marked nocapture we still need to check
77 // for copies made inside the function. The nocapture attribute only
78 // specifies that there are no copies made that outlive the function.
79 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
84 /// isEscapeSource - Return true if the pointer is one which would have
85 /// been considered an escape by isNonEscapingLocalObject.
86 static bool isEscapeSource(const Value *V) {
87 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
90 // The load case works because isNonEscapingLocalObject considers all
91 // stores to be escapes (it passes true for the StoreCaptures argument
92 // to PointerMayBeCaptured).
99 /// getObjectSize - Return the size of the object specified by V, or
100 /// UnknownSize if unknown.
101 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
102 const TargetLibraryInfo &TLI,
103 bool RoundToAlign = false) {
105 if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign))
107 return AliasAnalysis::UnknownSize;
110 /// isObjectSmallerThan - Return true if we can prove that the object specified
111 /// by V is smaller than Size.
112 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
113 const DataLayout &DL,
114 const TargetLibraryInfo &TLI) {
115 // Note that the meanings of the "object" are slightly different in the
116 // following contexts:
117 // c1: llvm::getObjectSize()
118 // c2: llvm.objectsize() intrinsic
119 // c3: isObjectSmallerThan()
120 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
121 // refers to the "entire object".
123 // Consider this example:
124 // char *p = (char*)malloc(100)
127 // In the context of c1 and c2, the "object" pointed by q refers to the
128 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
130 // However, in the context of c3, the "object" refers to the chunk of memory
131 // being allocated. So, the "object" has 100 bytes, and q points to the middle
132 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
133 // parameter, before the llvm::getObjectSize() is called to get the size of
134 // entire object, we should:
135 // - either rewind the pointer q to the base-address of the object in
136 // question (in this case rewind to p), or
137 // - just give up. It is up to caller to make sure the pointer is pointing
138 // to the base address the object.
140 // We go for 2nd option for simplicity.
141 if (!isIdentifiedObject(V))
144 // This function needs to use the aligned object size because we allow
145 // reads a bit past the end given sufficient alignment.
146 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
148 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
151 /// isObjectSize - Return true if we can prove that the object specified
152 /// by V has size Size.
153 static bool isObjectSize(const Value *V, uint64_t Size,
154 const DataLayout &DL, const TargetLibraryInfo &TLI) {
155 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
156 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
159 /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
160 /// at the function-level. Different IdentifiedFunctionLocals can't alias.
161 /// Further, an IdentifiedFunctionLocal can not alias with any function
162 /// arguments other than itself, which is not necessarily true for
163 /// IdentifiedObjects.
164 static bool isIdentifiedFunctionLocal(const Value *V)
166 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
170 //===----------------------------------------------------------------------===//
171 // GetElementPtr Instruction Decomposition and Analysis
172 //===----------------------------------------------------------------------===//
181 struct VariableGEPIndex {
183 ExtensionKind Extension;
186 bool operator==(const VariableGEPIndex &Other) const {
187 return V == Other.V && Extension == Other.Extension &&
188 Scale == Other.Scale;
191 bool operator!=(const VariableGEPIndex &Other) const {
192 return !operator==(Other);
198 /// GetLinearExpression - Analyze the specified value as a linear expression:
199 /// "A*V + B", where A and B are constant integers. Return the scale and offset
200 /// values as APInts and return V as a Value*, and return whether we looked
201 /// through any sign or zero extends. The incoming Value is known to have
202 /// IntegerType and it may already be sign or zero extended.
204 /// Note that this looks through extends, so the high bits may not be
205 /// represented in the result.
206 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
207 ExtensionKind &Extension,
208 const DataLayout &DL, unsigned Depth) {
209 assert(V->getType()->isIntegerTy() && "Not an integer value");
211 // Limit our recursion depth.
218 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
219 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
220 switch (BOp->getOpcode()) {
222 case Instruction::Or:
223 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
225 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL))
228 case Instruction::Add:
229 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
231 Offset += RHSC->getValue();
233 case Instruction::Mul:
234 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
236 Offset *= RHSC->getValue();
237 Scale *= RHSC->getValue();
239 case Instruction::Shl:
240 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
242 Offset <<= RHSC->getValue().getLimitedValue();
243 Scale <<= RHSC->getValue().getLimitedValue();
249 // Since GEP indices are sign extended anyway, we don't care about the high
250 // bits of a sign or zero extended value - just scales and offsets. The
251 // extensions have to be consistent though.
252 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
253 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
254 Value *CastOp = cast<CastInst>(V)->getOperand(0);
255 unsigned OldWidth = Scale.getBitWidth();
256 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
257 Scale = Scale.trunc(SmallWidth);
258 Offset = Offset.trunc(SmallWidth);
259 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
261 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
263 Scale = Scale.zext(OldWidth);
264 Offset = Offset.zext(OldWidth);
274 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
275 /// into a base pointer with a constant offset and a number of scaled symbolic
278 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
279 /// the VarIndices vector) are Value*'s that are known to be scaled by the
280 /// specified amount, but which may have other unrepresented high bits. As such,
281 /// the gep cannot necessarily be reconstructed from its decomposed form.
283 /// When DataLayout is around, this function is capable of analyzing everything
284 /// that GetUnderlyingObject can look through. To be able to do that
285 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
286 /// depth (MaxLookupSearchDepth).
287 /// When DataLayout not is around, it just looks through pointer casts.
290 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
291 SmallVectorImpl<VariableGEPIndex> &VarIndices,
292 bool &MaxLookupReached, const DataLayout *DL) {
293 // Limit recursion depth to limit compile time in crazy cases.
294 unsigned MaxLookup = MaxLookupSearchDepth;
295 MaxLookupReached = false;
299 // See if this is a bitcast or GEP.
300 const Operator *Op = dyn_cast<Operator>(V);
302 // The only non-operator case we can handle are GlobalAliases.
303 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
304 if (!GA->mayBeOverridden()) {
305 V = GA->getAliasee();
312 if (Op->getOpcode() == Instruction::BitCast) {
313 V = Op->getOperand(0);
317 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
319 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
320 // can come up with something. This matches what GetUnderlyingObject does.
321 if (const Instruction *I = dyn_cast<Instruction>(V))
322 // TODO: Get a DominatorTree and use it here.
323 if (const Value *Simplified =
324 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
332 // Don't attempt to analyze GEPs over unsized objects.
333 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
336 // If we are lacking DataLayout information, we can't compute the offets of
337 // elements computed by GEPs. However, we can handle bitcast equivalent
340 if (!GEPOp->hasAllZeroIndices())
342 V = GEPOp->getOperand(0);
346 unsigned AS = GEPOp->getPointerAddressSpace();
347 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
348 gep_type_iterator GTI = gep_type_begin(GEPOp);
349 for (User::const_op_iterator I = GEPOp->op_begin()+1,
350 E = GEPOp->op_end(); I != E; ++I) {
352 // Compute the (potentially symbolic) offset in bytes for this index.
353 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
354 // For a struct, add the member offset.
355 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
356 if (FieldNo == 0) continue;
358 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
362 // For an array/pointer, add the element offset, explicitly scaled.
363 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
364 if (CIdx->isZero()) continue;
365 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
369 uint64_t Scale = DL->getTypeAllocSize(*GTI);
370 ExtensionKind Extension = EK_NotExtended;
372 // If the integer type is smaller than the pointer size, it is implicitly
373 // sign extended to pointer size.
374 unsigned Width = Index->getType()->getIntegerBitWidth();
375 if (DL->getPointerSizeInBits(AS) > Width)
376 Extension = EK_SignExt;
378 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
379 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
380 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
383 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
384 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
385 BaseOffs += IndexOffset.getSExtValue()*Scale;
386 Scale *= IndexScale.getSExtValue();
388 // If we already had an occurrence of this index variable, merge this
389 // scale into it. For example, we want to handle:
390 // A[x][x] -> x*16 + x*4 -> x*20
391 // This also ensures that 'x' only appears in the index list once.
392 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
393 if (VarIndices[i].V == Index &&
394 VarIndices[i].Extension == Extension) {
395 Scale += VarIndices[i].Scale;
396 VarIndices.erase(VarIndices.begin()+i);
401 // Make sure that we have a scale that makes sense for this target's
403 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
405 Scale = (int64_t)Scale >> ShiftBits;
409 VariableGEPIndex Entry = {Index, Extension,
410 static_cast<int64_t>(Scale)};
411 VarIndices.push_back(Entry);
415 // Analyze the base pointer next.
416 V = GEPOp->getOperand(0);
417 } while (--MaxLookup);
419 // If the chain of expressions is too deep, just return early.
420 MaxLookupReached = true;
424 //===----------------------------------------------------------------------===//
425 // BasicAliasAnalysis Pass
426 //===----------------------------------------------------------------------===//
429 static const Function *getParent(const Value *V) {
430 if (const Instruction *inst = dyn_cast<Instruction>(V))
431 return inst->getParent()->getParent();
433 if (const Argument *arg = dyn_cast<Argument>(V))
434 return arg->getParent();
439 static bool notDifferentParent(const Value *O1, const Value *O2) {
441 const Function *F1 = getParent(O1);
442 const Function *F2 = getParent(O2);
444 return !F1 || !F2 || F1 == F2;
449 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
450 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
451 static char ID; // Class identification, replacement for typeinfo
452 BasicAliasAnalysis() : ImmutablePass(ID) {
453 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
456 void initializePass() override {
457 InitializeAliasAnalysis(this);
460 void getAnalysisUsage(AnalysisUsage &AU) const override {
461 AU.addRequired<AliasAnalysis>();
462 AU.addRequired<TargetLibraryInfo>();
465 AliasResult alias(const Location &LocA, const Location &LocB) override {
466 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
467 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
468 "BasicAliasAnalysis doesn't support interprocedural queries.");
469 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.TBAATag,
470 LocB.Ptr, LocB.Size, LocB.TBAATag);
471 // AliasCache rarely has more than 1 or 2 elements, always use
472 // shrink_and_clear so it quickly returns to the inline capacity of the
473 // SmallDenseMap if it ever grows larger.
474 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
475 AliasCache.shrink_and_clear();
476 VisitedPhiBBs.clear();
480 ModRefResult getModRefInfo(ImmutableCallSite CS,
481 const Location &Loc) override;
483 ModRefResult getModRefInfo(ImmutableCallSite CS1,
484 ImmutableCallSite CS2) override {
485 // The AliasAnalysis base class has some smarts, lets use them.
486 return AliasAnalysis::getModRefInfo(CS1, CS2);
489 /// pointsToConstantMemory - Chase pointers until we find a (constant
491 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
493 /// Get the location associated with a pointer argument of a callsite.
494 Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
495 ModRefResult &Mask) override;
497 /// getModRefBehavior - Return the behavior when calling the given
499 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
501 /// getModRefBehavior - Return the behavior when calling the given function.
502 /// For use when the call site is not known.
503 ModRefBehavior getModRefBehavior(const Function *F) override;
505 /// getAdjustedAnalysisPointer - This method is used when a pass implements
506 /// an analysis interface through multiple inheritance. If needed, it
507 /// should override this to adjust the this pointer as needed for the
508 /// specified pass info.
509 void *getAdjustedAnalysisPointer(const void *ID) override {
510 if (ID == &AliasAnalysis::ID)
511 return (AliasAnalysis*)this;
516 // AliasCache - Track alias queries to guard against recursion.
517 typedef std::pair<Location, Location> LocPair;
518 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
519 AliasCacheTy AliasCache;
521 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
522 /// equality as value equality we need to make sure that the "Value" is not
523 /// part of a cycle. Otherwise, two uses could come from different
524 /// "iterations" of a cycle and see different values for the same "Value"
526 /// The following example shows the problem:
527 /// %p = phi(%alloca1, %addr2)
529 /// %addr1 = gep, %alloca2, 0, %l
530 /// %addr2 = gep %alloca2, 0, (%l + 1)
531 /// alias(%p, %addr1) -> MayAlias !
533 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
535 // Visited - Track instructions visited by pointsToConstantMemory.
536 SmallPtrSet<const Value*, 16> Visited;
538 /// \brief Check whether two Values can be considered equivalent.
540 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
541 /// whether they can not be part of a cycle in the value graph by looking at
542 /// all visited phi nodes an making sure that the phis cannot reach the
543 /// value. We have to do this because we are looking through phi nodes (That
544 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
545 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
547 /// \brief Dest and Src are the variable indices from two decomposed
548 /// GetElementPtr instructions GEP1 and GEP2 which have common base
549 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
550 /// difference between the two pointers.
551 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
552 const SmallVectorImpl<VariableGEPIndex> &Src);
554 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
555 // instruction against another.
556 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
557 const MDNode *V1TBAAInfo,
558 const Value *V2, uint64_t V2Size,
559 const MDNode *V2TBAAInfo,
560 const Value *UnderlyingV1, const Value *UnderlyingV2);
562 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
563 // instruction against another.
564 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
565 const MDNode *PNTBAAInfo,
566 const Value *V2, uint64_t V2Size,
567 const MDNode *V2TBAAInfo);
569 /// aliasSelect - Disambiguate a Select instruction against another value.
570 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
571 const MDNode *SITBAAInfo,
572 const Value *V2, uint64_t V2Size,
573 const MDNode *V2TBAAInfo);
575 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
576 const MDNode *V1TBAATag,
577 const Value *V2, uint64_t V2Size,
578 const MDNode *V2TBAATag);
580 } // End of anonymous namespace
582 // Register this pass...
583 char BasicAliasAnalysis::ID = 0;
584 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
585 "Basic Alias Analysis (stateless AA impl)",
587 INITIALIZE_PASS_DEPENDENCY(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 /// getModRefInfo - Check to see if the specified callsite can clobber the
802 /// specified memory object. Since we only look at local properties of this
803 /// function, we really can't say much about this query. We do, however, use
804 /// simple "address taken" analysis on local objects.
805 AliasAnalysis::ModRefResult
806 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
807 const Location &Loc) {
808 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
809 "AliasAnalysis query involving multiple functions!");
811 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
813 // If this is a tail call and Loc.Ptr points to a stack location, we know that
814 // the tail call cannot access or modify the local stack.
815 // We cannot exclude byval arguments here; these belong to the caller of
816 // the current function not to the current function, and a tail callee
817 // may reference them.
818 if (isa<AllocaInst>(Object))
819 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
820 if (CI->isTailCall())
823 // If the pointer is to a locally allocated object that does not escape,
824 // then the call can not mod/ref the pointer unless the call takes the pointer
825 // as an argument, and itself doesn't capture it.
826 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
827 isNonEscapingLocalObject(Object)) {
828 bool PassedAsArg = false;
830 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
831 CI != CE; ++CI, ++ArgNo) {
832 // Only look at the no-capture or byval pointer arguments. If this
833 // pointer were passed to arguments that were neither of these, then it
834 // couldn't be no-capture.
835 if (!(*CI)->getType()->isPointerTy() ||
836 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
839 // If this is a no-capture pointer argument, see if we can tell that it
840 // is impossible to alias the pointer we're checking. If not, we have to
841 // assume that the call could touch the pointer, even though it doesn't
843 if (!isNoAlias(Location(*CI), Location(Object))) {
853 // The AliasAnalysis base class has some smarts, lets use them.
854 return AliasAnalysis::getModRefInfo(CS, Loc);
857 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
858 /// against another pointer. We know that V1 is a GEP, but we don't know
859 /// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
860 /// UnderlyingV2 is the same for V2.
862 AliasAnalysis::AliasResult
863 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
864 const MDNode *V1TBAAInfo,
865 const Value *V2, uint64_t V2Size,
866 const MDNode *V2TBAAInfo,
867 const Value *UnderlyingV1,
868 const Value *UnderlyingV2) {
869 int64_t GEP1BaseOffset;
870 bool GEP1MaxLookupReached;
871 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
873 // If we have two gep instructions with must-alias or not-alias'ing base
874 // pointers, figure out if the indexes to the GEP tell us anything about the
876 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
877 // Do the base pointers alias?
878 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
879 UnderlyingV2, UnknownSize, nullptr);
881 // Check for geps of non-aliasing underlying pointers where the offsets are
883 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
884 // Do the base pointers alias assuming type and size.
885 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
886 V1TBAAInfo, UnderlyingV2,
888 if (PreciseBaseAlias == NoAlias) {
889 // See if the computed offset from the common pointer tells us about the
890 // relation of the resulting pointer.
891 int64_t GEP2BaseOffset;
892 bool GEP2MaxLookupReached;
893 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
894 const Value *GEP2BasePtr =
895 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
896 GEP2MaxLookupReached, DL);
897 const Value *GEP1BasePtr =
898 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
899 GEP1MaxLookupReached, DL);
900 // DecomposeGEPExpression and GetUnderlyingObject should return the
901 // same result except when DecomposeGEPExpression has no DataLayout.
902 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
904 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
907 // If the max search depth is reached the result is undefined
908 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
912 if (GEP1BaseOffset == GEP2BaseOffset &&
913 GEP1VariableIndices == GEP2VariableIndices)
915 GEP1VariableIndices.clear();
919 // If we get a No or May, then return it immediately, no amount of analysis
920 // will improve this situation.
921 if (BaseAlias != MustAlias) return BaseAlias;
923 // Otherwise, we have a MustAlias. Since the base pointers alias each other
924 // exactly, see if the computed offset from the common pointer tells us
925 // about the relation of the resulting pointer.
926 const Value *GEP1BasePtr =
927 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
928 GEP1MaxLookupReached, DL);
930 int64_t GEP2BaseOffset;
931 bool GEP2MaxLookupReached;
932 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
933 const Value *GEP2BasePtr =
934 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
935 GEP2MaxLookupReached, DL);
937 // DecomposeGEPExpression and GetUnderlyingObject should return the
938 // same result except when DecomposeGEPExpression has no DataLayout.
939 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
941 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
944 // If the max search depth is reached the result is undefined
945 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
948 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
949 // symbolic difference.
950 GEP1BaseOffset -= GEP2BaseOffset;
951 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
954 // Check to see if these two pointers are related by the getelementptr
955 // instruction. If one pointer is a GEP with a non-zero index of the other
956 // pointer, we know they cannot alias.
958 // If both accesses are unknown size, we can't do anything useful here.
959 if (V1Size == UnknownSize && V2Size == UnknownSize)
962 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
963 V2, V2Size, V2TBAAInfo);
965 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
966 // If V2 is known not to alias GEP base pointer, then the two values
967 // cannot alias per GEP semantics: "A pointer value formed from a
968 // getelementptr instruction is associated with the addresses associated
969 // with the first operand of the getelementptr".
972 const Value *GEP1BasePtr =
973 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
974 GEP1MaxLookupReached, DL);
976 // DecomposeGEPExpression and GetUnderlyingObject should return the
977 // same result except when DecomposeGEPExpression has no DataLayout.
978 if (GEP1BasePtr != UnderlyingV1) {
980 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
983 // If the max search depth is reached the result is undefined
984 if (GEP1MaxLookupReached)
988 // In the two GEP Case, if there is no difference in the offsets of the
989 // computed pointers, the resultant pointers are a must alias. This
990 // hapens when we have two lexically identical GEP's (for example).
992 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
993 // must aliases the GEP, the end result is a must alias also.
994 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
997 // If there is a constant difference between the pointers, but the difference
998 // is less than the size of the associated memory object, then we know
999 // that the objects are partially overlapping. If the difference is
1000 // greater, we know they do not overlap.
1001 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
1002 if (GEP1BaseOffset >= 0) {
1003 if (V2Size != UnknownSize) {
1004 if ((uint64_t)GEP1BaseOffset < V2Size)
1005 return PartialAlias;
1009 // We have the situation where:
1012 // ---------------->|
1013 // |-->V1Size |-------> V2Size
1015 // We need to know that V2Size is not unknown, otherwise we might have
1016 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1017 if (V1Size != UnknownSize && V2Size != UnknownSize) {
1018 if (-(uint64_t)GEP1BaseOffset < V1Size)
1019 return PartialAlias;
1025 // Try to distinguish something like &A[i][1] against &A[42][0].
1026 // Grab the least significant bit set in any of the scales.
1027 if (!GEP1VariableIndices.empty()) {
1028 uint64_t Modulo = 0;
1029 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i)
1030 Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
1031 Modulo = Modulo ^ (Modulo & (Modulo - 1));
1033 // We can compute the difference between the two addresses
1034 // mod Modulo. Check whether that difference guarantees that the
1035 // two locations do not alias.
1036 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1037 if (V1Size != UnknownSize && V2Size != UnknownSize &&
1038 ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1042 // Statically, we can see that the base objects are the same, but the
1043 // pointers have dynamic offsets which we can't resolve. And none of our
1044 // little tricks above worked.
1046 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1047 // practical effect of this is protecting TBAA in the case of dynamic
1048 // indices into arrays of unions or malloc'd memory.
1049 return PartialAlias;
1052 static AliasAnalysis::AliasResult
1053 MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1054 // If the results agree, take it.
1057 // A mix of PartialAlias and MustAlias is PartialAlias.
1058 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1059 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1060 return AliasAnalysis::PartialAlias;
1061 // Otherwise, we don't know anything.
1062 return AliasAnalysis::MayAlias;
1065 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1066 /// instruction against another.
1067 AliasAnalysis::AliasResult
1068 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
1069 const MDNode *SITBAAInfo,
1070 const Value *V2, uint64_t V2Size,
1071 const MDNode *V2TBAAInfo) {
1072 // If the values are Selects with the same condition, we can do a more precise
1073 // check: just check for aliases between the values on corresponding arms.
1074 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1075 if (SI->getCondition() == SI2->getCondition()) {
1077 aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
1078 SI2->getTrueValue(), V2Size, V2TBAAInfo);
1079 if (Alias == MayAlias)
1081 AliasResult ThisAlias =
1082 aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
1083 SI2->getFalseValue(), V2Size, V2TBAAInfo);
1084 return MergeAliasResults(ThisAlias, Alias);
1087 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1088 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1090 aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
1091 if (Alias == MayAlias)
1094 AliasResult ThisAlias =
1095 aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
1096 return MergeAliasResults(ThisAlias, Alias);
1099 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
1101 AliasAnalysis::AliasResult
1102 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1103 const MDNode *PNTBAAInfo,
1104 const Value *V2, uint64_t V2Size,
1105 const MDNode *V2TBAAInfo) {
1106 // Track phi nodes we have visited. We use this information when we determine
1107 // value equivalence.
1108 VisitedPhiBBs.insert(PN->getParent());
1110 // If the values are PHIs in the same block, we can do a more precise
1111 // as well as efficient check: just check for aliases between the values
1112 // on corresponding edges.
1113 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1114 if (PN2->getParent() == PN->getParent()) {
1115 LocPair Locs(Location(PN, PNSize, PNTBAAInfo),
1116 Location(V2, V2Size, V2TBAAInfo));
1118 std::swap(Locs.first, Locs.second);
1119 // Analyse the PHIs' inputs under the assumption that the PHIs are
1121 // If the PHIs are May/MustAlias there must be (recursively) an input
1122 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1123 // there must be an operation on the PHIs within the PHIs' value cycle
1124 // that causes a MayAlias.
1125 // Pretend the phis do not alias.
1126 AliasResult Alias = NoAlias;
1127 assert(AliasCache.count(Locs) &&
1128 "There must exist an entry for the phi node");
1129 AliasResult OrigAliasResult = AliasCache[Locs];
1130 AliasCache[Locs] = NoAlias;
1132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1133 AliasResult ThisAlias =
1134 aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
1135 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1136 V2Size, V2TBAAInfo);
1137 Alias = MergeAliasResults(ThisAlias, Alias);
1138 if (Alias == MayAlias)
1142 // Reset if speculation failed.
1143 if (Alias != NoAlias)
1144 AliasCache[Locs] = OrigAliasResult;
1149 SmallPtrSet<Value*, 4> UniqueSrc;
1150 SmallVector<Value*, 4> V1Srcs;
1151 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1152 Value *PV1 = PN->getIncomingValue(i);
1153 if (isa<PHINode>(PV1))
1154 // If any of the source itself is a PHI, return MayAlias conservatively
1155 // to avoid compile time explosion. The worst possible case is if both
1156 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1157 // and 'n' are the number of PHI sources.
1159 if (UniqueSrc.insert(PV1))
1160 V1Srcs.push_back(PV1);
1163 AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
1164 V1Srcs[0], PNSize, PNTBAAInfo);
1165 // Early exit if the check of the first PHI source against V2 is MayAlias.
1166 // Other results are not possible.
1167 if (Alias == MayAlias)
1170 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1171 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1172 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1173 Value *V = V1Srcs[i];
1175 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
1176 V, PNSize, PNTBAAInfo);
1177 Alias = MergeAliasResults(ThisAlias, Alias);
1178 if (Alias == MayAlias)
1185 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1186 // such as array references.
1188 AliasAnalysis::AliasResult
1189 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1190 const MDNode *V1TBAAInfo,
1191 const Value *V2, uint64_t V2Size,
1192 const MDNode *V2TBAAInfo) {
1193 // If either of the memory references is empty, it doesn't matter what the
1194 // pointer values are.
1195 if (V1Size == 0 || V2Size == 0)
1198 // Strip off any casts if they exist.
1199 V1 = V1->stripPointerCasts();
1200 V2 = V2->stripPointerCasts();
1202 // Are we checking for alias of the same value?
1203 // Because we look 'through' phi nodes we could look at "Value" pointers from
1204 // different iterations. We must therefore make sure that this is not the
1205 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1206 // happen by looking at the visited phi nodes and making sure they cannot
1208 if (isValueEqualInPotentialCycles(V1, V2))
1211 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1212 return NoAlias; // Scalars cannot alias each other
1214 // Figure out what objects these things are pointing to if we can.
1215 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1216 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
1218 // Null values in the default address space don't point to any object, so they
1219 // don't alias any other pointer.
1220 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1221 if (CPN->getType()->getAddressSpace() == 0)
1223 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1224 if (CPN->getType()->getAddressSpace() == 0)
1228 // If V1/V2 point to two different objects we know that we have no alias.
1229 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1232 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1233 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1234 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1237 // Function arguments can't alias with things that are known to be
1238 // unambigously identified at the function level.
1239 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1240 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1243 // Most objects can't alias null.
1244 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1245 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1248 // If one pointer is the result of a call/invoke or load and the other is a
1249 // non-escaping local object within the same function, then we know the
1250 // object couldn't escape to a point where the call could return it.
1252 // Note that if the pointers are in different functions, there are a
1253 // variety of complications. A call with a nocapture argument may still
1254 // temporary store the nocapture argument's value in a temporary memory
1255 // location if that memory location doesn't escape. Or it may pass a
1256 // nocapture value to other functions as long as they don't capture it.
1257 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1259 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1263 // If the size of one access is larger than the entire object on the other
1264 // side, then we know such behavior is undefined and can assume no alias.
1266 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1267 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1270 // Check the cache before climbing up use-def chains. This also terminates
1271 // otherwise infinitely recursive queries.
1272 LocPair Locs(Location(V1, V1Size, V1TBAAInfo),
1273 Location(V2, V2Size, V2TBAAInfo));
1275 std::swap(Locs.first, Locs.second);
1276 std::pair<AliasCacheTy::iterator, bool> Pair =
1277 AliasCache.insert(std::make_pair(Locs, MayAlias));
1279 return Pair.first->second;
1281 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1282 // GEP can't simplify, we don't even look at the PHI cases.
1283 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1285 std::swap(V1Size, V2Size);
1287 std::swap(V1TBAAInfo, V2TBAAInfo);
1289 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1290 AliasResult Result = aliasGEP(GV1, V1Size, V1TBAAInfo, V2, V2Size, V2TBAAInfo, O1, O2);
1291 if (Result != MayAlias) return AliasCache[Locs] = Result;
1294 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1296 std::swap(V1Size, V2Size);
1297 std::swap(V1TBAAInfo, V2TBAAInfo);
1299 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1300 AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1301 V2, V2Size, V2TBAAInfo);
1302 if (Result != MayAlias) return AliasCache[Locs] = Result;
1305 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1307 std::swap(V1Size, V2Size);
1308 std::swap(V1TBAAInfo, V2TBAAInfo);
1310 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1311 AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1312 V2, V2Size, V2TBAAInfo);
1313 if (Result != MayAlias) 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 != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1321 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
1322 return AliasCache[Locs] = PartialAlias;
1324 AliasResult Result =
1325 AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1326 Location(V2, V2Size, V2TBAAInfo));
1327 return AliasCache[Locs] = Result;
1330 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1335 const Instruction *Inst = dyn_cast<Instruction>(V);
1339 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1342 // Use dominance or loop info if available.
1343 DominatorTreeWrapperPass *DTWP =
1344 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1345 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1346 LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
1348 // Make sure that the visited phis cannot reach the Value. This ensures that
1349 // the Values cannot come from different iterations of a potential cycle the
1350 // phi nodes could be involved in.
1351 for (SmallPtrSet<const BasicBlock *, 8>::iterator PI = VisitedPhiBBs.begin(),
1352 PE = VisitedPhiBBs.end();
1354 if (isPotentiallyReachable((*PI)->begin(), Inst, DT, LI))
1360 /// GetIndexDifference - Dest and Src are the variable indices from two
1361 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1362 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1363 /// difference between the two pointers.
1364 void BasicAliasAnalysis::GetIndexDifference(
1365 SmallVectorImpl<VariableGEPIndex> &Dest,
1366 const SmallVectorImpl<VariableGEPIndex> &Src) {
1370 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1371 const Value *V = Src[i].V;
1372 ExtensionKind Extension = Src[i].Extension;
1373 int64_t Scale = Src[i].Scale;
1375 // Find V in Dest. This is N^2, but pointer indices almost never have more
1376 // than a few variable indexes.
1377 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1378 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1379 Dest[j].Extension != Extension)
1382 // If we found it, subtract off Scale V's from the entry in Dest. If it
1383 // goes to zero, remove the entry.
1384 if (Dest[j].Scale != Scale)
1385 Dest[j].Scale -= Scale;
1387 Dest.erase(Dest.begin() + j);
1392 // If we didn't consume this entry, add it to the end of the Dest list.
1394 VariableGEPIndex Entry = { V, Extension, -Scale };
1395 Dest.push_back(Entry);