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