Yes, we can do better, but this is not the place for it.
[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/Type.h"
34 #include "llvm/Target/TargetData.h"
35 using namespace llvm;
36
37 // Register the AliasAnalysis interface, providing a nice name to refer to.
38 static RegisterAnalysisGroup<AliasAnalysis> Z("Alias Analysis");
39 char AliasAnalysis::ID = 0;
40
41 //===----------------------------------------------------------------------===//
42 // Default chaining methods
43 //===----------------------------------------------------------------------===//
44
45 AliasAnalysis::AliasResult
46 AliasAnalysis::alias(const Value *V1, unsigned V1Size,
47                      const Value *V2, unsigned V2Size) {
48   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
49   return AA->alias(V1, V1Size, V2, V2Size);
50 }
51
52 bool AliasAnalysis::pointsToConstantMemory(const Value *P) {
53   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
54   return AA->pointsToConstantMemory(P);
55 }
56
57 void AliasAnalysis::deleteValue(Value *V) {
58   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
59   AA->deleteValue(V);
60 }
61
62 void AliasAnalysis::copyValue(Value *From, Value *To) {
63   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
64   AA->copyValue(From, To);
65 }
66
67 AliasAnalysis::ModRefResult
68 AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
69   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
70   return AA->getModRefInfo(CS1, CS2);
71 }
72
73
74 //===----------------------------------------------------------------------===//
75 // AliasAnalysis non-virtual helper method implementation
76 //===----------------------------------------------------------------------===//
77
78 AliasAnalysis::ModRefResult
79 AliasAnalysis::getModRefInfo(const LoadInst *L, const Value *P, unsigned Size) {
80   // If the load address doesn't alias the given address, it doesn't read
81   // or write the specified memory.
82   if (!alias(L->getOperand(0), getTypeStoreSize(L->getType()), P, Size))
83     return NoModRef;
84
85   // Be conservative in the face of volatile.
86   if (L->isVolatile())
87     return ModRef;
88
89   // Otherwise, a load just reads.
90   return Ref;
91 }
92
93 AliasAnalysis::ModRefResult
94 AliasAnalysis::getModRefInfo(const StoreInst *S, const Value *P, unsigned Size) {
95   // If the stored address cannot alias the pointer in question, then the
96   // pointer cannot be modified by the store.
97   if (!alias(S->getOperand(1),
98              getTypeStoreSize(S->getOperand(0)->getType()), P, Size))
99     return NoModRef;
100
101   // Be conservative in the face of volatile.
102   if (S->isVolatile())
103     return ModRef;
104
105   // If the pointer is a pointer to constant memory, then it could not have been
106   // modified by this store.
107   if (pointsToConstantMemory(P))
108     return NoModRef;
109
110   // Otherwise, a store just writes.
111   return Mod;
112 }
113
114 AliasAnalysis::ModRefBehavior
115 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
116   if (CS.doesNotAccessMemory())
117     // Can't do better than this.
118     return DoesNotAccessMemory;
119   ModRefBehavior MRB = getModRefBehavior(CS.getCalledFunction());
120   if (MRB != DoesNotAccessMemory && CS.onlyReadsMemory())
121     return OnlyReadsMemory;
122   return MRB;
123 }
124
125 AliasAnalysis::ModRefBehavior
126 AliasAnalysis::getModRefBehavior(const Function *F) {
127   if (F) {
128     if (F->doesNotAccessMemory())
129       // Can't do better than this.
130       return DoesNotAccessMemory;
131     if (F->onlyReadsMemory())
132       return OnlyReadsMemory;
133     if (unsigned id = F->getIntrinsicID())
134       return getIntrinsicModRefBehavior(id);
135   }
136   return UnknownModRefBehavior;
137 }
138
139 AliasAnalysis::ModRefBehavior
140 AliasAnalysis::getIntrinsicModRefBehavior(unsigned iid) {
141 #define GET_INTRINSIC_MODREF_BEHAVIOR
142 #include "llvm/Intrinsics.gen"
143 #undef GET_INTRINSIC_MODREF_BEHAVIOR
144 }
145
146 AliasAnalysis::ModRefResult
147 AliasAnalysis::getModRefInfo(ImmutableCallSite CS,
148                              const Value *P, unsigned Size) {
149   ModRefBehavior MRB = getModRefBehavior(CS);
150   if (MRB == DoesNotAccessMemory)
151     return NoModRef;
152   
153   ModRefResult Mask = ModRef;
154   if (MRB == OnlyReadsMemory)
155     Mask = Ref;
156   else if (MRB == AliasAnalysis::AccessesArguments) {
157     bool doesAlias = false;
158     for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
159          AI != AE; ++AI)
160       if (!isNoAlias(*AI, ~0U, P, Size)) {
161         doesAlias = true;
162         break;
163       }
164
165     if (!doesAlias)
166       return NoModRef;
167   }
168
169   if (!AA) return Mask;
170
171   // If P points to a constant memory location, the call definitely could not
172   // modify the memory location.
173   if ((Mask & Mod) && AA->pointsToConstantMemory(P))
174     Mask = ModRefResult(Mask & ~Mod);
175
176   return ModRefResult(Mask & AA->getModRefInfo(CS, P, Size));
177 }
178
179 // AliasAnalysis destructor: DO NOT move this to the header file for
180 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
181 // the AliasAnalysis.o file in the current .a file, causing alias analysis
182 // support to not be included in the tool correctly!
183 //
184 AliasAnalysis::~AliasAnalysis() {}
185
186 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
187 /// AliasAnalysis interface before any other methods are called.
188 ///
189 void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
190   TD = P->getAnalysisIfAvailable<TargetData>();
191   AA = &P->getAnalysis<AliasAnalysis>();
192 }
193
194 // getAnalysisUsage - All alias analysis implementations should invoke this
195 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
196 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
197   AU.addRequired<AliasAnalysis>();         // All AA's chain
198 }
199
200 /// getTypeStoreSize - Return the TargetData store size for the given type,
201 /// if known, or a conservative value otherwise.
202 ///
203 unsigned AliasAnalysis::getTypeStoreSize(const Type *Ty) {
204   return TD ? TD->getTypeStoreSize(Ty) : ~0u;
205 }
206
207 /// canBasicBlockModify - Return true if it is possible for execution of the
208 /// specified basic block to modify the value pointed to by Ptr.
209 ///
210 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
211                                         const Value *Ptr, unsigned Size) {
212   return canInstructionRangeModify(BB.front(), BB.back(), Ptr, Size);
213 }
214
215 /// canInstructionRangeModify - Return true if it is possible for the execution
216 /// of the specified instructions to modify the value pointed to by Ptr.  The
217 /// instructions to consider are all of the instructions in the range of [I1,I2]
218 /// INCLUSIVE.  I1 and I2 must be in the same basic block.
219 ///
220 bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
221                                               const Instruction &I2,
222                                               const Value *Ptr, unsigned Size) {
223   assert(I1.getParent() == I2.getParent() &&
224          "Instructions not in same basic block!");
225   BasicBlock::const_iterator I = &I1;
226   BasicBlock::const_iterator E = &I2;
227   ++E;  // Convert from inclusive to exclusive range.
228
229   for (; I != E; ++I) // Check every instruction in range
230     if (getModRefInfo(I, Ptr, Size) & Mod)
231       return true;
232   return false;
233 }
234
235 /// isNoAliasCall - Return true if this pointer is returned by a noalias
236 /// function.
237 bool llvm::isNoAliasCall(const Value *V) {
238   if (isa<CallInst>(V) || isa<InvokeInst>(V))
239     return ImmutableCallSite(cast<Instruction>(V))
240       .paramHasAttr(0, Attribute::NoAlias);
241   return false;
242 }
243
244 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
245 /// identifiable object.  This returns true for:
246 ///    Global Variables and Functions (but not Global Aliases)
247 ///    Allocas and Mallocs
248 ///    ByVal and NoAlias Arguments
249 ///    NoAlias returns
250 ///
251 bool llvm::isIdentifiedObject(const Value *V) {
252   if (isa<AllocaInst>(V))
253     return true;
254   if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
255     return true;
256   if (isNoAliasCall(V))
257     return true;
258   if (const Argument *A = dyn_cast<Argument>(V))
259     return A->hasNoAliasAttr() || A->hasByValAttr();
260   return false;
261 }
262
263 // Because of the way .a files work, we must force the BasicAA implementation to
264 // be pulled in if the AliasAnalysis classes are pulled in.  Otherwise we run
265 // the risk of AliasAnalysis being used, but the default implementation not
266 // being linked into the tool that uses it.
267 DEFINING_FILE_FOR(AliasAnalysis)