[PM/AA] Split the location computation out of getArgLocation so the
[oota-llvm.git] / lib / Analysis / AliasAnalysis.cpp
1 //===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
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,
17 // etc.
18 //
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
23 // easy cases.
24 //
25 //===----------------------------------------------------------------------===//
26
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"
41 using namespace llvm;
42
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;
46
47 //===----------------------------------------------------------------------===//
48 // Default chaining methods
49 //===----------------------------------------------------------------------===//
50
51 AliasAnalysis::AliasResult
52 AliasAnalysis::alias(const Location &LocA, const Location &LocB) {
53   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
54   return AA->alias(LocA, LocB);
55 }
56
57 bool AliasAnalysis::pointsToConstantMemory(const Location &Loc,
58                                            bool OrLocal) {
59   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
60   return AA->pointsToConstantMemory(Loc, OrLocal);
61 }
62
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);
67 }
68
69 void AliasAnalysis::deleteValue(Value *V) {
70   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
71   AA->deleteValue(V);
72 }
73
74 void AliasAnalysis::copyValue(Value *From, Value *To) {
75   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
76   AA->copyValue(From, To);
77 }
78
79 void AliasAnalysis::addEscapingUse(Use &U) {
80   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
81   AA->addEscapingUse(U);
82 }
83
84 AliasAnalysis::ModRefResult
85 AliasAnalysis::getModRefInfo(Instruction *I, ImmutableCallSite Call) {
86   // We may have two calls
87   if (auto CS = ImmutableCallSite(I)) {
88     // Check if the two calls modify the same memory
89     return getModRefInfo(Call, CS);
90   } else {
91     // Otherwise, check if the call modifies or references the
92     // location this memory access defines.  The best we can say
93     // is that if the call references what this instruction
94     // defines, it must be clobbered by this location.
95     const AliasAnalysis::Location DefLoc = MemoryLocation::get(I);
96     if (getModRefInfo(Call, DefLoc) != AliasAnalysis::NoModRef)
97       return AliasAnalysis::ModRef;
98   }
99   return AliasAnalysis::NoModRef;
100 }
101
102 AliasAnalysis::ModRefResult
103 AliasAnalysis::getModRefInfo(ImmutableCallSite CS,
104                              const Location &Loc) {
105   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
106
107   ModRefBehavior MRB = getModRefBehavior(CS);
108   if (MRB == DoesNotAccessMemory)
109     return NoModRef;
110
111   ModRefResult Mask = ModRef;
112   if (onlyReadsMemory(MRB))
113     Mask = Ref;
114
115   if (onlyAccessesArgPointees(MRB)) {
116     bool doesAlias = false;
117     ModRefResult AllArgsMask = NoModRef;
118     if (doesAccessArgPointees(MRB)) {
119       for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
120            AI != AE; ++AI) {
121         const Value *Arg = *AI;
122         if (!Arg->getType()->isPointerTy())
123           continue;
124         unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
125         Location ArgLoc = MemoryLocation::getForArgument(CS, ArgIdx, *TLI);
126         if (!isNoAlias(ArgLoc, Loc)) {
127           ModRefResult ArgMask = getArgModRefInfo(CS, ArgIdx);
128           doesAlias = true;
129           AllArgsMask = ModRefResult(AllArgsMask | ArgMask);
130         }
131       }
132     }
133     if (!doesAlias)
134       return NoModRef;
135     Mask = ModRefResult(Mask & AllArgsMask);
136   }
137
138   // If Loc is a constant memory location, the call definitely could not
139   // modify the memory location.
140   if ((Mask & Mod) && pointsToConstantMemory(Loc))
141     Mask = ModRefResult(Mask & ~Mod);
142
143   // If this is the end of the chain, don't forward.
144   if (!AA) return Mask;
145
146   // Otherwise, fall back to the next AA in the chain. But we can merge
147   // in any mask we've managed to compute.
148   return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
149 }
150
151 AliasAnalysis::ModRefResult
152 AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
153   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
154
155   // If CS1 or CS2 are readnone, they don't interact.
156   ModRefBehavior CS1B = getModRefBehavior(CS1);
157   if (CS1B == DoesNotAccessMemory) return NoModRef;
158
159   ModRefBehavior CS2B = getModRefBehavior(CS2);
160   if (CS2B == DoesNotAccessMemory) return NoModRef;
161
162   // If they both only read from memory, there is no dependence.
163   if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
164     return NoModRef;
165
166   AliasAnalysis::ModRefResult Mask = ModRef;
167
168   // If CS1 only reads memory, the only dependence on CS2 can be
169   // from CS1 reading memory written by CS2.
170   if (onlyReadsMemory(CS1B))
171     Mask = ModRefResult(Mask & Ref);
172
173   // If CS2 only access memory through arguments, accumulate the mod/ref
174   // information from CS1's references to the memory referenced by
175   // CS2's arguments.
176   if (onlyAccessesArgPointees(CS2B)) {
177     AliasAnalysis::ModRefResult R = NoModRef;
178     if (doesAccessArgPointees(CS2B)) {
179       for (ImmutableCallSite::arg_iterator
180            I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
181         const Value *Arg = *I;
182         if (!Arg->getType()->isPointerTy())
183           continue;
184         unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
185         Location CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, *TLI);
186
187         // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence of
188         // CS1 on that location is the inverse.
189         ModRefResult ArgMask = getArgModRefInfo(CS2, CS2ArgIdx);
190         if (ArgMask == Mod)
191           ArgMask = ModRef;
192         else if (ArgMask == Ref)
193           ArgMask = Mod;
194
195         R = ModRefResult((R | (getModRefInfo(CS1, CS2ArgLoc) & ArgMask)) & Mask);
196         if (R == Mask)
197           break;
198       }
199     }
200     return R;
201   }
202
203   // If CS1 only accesses memory through arguments, check if CS2 references
204   // any of the memory referenced by CS1's arguments. If not, return NoModRef.
205   if (onlyAccessesArgPointees(CS1B)) {
206     AliasAnalysis::ModRefResult R = NoModRef;
207     if (doesAccessArgPointees(CS1B)) {
208       for (ImmutableCallSite::arg_iterator
209            I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
210         const Value *Arg = *I;
211         if (!Arg->getType()->isPointerTy())
212           continue;
213         unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
214         Location CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, *TLI);
215
216         // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
217         // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
218         // might Ref, then we care only about a Mod by CS2.
219         ModRefResult ArgMask = getArgModRefInfo(CS1, CS1ArgIdx);
220         ModRefResult ArgR = getModRefInfo(CS2, CS1ArgLoc);
221         if (((ArgMask & Mod) != NoModRef && (ArgR & ModRef) != NoModRef) ||
222             ((ArgMask & Ref) != NoModRef && (ArgR & Mod)    != NoModRef))
223           R = ModRefResult((R | ArgMask) & Mask);
224
225         if (R == Mask)
226           break;
227       }
228     }
229     return R;
230   }
231
232   // If this is the end of the chain, don't forward.
233   if (!AA) return Mask;
234
235   // Otherwise, fall back to the next AA in the chain. But we can merge
236   // in any mask we've managed to compute.
237   return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
238 }
239
240 AliasAnalysis::ModRefBehavior
241 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
242   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
243
244   ModRefBehavior Min = UnknownModRefBehavior;
245
246   // Call back into the alias analysis with the other form of getModRefBehavior
247   // to see if it can give a better response.
248   if (const Function *F = CS.getCalledFunction())
249     Min = getModRefBehavior(F);
250
251   // If this is the end of the chain, don't forward.
252   if (!AA) return Min;
253
254   // Otherwise, fall back to the next AA in the chain. But we can merge
255   // in any result we've managed to compute.
256   return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
257 }
258
259 AliasAnalysis::ModRefBehavior
260 AliasAnalysis::getModRefBehavior(const Function *F) {
261   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
262   return AA->getModRefBehavior(F);
263 }
264
265 //===----------------------------------------------------------------------===//
266 // AliasAnalysis non-virtual helper method implementation
267 //===----------------------------------------------------------------------===//
268
269 AliasAnalysis::ModRefResult
270 AliasAnalysis::getModRefInfo(const LoadInst *L, const Location &Loc) {
271   // Be conservative in the face of volatile/atomic.
272   if (!L->isUnordered())
273     return ModRef;
274
275   // If the load address doesn't alias the given address, it doesn't read
276   // or write the specified memory.
277   if (Loc.Ptr && !alias(MemoryLocation::get(L), Loc))
278     return NoModRef;
279
280   // Otherwise, a load just reads.
281   return Ref;
282 }
283
284 AliasAnalysis::ModRefResult
285 AliasAnalysis::getModRefInfo(const StoreInst *S, const Location &Loc) {
286   // Be conservative in the face of volatile/atomic.
287   if (!S->isUnordered())
288     return ModRef;
289
290   if (Loc.Ptr) {
291     // If the store address cannot alias the pointer in question, then the
292     // specified memory cannot be modified by the store.
293     if (!alias(MemoryLocation::get(S), Loc))
294       return NoModRef;
295
296     // If the pointer is a pointer to constant memory, then it could not have
297     // been modified by this store.
298     if (pointsToConstantMemory(Loc))
299       return NoModRef;
300
301   }
302
303   // Otherwise, a store just writes.
304   return Mod;
305 }
306
307 AliasAnalysis::ModRefResult
308 AliasAnalysis::getModRefInfo(const VAArgInst *V, const Location &Loc) {
309
310   if (Loc.Ptr) {
311     // If the va_arg address cannot alias the pointer in question, then the
312     // specified memory cannot be accessed by the va_arg.
313     if (!alias(MemoryLocation::get(V), Loc))
314       return NoModRef;
315
316     // If the pointer is a pointer to constant memory, then it could not have
317     // been modified by this va_arg.
318     if (pointsToConstantMemory(Loc))
319       return NoModRef;
320   }
321
322   // Otherwise, a va_arg reads and writes.
323   return ModRef;
324 }
325
326 AliasAnalysis::ModRefResult
327 AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX, const Location &Loc) {
328   // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
329   if (CX->getSuccessOrdering() > Monotonic)
330     return ModRef;
331
332   // If the cmpxchg address does not alias the location, it does not access it.
333   if (Loc.Ptr && !alias(MemoryLocation::get(CX), Loc))
334     return NoModRef;
335
336   return ModRef;
337 }
338
339 AliasAnalysis::ModRefResult
340 AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW, const Location &Loc) {
341   // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
342   if (RMW->getOrdering() > Monotonic)
343     return ModRef;
344
345   // If the atomicrmw address does not alias the location, it does not access it.
346   if (Loc.Ptr && !alias(MemoryLocation::get(RMW), Loc))
347     return NoModRef;
348
349   return ModRef;
350 }
351
352 // FIXME: this is really just shoring-up a deficiency in alias analysis.
353 // BasicAA isn't willing to spend linear time determining whether an alloca
354 // was captured before or after this particular call, while we are. However,
355 // with a smarter AA in place, this test is just wasting compile time.
356 AliasAnalysis::ModRefResult
357 AliasAnalysis::callCapturesBefore(const Instruction *I,
358                                   const AliasAnalysis::Location &MemLoc,
359                                   DominatorTree *DT) {
360   if (!DT)
361     return AliasAnalysis::ModRef;
362
363   const Value *Object = GetUnderlyingObject(MemLoc.Ptr, *DL);
364   if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
365       isa<Constant>(Object))
366     return AliasAnalysis::ModRef;
367
368   ImmutableCallSite CS(I);
369   if (!CS.getInstruction() || CS.getInstruction() == Object)
370     return AliasAnalysis::ModRef;
371
372   if (llvm::PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
373                                        /* StoreCaptures */ true, I, DT,
374                                        /* include Object */ true))
375     return AliasAnalysis::ModRef;
376
377   unsigned ArgNo = 0;
378   AliasAnalysis::ModRefResult R = AliasAnalysis::NoModRef;
379   for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
380        CI != CE; ++CI, ++ArgNo) {
381     // Only look at the no-capture or byval pointer arguments.  If this
382     // pointer were passed to arguments that were neither of these, then it
383     // couldn't be no-capture.
384     if (!(*CI)->getType()->isPointerTy() ||
385         (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
386       continue;
387
388     // If this is a no-capture pointer argument, see if we can tell that it
389     // is impossible to alias the pointer we're checking.  If not, we have to
390     // assume that the call could touch the pointer, even though it doesn't
391     // escape.
392     if (isNoAlias(AliasAnalysis::Location(*CI),
393                   AliasAnalysis::Location(Object)))
394       continue;
395     if (CS.doesNotAccessMemory(ArgNo))
396       continue;
397     if (CS.onlyReadsMemory(ArgNo)) {
398       R = AliasAnalysis::Ref;
399       continue;
400     }
401     return AliasAnalysis::ModRef;
402   }
403   return R;
404 }
405
406 // AliasAnalysis destructor: DO NOT move this to the header file for
407 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
408 // the AliasAnalysis.o file in the current .a file, causing alias analysis
409 // support to not be included in the tool correctly!
410 //
411 AliasAnalysis::~AliasAnalysis() {}
412
413 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
414 /// AliasAnalysis interface before any other methods are called.
415 ///
416 void AliasAnalysis::InitializeAliasAnalysis(Pass *P, const DataLayout *NewDL) {
417   DL = NewDL;
418   auto *TLIP = P->getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
419   TLI = TLIP ? &TLIP->getTLI() : nullptr;
420   AA = &P->getAnalysis<AliasAnalysis>();
421 }
422
423 // getAnalysisUsage - All alias analysis implementations should invoke this
424 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
425 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
426   AU.addRequired<AliasAnalysis>();         // All AA's chain
427 }
428
429 /// getTypeStoreSize - Return the DataLayout store size for the given type,
430 /// if known, or a conservative value otherwise.
431 ///
432 uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
433   return DL ? DL->getTypeStoreSize(Ty) : UnknownSize;
434 }
435
436 /// canBasicBlockModify - Return true if it is possible for execution of the
437 /// specified basic block to modify the location Loc.
438 ///
439 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
440                                         const Location &Loc) {
441   return canInstructionRangeModRef(BB.front(), BB.back(), Loc, Mod);
442 }
443
444 /// canInstructionRangeModRef - Return true if it is possible for the
445 /// execution of the specified instructions to mod\ref (according to the
446 /// mode) the location Loc. The instructions to consider are all
447 /// of the instructions in the range of [I1,I2] INCLUSIVE.
448 /// I1 and I2 must be in the same basic block.
449 bool AliasAnalysis::canInstructionRangeModRef(const Instruction &I1,
450                                               const Instruction &I2,
451                                               const Location &Loc,
452                                               const ModRefResult Mode) {
453   assert(I1.getParent() == I2.getParent() &&
454          "Instructions not in same basic block!");
455   BasicBlock::const_iterator I = &I1;
456   BasicBlock::const_iterator E = &I2;
457   ++E;  // Convert from inclusive to exclusive range.
458
459   for (; I != E; ++I) // Check every instruction in range
460     if (getModRefInfo(I, Loc) & Mode)
461       return true;
462   return false;
463 }
464
465 /// isNoAliasCall - Return true if this pointer is returned by a noalias
466 /// function.
467 bool llvm::isNoAliasCall(const Value *V) {
468   if (isa<CallInst>(V) || isa<InvokeInst>(V))
469     return ImmutableCallSite(cast<Instruction>(V))
470       .paramHasAttr(0, Attribute::NoAlias);
471   return false;
472 }
473
474 /// isNoAliasArgument - Return true if this is an argument with the noalias
475 /// attribute.
476 bool llvm::isNoAliasArgument(const Value *V)
477 {
478   if (const Argument *A = dyn_cast<Argument>(V))
479     return A->hasNoAliasAttr();
480   return false;
481 }
482
483 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
484 /// identifiable object.  This returns true for:
485 ///    Global Variables and Functions (but not Global Aliases)
486 ///    Allocas and Mallocs
487 ///    ByVal and NoAlias Arguments
488 ///    NoAlias returns
489 ///
490 bool llvm::isIdentifiedObject(const Value *V) {
491   if (isa<AllocaInst>(V))
492     return true;
493   if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
494     return true;
495   if (isNoAliasCall(V))
496     return true;
497   if (const Argument *A = dyn_cast<Argument>(V))
498     return A->hasNoAliasAttr() || A->hasByValAttr();
499   return false;
500 }
501
502 /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
503 /// at the function-level. Different IdentifiedFunctionLocals can't alias.
504 /// Further, an IdentifiedFunctionLocal can not alias with any function
505 /// arguments other than itself, which is not necessarily true for
506 /// IdentifiedObjects.
507 bool llvm::isIdentifiedFunctionLocal(const Value *V)
508 {
509   return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
510 }