1 //===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==//
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 implements the generic AliasAnalysis interface which is used as the
11 // common interface used by all clients and implementations of alias analysis.
13 // This file also implements the default version of the AliasAnalysis interface
14 // that is to be used when no other implementation is specified. This does some
15 // simple tests that detect obvious cases: two different global pointers cannot
16 // alias, a global cannot alias a malloc, two different mallocs cannot alias,
19 // This alias analysis implementation really isn't very good for anything, but
20 // it is very fast, and makes a nice clean default implementation. Because it
21 // handles lots of little corner cases, other, more complex, alias analysis
22 // implementations may choose to rely on this pass to resolve these simple and
25 //===----------------------------------------------------------------------===//
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/Pass.h"
43 // Register the AliasAnalysis interface, providing a nice name to refer to.
44 INITIALIZE_ANALYSIS_GROUP(AliasAnalysis, "Alias Analysis", NoAA)
45 char AliasAnalysis::ID = 0;
47 //===----------------------------------------------------------------------===//
48 // Default chaining methods
49 //===----------------------------------------------------------------------===//
51 AliasResult AliasAnalysis::alias(const MemoryLocation &LocA,
52 const MemoryLocation &LocB) {
53 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
54 return AA->alias(LocA, LocB);
57 bool AliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
59 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
60 return AA->pointsToConstantMemory(Loc, OrLocal);
63 AliasAnalysis::ModRefResult
64 AliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
65 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
66 return AA->getArgModRefInfo(CS, ArgIdx);
69 void AliasAnalysis::deleteValue(Value *V) {
70 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
74 void AliasAnalysis::addEscapingUse(Use &U) {
75 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
76 AA->addEscapingUse(U);
79 AliasAnalysis::ModRefResult
80 AliasAnalysis::getModRefInfo(Instruction *I, ImmutableCallSite Call) {
81 // We may have two calls
82 if (auto CS = ImmutableCallSite(I)) {
83 // Check if the two calls modify the same memory
84 return getModRefInfo(Call, CS);
86 // Otherwise, check if the call modifies or references the
87 // location this memory access defines. The best we can say
88 // is that if the call references what this instruction
89 // defines, it must be clobbered by this location.
90 const MemoryLocation DefLoc = MemoryLocation::get(I);
91 if (getModRefInfo(Call, DefLoc) != AliasAnalysis::NoModRef)
92 return AliasAnalysis::ModRef;
94 return AliasAnalysis::NoModRef;
97 AliasAnalysis::ModRefResult
98 AliasAnalysis::getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
99 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
101 ModRefBehavior MRB = getModRefBehavior(CS);
102 if (MRB == DoesNotAccessMemory)
105 ModRefResult Mask = ModRef;
106 if (onlyReadsMemory(MRB))
109 if (onlyAccessesArgPointees(MRB)) {
110 bool doesAlias = false;
111 ModRefResult AllArgsMask = NoModRef;
112 if (doesAccessArgPointees(MRB)) {
113 for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
115 const Value *Arg = *AI;
116 if (!Arg->getType()->isPointerTy())
118 unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
119 MemoryLocation ArgLoc =
120 MemoryLocation::getForArgument(CS, ArgIdx, *TLI);
121 if (!isNoAlias(ArgLoc, Loc)) {
122 ModRefResult ArgMask = getArgModRefInfo(CS, ArgIdx);
124 AllArgsMask = ModRefResult(AllArgsMask | ArgMask);
130 Mask = ModRefResult(Mask & AllArgsMask);
133 // If Loc is a constant memory location, the call definitely could not
134 // modify the memory location.
135 if ((Mask & Mod) && pointsToConstantMemory(Loc))
136 Mask = ModRefResult(Mask & ~Mod);
138 // If this is the end of the chain, don't forward.
139 if (!AA) return Mask;
141 // Otherwise, fall back to the next AA in the chain. But we can merge
142 // in any mask we've managed to compute.
143 return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
146 AliasAnalysis::ModRefResult
147 AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
148 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
150 // If CS1 or CS2 are readnone, they don't interact.
151 ModRefBehavior CS1B = getModRefBehavior(CS1);
152 if (CS1B == DoesNotAccessMemory) return NoModRef;
154 ModRefBehavior CS2B = getModRefBehavior(CS2);
155 if (CS2B == DoesNotAccessMemory) return NoModRef;
157 // If they both only read from memory, there is no dependence.
158 if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
161 AliasAnalysis::ModRefResult Mask = ModRef;
163 // If CS1 only reads memory, the only dependence on CS2 can be
164 // from CS1 reading memory written by CS2.
165 if (onlyReadsMemory(CS1B))
166 Mask = ModRefResult(Mask & Ref);
168 // If CS2 only access memory through arguments, accumulate the mod/ref
169 // information from CS1's references to the memory referenced by
171 if (onlyAccessesArgPointees(CS2B)) {
172 AliasAnalysis::ModRefResult R = NoModRef;
173 if (doesAccessArgPointees(CS2B)) {
174 for (ImmutableCallSite::arg_iterator
175 I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
176 const Value *Arg = *I;
177 if (!Arg->getType()->isPointerTy())
179 unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
180 auto CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, *TLI);
182 // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence of
183 // CS1 on that location is the inverse.
184 ModRefResult ArgMask = getArgModRefInfo(CS2, CS2ArgIdx);
187 else if (ArgMask == Ref)
190 R = ModRefResult((R | (getModRefInfo(CS1, CS2ArgLoc) & ArgMask)) & Mask);
198 // If CS1 only accesses memory through arguments, check if CS2 references
199 // any of the memory referenced by CS1's arguments. If not, return NoModRef.
200 if (onlyAccessesArgPointees(CS1B)) {
201 AliasAnalysis::ModRefResult R = NoModRef;
202 if (doesAccessArgPointees(CS1B)) {
203 for (ImmutableCallSite::arg_iterator
204 I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
205 const Value *Arg = *I;
206 if (!Arg->getType()->isPointerTy())
208 unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
209 auto CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, *TLI);
211 // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
212 // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
213 // might Ref, then we care only about a Mod by CS2.
214 ModRefResult ArgMask = getArgModRefInfo(CS1, CS1ArgIdx);
215 ModRefResult ArgR = getModRefInfo(CS2, CS1ArgLoc);
216 if (((ArgMask & Mod) != NoModRef && (ArgR & ModRef) != NoModRef) ||
217 ((ArgMask & Ref) != NoModRef && (ArgR & Mod) != NoModRef))
218 R = ModRefResult((R | ArgMask) & Mask);
227 // If this is the end of the chain, don't forward.
228 if (!AA) return Mask;
230 // Otherwise, fall back to the next AA in the chain. But we can merge
231 // in any mask we've managed to compute.
232 return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
235 AliasAnalysis::ModRefBehavior
236 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
237 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
239 ModRefBehavior Min = UnknownModRefBehavior;
241 // Call back into the alias analysis with the other form of getModRefBehavior
242 // to see if it can give a better response.
243 if (const Function *F = CS.getCalledFunction())
244 Min = getModRefBehavior(F);
246 // If this is the end of the chain, don't forward.
249 // Otherwise, fall back to the next AA in the chain. But we can merge
250 // in any result we've managed to compute.
251 return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
254 AliasAnalysis::ModRefBehavior
255 AliasAnalysis::getModRefBehavior(const Function *F) {
256 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
257 return AA->getModRefBehavior(F);
260 //===----------------------------------------------------------------------===//
261 // AliasAnalysis non-virtual helper method implementation
262 //===----------------------------------------------------------------------===//
264 AliasAnalysis::ModRefResult
265 AliasAnalysis::getModRefInfo(const LoadInst *L, const MemoryLocation &Loc) {
266 // Be conservative in the face of volatile/atomic.
267 if (!L->isUnordered())
270 // If the load address doesn't alias the given address, it doesn't read
271 // or write the specified memory.
272 if (Loc.Ptr && !alias(MemoryLocation::get(L), Loc))
275 // Otherwise, a load just reads.
279 AliasAnalysis::ModRefResult
280 AliasAnalysis::getModRefInfo(const StoreInst *S, const MemoryLocation &Loc) {
281 // Be conservative in the face of volatile/atomic.
282 if (!S->isUnordered())
286 // If the store address cannot alias the pointer in question, then the
287 // specified memory cannot be modified by the store.
288 if (!alias(MemoryLocation::get(S), Loc))
291 // If the pointer is a pointer to constant memory, then it could not have
292 // been modified by this store.
293 if (pointsToConstantMemory(Loc))
298 // Otherwise, a store just writes.
302 AliasAnalysis::ModRefResult
303 AliasAnalysis::getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc) {
306 // If the va_arg address cannot alias the pointer in question, then the
307 // specified memory cannot be accessed by the va_arg.
308 if (!alias(MemoryLocation::get(V), Loc))
311 // If the pointer is a pointer to constant memory, then it could not have
312 // been modified by this va_arg.
313 if (pointsToConstantMemory(Loc))
317 // Otherwise, a va_arg reads and writes.
321 AliasAnalysis::ModRefResult
322 AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX,
323 const MemoryLocation &Loc) {
324 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
325 if (CX->getSuccessOrdering() > Monotonic)
328 // If the cmpxchg address does not alias the location, it does not access it.
329 if (Loc.Ptr && !alias(MemoryLocation::get(CX), Loc))
335 AliasAnalysis::ModRefResult
336 AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW,
337 const MemoryLocation &Loc) {
338 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
339 if (RMW->getOrdering() > Monotonic)
342 // If the atomicrmw address does not alias the location, it does not access it.
343 if (Loc.Ptr && !alias(MemoryLocation::get(RMW), Loc))
349 // FIXME: this is really just shoring-up a deficiency in alias analysis.
350 // BasicAA isn't willing to spend linear time determining whether an alloca
351 // was captured before or after this particular call, while we are. However,
352 // with a smarter AA in place, this test is just wasting compile time.
353 AliasAnalysis::ModRefResult AliasAnalysis::callCapturesBefore(
354 const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT) {
356 return AliasAnalysis::ModRef;
358 const Value *Object = GetUnderlyingObject(MemLoc.Ptr, *DL);
359 if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
360 isa<Constant>(Object))
361 return AliasAnalysis::ModRef;
363 ImmutableCallSite CS(I);
364 if (!CS.getInstruction() || CS.getInstruction() == Object)
365 return AliasAnalysis::ModRef;
367 if (llvm::PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
368 /* StoreCaptures */ true, I, DT,
369 /* include Object */ true))
370 return AliasAnalysis::ModRef;
373 AliasAnalysis::ModRefResult R = AliasAnalysis::NoModRef;
374 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
375 CI != CE; ++CI, ++ArgNo) {
376 // Only look at the no-capture or byval pointer arguments. If this
377 // pointer were passed to arguments that were neither of these, then it
378 // couldn't be no-capture.
379 if (!(*CI)->getType()->isPointerTy() ||
380 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
383 // If this is a no-capture pointer argument, see if we can tell that it
384 // is impossible to alias the pointer we're checking. If not, we have to
385 // assume that the call could touch the pointer, even though it doesn't
387 if (isNoAlias(MemoryLocation(*CI), MemoryLocation(Object)))
389 if (CS.doesNotAccessMemory(ArgNo))
391 if (CS.onlyReadsMemory(ArgNo)) {
392 R = AliasAnalysis::Ref;
395 return AliasAnalysis::ModRef;
400 // AliasAnalysis destructor: DO NOT move this to the header file for
401 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
402 // the AliasAnalysis.o file in the current .a file, causing alias analysis
403 // support to not be included in the tool correctly!
405 AliasAnalysis::~AliasAnalysis() {}
407 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
408 /// AliasAnalysis interface before any other methods are called.
410 void AliasAnalysis::InitializeAliasAnalysis(Pass *P, const DataLayout *NewDL) {
412 auto *TLIP = P->getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
413 TLI = TLIP ? &TLIP->getTLI() : nullptr;
414 AA = &P->getAnalysis<AliasAnalysis>();
417 // getAnalysisUsage - All alias analysis implementations should invoke this
418 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
419 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
420 AU.addRequired<AliasAnalysis>(); // All AA's chain
423 /// getTypeStoreSize - Return the DataLayout store size for the given type,
424 /// if known, or a conservative value otherwise.
426 uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
427 return DL ? DL->getTypeStoreSize(Ty) : MemoryLocation::UnknownSize;
430 /// canBasicBlockModify - Return true if it is possible for execution of the
431 /// specified basic block to modify the location Loc.
433 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
434 const MemoryLocation &Loc) {
435 return canInstructionRangeModRef(BB.front(), BB.back(), Loc, Mod);
438 /// canInstructionRangeModRef - Return true if it is possible for the
439 /// execution of the specified instructions to mod\ref (according to the
440 /// mode) the location Loc. The instructions to consider are all
441 /// of the instructions in the range of [I1,I2] INCLUSIVE.
442 /// I1 and I2 must be in the same basic block.
443 bool AliasAnalysis::canInstructionRangeModRef(const Instruction &I1,
444 const Instruction &I2,
445 const MemoryLocation &Loc,
446 const ModRefResult Mode) {
447 assert(I1.getParent() == I2.getParent() &&
448 "Instructions not in same basic block!");
449 BasicBlock::const_iterator I = &I1;
450 BasicBlock::const_iterator E = &I2;
451 ++E; // Convert from inclusive to exclusive range.
453 for (; I != E; ++I) // Check every instruction in range
454 if (getModRefInfo(I, Loc) & Mode)
459 /// isNoAliasCall - Return true if this pointer is returned by a noalias
461 bool llvm::isNoAliasCall(const Value *V) {
462 if (isa<CallInst>(V) || isa<InvokeInst>(V))
463 return ImmutableCallSite(cast<Instruction>(V))
464 .paramHasAttr(0, Attribute::NoAlias);
468 /// isNoAliasArgument - Return true if this is an argument with the noalias
470 bool llvm::isNoAliasArgument(const Value *V)
472 if (const Argument *A = dyn_cast<Argument>(V))
473 return A->hasNoAliasAttr();
477 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
478 /// identifiable object. This returns true for:
479 /// Global Variables and Functions (but not Global Aliases)
480 /// Allocas and Mallocs
481 /// ByVal and NoAlias Arguments
484 bool llvm::isIdentifiedObject(const Value *V) {
485 if (isa<AllocaInst>(V))
487 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
489 if (isNoAliasCall(V))
491 if (const Argument *A = dyn_cast<Argument>(V))
492 return A->hasNoAliasAttr() || A->hasByValAttr();
496 /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
497 /// at the function-level. Different IdentifiedFunctionLocals can't alias.
498 /// Further, an IdentifiedFunctionLocal can not alias with any function
499 /// arguments other than itself, which is not necessarily true for
500 /// IdentifiedObjects.
501 bool llvm::isIdentifiedFunctionLocal(const Value *V)
503 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);