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 AliasAnalysis::ModRefResult
75 AliasAnalysis::getModRefInfo(Instruction *I, ImmutableCallSite Call) {
76 // We may have two calls
77 if (auto CS = ImmutableCallSite(I)) {
78 // Check if the two calls modify the same memory
79 return getModRefInfo(Call, CS);
81 // Otherwise, check if the call modifies or references the
82 // location this memory access defines. The best we can say
83 // is that if the call references what this instruction
84 // defines, it must be clobbered by this location.
85 const MemoryLocation DefLoc = MemoryLocation::get(I);
86 if (getModRefInfo(Call, DefLoc) != AliasAnalysis::NoModRef)
87 return AliasAnalysis::ModRef;
89 return AliasAnalysis::NoModRef;
92 AliasAnalysis::ModRefResult
93 AliasAnalysis::getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
94 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
96 ModRefBehavior MRB = getModRefBehavior(CS);
97 if (MRB == DoesNotAccessMemory)
100 ModRefResult Mask = ModRef;
101 if (onlyReadsMemory(MRB))
104 if (onlyAccessesArgPointees(MRB)) {
105 bool doesAlias = false;
106 ModRefResult AllArgsMask = NoModRef;
107 if (doesAccessArgPointees(MRB)) {
108 for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
110 const Value *Arg = *AI;
111 if (!Arg->getType()->isPointerTy())
113 unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
114 MemoryLocation ArgLoc =
115 MemoryLocation::getForArgument(CS, ArgIdx, *TLI);
116 if (!isNoAlias(ArgLoc, Loc)) {
117 ModRefResult ArgMask = getArgModRefInfo(CS, ArgIdx);
119 AllArgsMask = ModRefResult(AllArgsMask | ArgMask);
125 Mask = ModRefResult(Mask & AllArgsMask);
128 // If Loc is a constant memory location, the call definitely could not
129 // modify the memory location.
130 if ((Mask & Mod) && pointsToConstantMemory(Loc))
131 Mask = ModRefResult(Mask & ~Mod);
133 // If this is the end of the chain, don't forward.
134 if (!AA) return Mask;
136 // Otherwise, fall back to the next AA in the chain. But we can merge
137 // in any mask we've managed to compute.
138 return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
141 AliasAnalysis::ModRefResult
142 AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
143 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
145 // If CS1 or CS2 are readnone, they don't interact.
146 ModRefBehavior CS1B = getModRefBehavior(CS1);
147 if (CS1B == DoesNotAccessMemory) return NoModRef;
149 ModRefBehavior CS2B = getModRefBehavior(CS2);
150 if (CS2B == DoesNotAccessMemory) return NoModRef;
152 // If they both only read from memory, there is no dependence.
153 if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
156 AliasAnalysis::ModRefResult Mask = ModRef;
158 // If CS1 only reads memory, the only dependence on CS2 can be
159 // from CS1 reading memory written by CS2.
160 if (onlyReadsMemory(CS1B))
161 Mask = ModRefResult(Mask & Ref);
163 // If CS2 only access memory through arguments, accumulate the mod/ref
164 // information from CS1's references to the memory referenced by
166 if (onlyAccessesArgPointees(CS2B)) {
167 AliasAnalysis::ModRefResult R = NoModRef;
168 if (doesAccessArgPointees(CS2B)) {
169 for (ImmutableCallSite::arg_iterator
170 I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
171 const Value *Arg = *I;
172 if (!Arg->getType()->isPointerTy())
174 unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
175 auto CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, *TLI);
177 // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence of
178 // CS1 on that location is the inverse.
179 ModRefResult ArgMask = getArgModRefInfo(CS2, CS2ArgIdx);
182 else if (ArgMask == Ref)
185 R = ModRefResult((R | (getModRefInfo(CS1, CS2ArgLoc) & ArgMask)) & Mask);
193 // If CS1 only accesses memory through arguments, check if CS2 references
194 // any of the memory referenced by CS1's arguments. If not, return NoModRef.
195 if (onlyAccessesArgPointees(CS1B)) {
196 AliasAnalysis::ModRefResult R = NoModRef;
197 if (doesAccessArgPointees(CS1B)) {
198 for (ImmutableCallSite::arg_iterator
199 I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
200 const Value *Arg = *I;
201 if (!Arg->getType()->isPointerTy())
203 unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
204 auto CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, *TLI);
206 // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
207 // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
208 // might Ref, then we care only about a Mod by CS2.
209 ModRefResult ArgMask = getArgModRefInfo(CS1, CS1ArgIdx);
210 ModRefResult ArgR = getModRefInfo(CS2, CS1ArgLoc);
211 if (((ArgMask & Mod) != NoModRef && (ArgR & ModRef) != NoModRef) ||
212 ((ArgMask & Ref) != NoModRef && (ArgR & Mod) != NoModRef))
213 R = ModRefResult((R | ArgMask) & Mask);
222 // If this is the end of the chain, don't forward.
223 if (!AA) return Mask;
225 // Otherwise, fall back to the next AA in the chain. But we can merge
226 // in any mask we've managed to compute.
227 return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
230 AliasAnalysis::ModRefBehavior
231 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
232 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
234 ModRefBehavior Min = UnknownModRefBehavior;
236 // Call back into the alias analysis with the other form of getModRefBehavior
237 // to see if it can give a better response.
238 if (const Function *F = CS.getCalledFunction())
239 Min = getModRefBehavior(F);
241 // If this is the end of the chain, don't forward.
244 // Otherwise, fall back to the next AA in the chain. But we can merge
245 // in any result we've managed to compute.
246 return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
249 AliasAnalysis::ModRefBehavior
250 AliasAnalysis::getModRefBehavior(const Function *F) {
251 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
252 return AA->getModRefBehavior(F);
255 //===----------------------------------------------------------------------===//
256 // AliasAnalysis non-virtual helper method implementation
257 //===----------------------------------------------------------------------===//
259 AliasAnalysis::ModRefResult
260 AliasAnalysis::getModRefInfo(const LoadInst *L, const MemoryLocation &Loc) {
261 // Be conservative in the face of volatile/atomic.
262 if (!L->isUnordered())
265 // If the load address doesn't alias the given address, it doesn't read
266 // or write the specified memory.
267 if (Loc.Ptr && !alias(MemoryLocation::get(L), Loc))
270 // Otherwise, a load just reads.
274 AliasAnalysis::ModRefResult
275 AliasAnalysis::getModRefInfo(const StoreInst *S, const MemoryLocation &Loc) {
276 // Be conservative in the face of volatile/atomic.
277 if (!S->isUnordered())
281 // If the store address cannot alias the pointer in question, then the
282 // specified memory cannot be modified by the store.
283 if (!alias(MemoryLocation::get(S), Loc))
286 // If the pointer is a pointer to constant memory, then it could not have
287 // been modified by this store.
288 if (pointsToConstantMemory(Loc))
293 // Otherwise, a store just writes.
297 AliasAnalysis::ModRefResult
298 AliasAnalysis::getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc) {
301 // If the va_arg address cannot alias the pointer in question, then the
302 // specified memory cannot be accessed by the va_arg.
303 if (!alias(MemoryLocation::get(V), Loc))
306 // If the pointer is a pointer to constant memory, then it could not have
307 // been modified by this va_arg.
308 if (pointsToConstantMemory(Loc))
312 // Otherwise, a va_arg reads and writes.
316 AliasAnalysis::ModRefResult
317 AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX,
318 const MemoryLocation &Loc) {
319 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
320 if (CX->getSuccessOrdering() > Monotonic)
323 // If the cmpxchg address does not alias the location, it does not access it.
324 if (Loc.Ptr && !alias(MemoryLocation::get(CX), Loc))
330 AliasAnalysis::ModRefResult
331 AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW,
332 const MemoryLocation &Loc) {
333 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
334 if (RMW->getOrdering() > Monotonic)
337 // If the atomicrmw address does not alias the location, it does not access it.
338 if (Loc.Ptr && !alias(MemoryLocation::get(RMW), Loc))
344 // FIXME: this is really just shoring-up a deficiency in alias analysis.
345 // BasicAA isn't willing to spend linear time determining whether an alloca
346 // was captured before or after this particular call, while we are. However,
347 // with a smarter AA in place, this test is just wasting compile time.
348 AliasAnalysis::ModRefResult AliasAnalysis::callCapturesBefore(
349 const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT) {
351 return AliasAnalysis::ModRef;
353 const Value *Object = GetUnderlyingObject(MemLoc.Ptr, *DL);
354 if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
355 isa<Constant>(Object))
356 return AliasAnalysis::ModRef;
358 ImmutableCallSite CS(I);
359 if (!CS.getInstruction() || CS.getInstruction() == Object)
360 return AliasAnalysis::ModRef;
362 if (llvm::PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
363 /* StoreCaptures */ true, I, DT,
364 /* include Object */ true))
365 return AliasAnalysis::ModRef;
368 AliasAnalysis::ModRefResult R = AliasAnalysis::NoModRef;
369 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
370 CI != CE; ++CI, ++ArgNo) {
371 // Only look at the no-capture or byval pointer arguments. If this
372 // pointer were passed to arguments that were neither of these, then it
373 // couldn't be no-capture.
374 if (!(*CI)->getType()->isPointerTy() ||
375 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
378 // If this is a no-capture pointer argument, see if we can tell that it
379 // is impossible to alias the pointer we're checking. If not, we have to
380 // assume that the call could touch the pointer, even though it doesn't
382 if (isNoAlias(MemoryLocation(*CI), MemoryLocation(Object)))
384 if (CS.doesNotAccessMemory(ArgNo))
386 if (CS.onlyReadsMemory(ArgNo)) {
387 R = AliasAnalysis::Ref;
390 return AliasAnalysis::ModRef;
395 // AliasAnalysis destructor: DO NOT move this to the header file for
396 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
397 // the AliasAnalysis.o file in the current .a file, causing alias analysis
398 // support to not be included in the tool correctly!
400 AliasAnalysis::~AliasAnalysis() {}
402 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
403 /// AliasAnalysis interface before any other methods are called.
405 void AliasAnalysis::InitializeAliasAnalysis(Pass *P, const DataLayout *NewDL) {
407 auto *TLIP = P->getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
408 TLI = TLIP ? &TLIP->getTLI() : nullptr;
409 AA = &P->getAnalysis<AliasAnalysis>();
412 // getAnalysisUsage - All alias analysis implementations should invoke this
413 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
414 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
415 AU.addRequired<AliasAnalysis>(); // All AA's chain
418 /// getTypeStoreSize - Return the DataLayout store size for the given type,
419 /// if known, or a conservative value otherwise.
421 uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
422 return DL ? DL->getTypeStoreSize(Ty) : MemoryLocation::UnknownSize;
425 /// canBasicBlockModify - Return true if it is possible for execution of the
426 /// specified basic block to modify the location Loc.
428 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
429 const MemoryLocation &Loc) {
430 return canInstructionRangeModRef(BB.front(), BB.back(), Loc, Mod);
433 /// canInstructionRangeModRef - Return true if it is possible for the
434 /// execution of the specified instructions to mod\ref (according to the
435 /// mode) the location Loc. The instructions to consider are all
436 /// of the instructions in the range of [I1,I2] INCLUSIVE.
437 /// I1 and I2 must be in the same basic block.
438 bool AliasAnalysis::canInstructionRangeModRef(const Instruction &I1,
439 const Instruction &I2,
440 const MemoryLocation &Loc,
441 const ModRefResult Mode) {
442 assert(I1.getParent() == I2.getParent() &&
443 "Instructions not in same basic block!");
444 BasicBlock::const_iterator I = &I1;
445 BasicBlock::const_iterator E = &I2;
446 ++E; // Convert from inclusive to exclusive range.
448 for (; I != E; ++I) // Check every instruction in range
449 if (getModRefInfo(I, Loc) & Mode)
454 /// isNoAliasCall - Return true if this pointer is returned by a noalias
456 bool llvm::isNoAliasCall(const Value *V) {
457 if (isa<CallInst>(V) || isa<InvokeInst>(V))
458 return ImmutableCallSite(cast<Instruction>(V))
459 .paramHasAttr(0, Attribute::NoAlias);
463 /// isNoAliasArgument - Return true if this is an argument with the noalias
465 bool llvm::isNoAliasArgument(const Value *V)
467 if (const Argument *A = dyn_cast<Argument>(V))
468 return A->hasNoAliasAttr();
472 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
473 /// identifiable object. This returns true for:
474 /// Global Variables and Functions (but not Global Aliases)
475 /// Allocas and Mallocs
476 /// ByVal and NoAlias Arguments
479 bool llvm::isIdentifiedObject(const Value *V) {
480 if (isa<AllocaInst>(V))
482 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
484 if (isNoAliasCall(V))
486 if (const Argument *A = dyn_cast<Argument>(V))
487 return A->hasNoAliasAttr() || A->hasByValAttr();
491 /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
492 /// at the function-level. Different IdentifiedFunctionLocals can't alias.
493 /// Further, an IdentifiedFunctionLocal can not alias with any function
494 /// arguments other than itself, which is not necessarily true for
495 /// IdentifiedObjects.
496 bool llvm::isIdentifiedFunctionLocal(const Value *V)
498 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);