If a function only reads memory, then we know that...
[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 void AliasAnalysis::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
53   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
54   return AA->getMustAliases(P, RetVals);
55 }
56
57 bool AliasAnalysis::pointsToConstantMemory(const Value *P) {
58   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
59   return AA->pointsToConstantMemory(P);
60 }
61
62 bool AliasAnalysis::hasNoModRefInfoForCalls() const {
63   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
64   return AA->hasNoModRefInfoForCalls();
65 }
66
67 void AliasAnalysis::deleteValue(Value *V) {
68   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
69   AA->deleteValue(V);
70 }
71
72 void AliasAnalysis::copyValue(Value *From, Value *To) {
73   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
74   AA->copyValue(From, To);
75 }
76
77 AliasAnalysis::ModRefResult
78 AliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
79   // FIXME: we can do better.
80   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
81   return AA->getModRefInfo(CS1, CS2);
82 }
83
84
85 //===----------------------------------------------------------------------===//
86 // AliasAnalysis non-virtual helper method implementation
87 //===----------------------------------------------------------------------===//
88
89 AliasAnalysis::ModRefResult
90 AliasAnalysis::getModRefInfo(LoadInst *L, Value *P, unsigned Size) {
91   return alias(L->getOperand(0), TD->getTypeStoreSize(L->getType()),
92                P, Size) ? Ref : NoModRef;
93 }
94
95 AliasAnalysis::ModRefResult
96 AliasAnalysis::getModRefInfo(StoreInst *S, Value *P, unsigned Size) {
97   // If the stored address cannot alias the pointer in question, then the
98   // pointer cannot be modified by the store.
99   if (!alias(S->getOperand(1),
100              TD->getTypeStoreSize(S->getOperand(0)->getType()), P, Size))
101     return NoModRef;
102
103   // If the pointer is a pointer to constant memory, then it could not have been
104   // modified by this store.
105   return pointsToConstantMemory(P) ? NoModRef : Mod;
106 }
107
108 AliasAnalysis::ModRefBehavior
109 AliasAnalysis::getModRefBehavior(CallSite CS,
110                                  std::vector<PointerAccessInfo> *Info) {
111   if (CS.doesNotAccessMemory())
112     // Can't do better than this.
113     return DoesNotAccessMemory;
114   ModRefBehavior MRB = getModRefBehavior(CS.getCalledFunction(), Info);
115   if (MRB != DoesNotAccessMemory && CS.onlyReadsMemory())
116     return OnlyReadsMemory;
117   return MRB;
118 }
119
120 AliasAnalysis::ModRefBehavior
121 AliasAnalysis::getModRefBehavior(Function *F,
122                                  std::vector<PointerAccessInfo> *Info) {
123   if (F) {
124     if (F->doesNotAccessMemory())
125       // Can't do better than this.
126       return DoesNotAccessMemory;
127     else if (F->onlyReadsMemory())
128       return OnlyReadsMemory;
129   }
130   return UnknownModRefBehavior;
131 }
132
133 AliasAnalysis::ModRefResult
134 AliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
135   ModRefResult Mask = ModRef;
136   ModRefBehavior MRB = getModRefBehavior(CS);
137   if (MRB == DoesNotAccessMemory)
138     return NoModRef;
139   else if (MRB == OnlyReadsMemory)
140     Mask = Ref;
141   else if (MRB == AliasAnalysis::AccessesArguments) {
142     bool doesAlias = false;
143     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
144          AI != AE; ++AI)
145       if (alias(*AI, ~0U, P, Size) != NoAlias) {
146         doesAlias = true;
147         break;
148       }
149
150     if (!doesAlias)
151       return NoModRef;
152   }
153
154   if (!AA) return Mask;
155
156   // If P points to a constant memory location, the call definitely could not
157   // modify the memory location.
158   if ((Mask & Mod) && AA->pointsToConstantMemory(P))
159     Mask = ModRefResult(Mask & ~Mod);
160
161   return ModRefResult(Mask & AA->getModRefInfo(CS, P, Size));
162 }
163
164 // AliasAnalysis destructor: DO NOT move this to the header file for
165 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
166 // the AliasAnalysis.o file in the current .a file, causing alias analysis
167 // support to not be included in the tool correctly!
168 //
169 AliasAnalysis::~AliasAnalysis() {}
170
171 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
172 /// AliasAnalysis interface before any other methods are called.
173 ///
174 void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
175   TD = &P->getAnalysis<TargetData>();
176   AA = &P->getAnalysis<AliasAnalysis>();
177 }
178
179 // getAnalysisUsage - All alias analysis implementations should invoke this
180 // directly (using AliasAnalysis::getAnalysisUsage(AU)) to make sure that
181 // TargetData is required by the pass.
182 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
183   AU.addRequired<TargetData>();            // All AA's need TargetData.
184   AU.addRequired<AliasAnalysis>();         // All AA's chain
185 }
186
187 /// canBasicBlockModify - Return true if it is possible for execution of the
188 /// specified basic block to modify the value pointed to by Ptr.
189 ///
190 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
191                                         const Value *Ptr, unsigned Size) {
192   return canInstructionRangeModify(BB.front(), BB.back(), Ptr, Size);
193 }
194
195 /// canInstructionRangeModify - Return true if it is possible for the execution
196 /// of the specified instructions to modify the value pointed to by Ptr.  The
197 /// instructions to consider are all of the instructions in the range of [I1,I2]
198 /// INCLUSIVE.  I1 and I2 must be in the same basic block.
199 ///
200 bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
201                                               const Instruction &I2,
202                                               const Value *Ptr, unsigned Size) {
203   assert(I1.getParent() == I2.getParent() &&
204          "Instructions not in same basic block!");
205   BasicBlock::iterator I = const_cast<Instruction*>(&I1);
206   BasicBlock::iterator E = const_cast<Instruction*>(&I2);
207   ++E;  // Convert from inclusive to exclusive range.
208
209   for (; I != E; ++I) // Check every instruction in range
210     if (getModRefInfo(I, const_cast<Value*>(Ptr), Size) & Mod)
211       return true;
212   return false;
213 }
214
215 /// isNoAliasCall - Return true if this pointer is returned by a noalias
216 /// function.
217 bool llvm::isNoAliasCall(const Value *V) {
218   if (isa<CallInst>(V) || isa<InvokeInst>(V))
219     return CallSite(const_cast<Instruction*>(cast<Instruction>(V)))
220       .paramHasAttr(0, Attribute::NoAlias);
221   return false;
222 }
223
224 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
225 /// identifiable object.  This returns true for:
226 ///    Global Variables and Functions
227 ///    Allocas and Mallocs
228 ///    ByVal and NoAlias Arguments
229 ///    NoAlias returns
230 ///
231 bool llvm::isIdentifiedObject(const Value *V) {
232   if (isa<GlobalValue>(V) || isa<AllocationInst>(V) || isNoAliasCall(V))
233     return true;
234   if (const Argument *A = dyn_cast<Argument>(V))
235     return A->hasNoAliasAttr() || A->hasByValAttr();
236   return false;
237 }
238
239 // Because of the way .a files work, we must force the BasicAA implementation to
240 // be pulled in if the AliasAnalysis classes are pulled in.  Otherwise we run
241 // the risk of AliasAnalysis being used, but the default implementation not
242 // being linked into the tool that uses it.
243 DEFINING_FILE_FOR(AliasAnalysis)