sdisel flag -> glue.
[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/Pass.h"
29 #include "llvm/BasicBlock.h"
30 #include "llvm/Function.h"
31 #include "llvm/IntrinsicInst.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/LLVMContext.h"
34 #include "llvm/Type.h"
35 #include "llvm/Target/TargetData.h"
36 using namespace llvm;
37
38 // Register the AliasAnalysis interface, providing a nice name to refer to.
39 INITIALIZE_ANALYSIS_GROUP(AliasAnalysis, "Alias Analysis", NoAA)
40 char AliasAnalysis::ID = 0;
41
42 //===----------------------------------------------------------------------===//
43 // Default chaining methods
44 //===----------------------------------------------------------------------===//
45
46 AliasAnalysis::AliasResult
47 AliasAnalysis::alias(const Location &LocA, const Location &LocB) {
48   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
49   return AA->alias(LocA, LocB);
50 }
51
52 bool AliasAnalysis::pointsToConstantMemory(const Location &Loc,
53                                            bool OrLocal) {
54   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
55   return AA->pointsToConstantMemory(Loc, OrLocal);
56 }
57
58 void AliasAnalysis::deleteValue(Value *V) {
59   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
60   AA->deleteValue(V);
61 }
62
63 void AliasAnalysis::copyValue(Value *From, Value *To) {
64   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
65   AA->copyValue(From, To);
66 }
67
68 AliasAnalysis::ModRefResult
69 AliasAnalysis::getModRefInfo(ImmutableCallSite CS,
70                              const Location &Loc) {
71   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
72
73   ModRefBehavior MRB = getModRefBehavior(CS);
74   if (MRB == DoesNotAccessMemory)
75     return NoModRef;
76
77   ModRefResult Mask = ModRef;
78   if (onlyReadsMemory(MRB))
79     Mask = Ref;
80
81   if (onlyAccessesArgPointees(MRB)) {
82     bool doesAlias = false;
83     if (doesAccessArgPointees(MRB))
84       for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
85            AI != AE; ++AI)
86         if (!isNoAlias(Location(*AI), Loc)) {
87           doesAlias = true;
88           break;
89         }
90
91     if (!doesAlias)
92       return NoModRef;
93   }
94
95   // If Loc is a constant memory location, the call definitely could not
96   // modify the memory location.
97   if ((Mask & Mod) && pointsToConstantMemory(Loc))
98     Mask = ModRefResult(Mask & ~Mod);
99
100   // If this is the end of the chain, don't forward.
101   if (!AA) return Mask;
102
103   // Otherwise, fall back to the next AA in the chain. But we can merge
104   // in any mask we've managed to compute.
105   return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
106 }
107
108 AliasAnalysis::ModRefResult
109 AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
110   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
111
112   // If CS1 or CS2 are readnone, they don't interact.
113   ModRefBehavior CS1B = getModRefBehavior(CS1);
114   if (CS1B == DoesNotAccessMemory) return NoModRef;
115
116   ModRefBehavior CS2B = getModRefBehavior(CS2);
117   if (CS2B == DoesNotAccessMemory) return NoModRef;
118
119   // If they both only read from memory, there is no dependence.
120   if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
121     return NoModRef;
122
123   AliasAnalysis::ModRefResult Mask = ModRef;
124
125   // If CS1 only reads memory, the only dependence on CS2 can be
126   // from CS1 reading memory written by CS2.
127   if (onlyReadsMemory(CS1B))
128     Mask = ModRefResult(Mask & Ref);
129
130   // If CS2 only access memory through arguments, accumulate the mod/ref
131   // information from CS1's references to the memory referenced by
132   // CS2's arguments.
133   if (onlyAccessesArgPointees(CS2B)) {
134     AliasAnalysis::ModRefResult R = NoModRef;
135     if (doesAccessArgPointees(CS2B))
136       for (ImmutableCallSite::arg_iterator
137            I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
138         R = ModRefResult((R | getModRefInfo(CS1, *I, UnknownSize)) & Mask);
139         if (R == Mask)
140           break;
141       }
142     return R;
143   }
144
145   // If CS1 only accesses memory through arguments, check if CS2 references
146   // any of the memory referenced by CS1's arguments. If not, return NoModRef.
147   if (onlyAccessesArgPointees(CS1B)) {
148     AliasAnalysis::ModRefResult R = NoModRef;
149     if (doesAccessArgPointees(CS1B))
150       for (ImmutableCallSite::arg_iterator
151            I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I)
152         if (getModRefInfo(CS2, *I, UnknownSize) != NoModRef) {
153           R = Mask;
154           break;
155         }
156     if (R == NoModRef)
157       return R;
158   }
159
160   // If this is the end of the chain, don't forward.
161   if (!AA) return Mask;
162
163   // Otherwise, fall back to the next AA in the chain. But we can merge
164   // in any mask we've managed to compute.
165   return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
166 }
167
168 AliasAnalysis::ModRefBehavior
169 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
170   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
171
172   ModRefBehavior Min = UnknownModRefBehavior;
173
174   // Call back into the alias analysis with the other form of getModRefBehavior
175   // to see if it can give a better response.
176   if (const Function *F = CS.getCalledFunction())
177     Min = getModRefBehavior(F);
178
179   // If this is the end of the chain, don't forward.
180   if (!AA) return Min;
181
182   // Otherwise, fall back to the next AA in the chain. But we can merge
183   // in any result we've managed to compute.
184   return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
185 }
186
187 AliasAnalysis::ModRefBehavior
188 AliasAnalysis::getModRefBehavior(const Function *F) {
189   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
190   return AA->getModRefBehavior(F);
191 }
192
193 //===----------------------------------------------------------------------===//
194 // AliasAnalysis non-virtual helper method implementation
195 //===----------------------------------------------------------------------===//
196
197 AliasAnalysis::Location AliasAnalysis::getLocation(const LoadInst *LI) {
198   return Location(LI->getPointerOperand(),
199                   getTypeStoreSize(LI->getType()),
200                   LI->getMetadata(LLVMContext::MD_tbaa));
201 }
202
203 AliasAnalysis::Location AliasAnalysis::getLocation(const StoreInst *SI) {
204   return Location(SI->getPointerOperand(),
205                   getTypeStoreSize(SI->getValueOperand()->getType()),
206                   SI->getMetadata(LLVMContext::MD_tbaa));
207 }
208
209 AliasAnalysis::Location AliasAnalysis::getLocation(const VAArgInst *VI) {
210   return Location(VI->getPointerOperand(),
211                   UnknownSize,
212                   VI->getMetadata(LLVMContext::MD_tbaa));
213 }
214
215
216 AliasAnalysis::Location 
217 AliasAnalysis::getLocationForSource(const MemTransferInst *MTI) {
218   uint64_t Size = UnknownSize;
219   if (ConstantInt *C = dyn_cast<ConstantInt>(MTI->getLength()))
220     Size = C->getValue().getZExtValue();
221
222   // memcpy/memmove can have TBAA tags. For memcpy, they apply
223   // to both the source and the destination.
224   MDNode *TBAATag = MTI->getMetadata(LLVMContext::MD_tbaa);
225
226   return Location(MTI->getRawSource(), Size, TBAATag);
227 }
228
229 AliasAnalysis::Location 
230 AliasAnalysis::getLocationForDest(const MemIntrinsic *MTI) {
231   uint64_t Size = UnknownSize;
232   if (ConstantInt *C = dyn_cast<ConstantInt>(MTI->getLength()))
233     Size = C->getValue().getZExtValue();
234
235   // memcpy/memmove can have TBAA tags. For memcpy, they apply
236   // to both the source and the destination.
237   MDNode *TBAATag = MTI->getMetadata(LLVMContext::MD_tbaa);
238   
239   return Location(MTI->getRawDest(), Size, TBAATag);
240 }
241
242
243
244 AliasAnalysis::ModRefResult
245 AliasAnalysis::getModRefInfo(const LoadInst *L, const Location &Loc) {
246   // Be conservative in the face of volatile.
247   if (L->isVolatile())
248     return ModRef;
249
250   // If the load address doesn't alias the given address, it doesn't read
251   // or write the specified memory.
252   if (!alias(getLocation(L), Loc))
253     return NoModRef;
254
255   // Otherwise, a load just reads.
256   return Ref;
257 }
258
259 AliasAnalysis::ModRefResult
260 AliasAnalysis::getModRefInfo(const StoreInst *S, const Location &Loc) {
261   // Be conservative in the face of volatile.
262   if (S->isVolatile())
263     return ModRef;
264
265   // If the store address cannot alias the pointer in question, then the
266   // specified memory cannot be modified by the store.
267   if (!alias(getLocation(S), Loc))
268     return NoModRef;
269
270   // If the pointer is a pointer to constant memory, then it could not have been
271   // modified by this store.
272   if (pointsToConstantMemory(Loc))
273     return NoModRef;
274
275   // Otherwise, a store just writes.
276   return Mod;
277 }
278
279 AliasAnalysis::ModRefResult
280 AliasAnalysis::getModRefInfo(const VAArgInst *V, const Location &Loc) {
281   // If the va_arg address cannot alias the pointer in question, then the
282   // specified memory cannot be accessed by the va_arg.
283   if (!alias(getLocation(V), Loc))
284     return NoModRef;
285
286   // If the pointer is a pointer to constant memory, then it could not have been
287   // modified by this va_arg.
288   if (pointsToConstantMemory(Loc))
289     return NoModRef;
290
291   // Otherwise, a va_arg reads and writes.
292   return ModRef;
293 }
294
295 // AliasAnalysis destructor: DO NOT move this to the header file for
296 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
297 // the AliasAnalysis.o file in the current .a file, causing alias analysis
298 // support to not be included in the tool correctly!
299 //
300 AliasAnalysis::~AliasAnalysis() {}
301
302 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
303 /// AliasAnalysis interface before any other methods are called.
304 ///
305 void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
306   TD = P->getAnalysisIfAvailable<TargetData>();
307   AA = &P->getAnalysis<AliasAnalysis>();
308 }
309
310 // getAnalysisUsage - All alias analysis implementations should invoke this
311 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
312 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
313   AU.addRequired<AliasAnalysis>();         // All AA's chain
314 }
315
316 /// getTypeStoreSize - Return the TargetData store size for the given type,
317 /// if known, or a conservative value otherwise.
318 ///
319 uint64_t AliasAnalysis::getTypeStoreSize(const Type *Ty) {
320   return TD ? TD->getTypeStoreSize(Ty) : UnknownSize;
321 }
322
323 /// canBasicBlockModify - Return true if it is possible for execution of the
324 /// specified basic block to modify the value pointed to by Ptr.
325 ///
326 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
327                                         const Location &Loc) {
328   return canInstructionRangeModify(BB.front(), BB.back(), Loc);
329 }
330
331 /// canInstructionRangeModify - Return true if it is possible for the execution
332 /// of the specified instructions to modify the value pointed to by Ptr.  The
333 /// instructions to consider are all of the instructions in the range of [I1,I2]
334 /// INCLUSIVE.  I1 and I2 must be in the same basic block.
335 ///
336 bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
337                                               const Instruction &I2,
338                                               const Location &Loc) {
339   assert(I1.getParent() == I2.getParent() &&
340          "Instructions not in same basic block!");
341   BasicBlock::const_iterator I = &I1;
342   BasicBlock::const_iterator E = &I2;
343   ++E;  // Convert from inclusive to exclusive range.
344
345   for (; I != E; ++I) // Check every instruction in range
346     if (getModRefInfo(I, Loc) & Mod)
347       return true;
348   return false;
349 }
350
351 /// isNoAliasCall - Return true if this pointer is returned by a noalias
352 /// function.
353 bool llvm::isNoAliasCall(const Value *V) {
354   if (isa<CallInst>(V) || isa<InvokeInst>(V))
355     return ImmutableCallSite(cast<Instruction>(V))
356       .paramHasAttr(0, Attribute::NoAlias);
357   return false;
358 }
359
360 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
361 /// identifiable object.  This returns true for:
362 ///    Global Variables and Functions (but not Global Aliases)
363 ///    Allocas and Mallocs
364 ///    ByVal and NoAlias Arguments
365 ///    NoAlias returns
366 ///
367 bool llvm::isIdentifiedObject(const Value *V) {
368   if (isa<AllocaInst>(V))
369     return true;
370   if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
371     return true;
372   if (isNoAliasCall(V))
373     return true;
374   if (const Argument *A = dyn_cast<Argument>(V))
375     return A->hasNoAliasAttr() || A->hasByValAttr();
376   return false;
377 }