57867dd6eedd5466949419308d1fb1b0e0aeb907
[oota-llvm.git] / lib / Analysis / AliasAnalysis.cpp
1 //===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==//
2 //
3 // This file implements the generic AliasAnalysis interface which is used as the
4 // common interface used by all clients and implementations of alias analysis.
5 //
6 // This file also implements the default version of the AliasAnalysis interface
7 // that is to be used when no other implementation is specified.  This does some
8 // simple tests that detect obvious cases: two different global pointers cannot
9 // alias, a global cannot alias a malloc, two different mallocs cannot alias,
10 // etc.
11 //
12 // This alias analysis implementation really isn't very good for anything, but
13 // it is very fast, and makes a nice clean default implementation.  Because it
14 // handles lots of little corner cases, other, more complex, alias analysis
15 // implementations may choose to rely on this pass to resolve these simple and
16 // easy cases.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "llvm/Analysis/BasicAliasAnalysis.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/iMemory.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Constants.h"
26 #include "llvm/GlobalValue.h"
27 #include "llvm/DerivedTypes.h"
28
29 // Register the AliasAnalysis interface, providing a nice name to refer to.
30 namespace {
31   RegisterAnalysisGroup<AliasAnalysis> Z("Alias Analysis");
32 }
33
34 // CanModify - Define a little visitor class that is used to check to see if
35 // arbitrary chunks of code can modify a specified pointer.
36 //
37 namespace {
38   struct CanModify : public InstVisitor<CanModify, bool> {
39     AliasAnalysis &AA;
40     const Value *Ptr;
41
42     CanModify(AliasAnalysis *aa, const Value *ptr)
43       : AA(*aa), Ptr(ptr) {}
44
45     bool visitInvokeInst(InvokeInst &II) {
46       return AA.canInvokeModify(II, Ptr);
47     }
48     bool visitCallInst(CallInst &CI) {
49       return AA.canCallModify(CI, Ptr);
50     }
51     bool visitStoreInst(StoreInst &SI) {
52       return AA.alias(Ptr, SI.getOperand(1));
53     }
54
55     // Other instructions do not alias anything.
56     bool visitInstruction(Instruction &I) { return false; }
57   };
58 }
59
60 // AliasAnalysis destructor: DO NOT move this to the header file for
61 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
62 // the AliasAnalysis.o file in the current .a file, causing alias analysis
63 // support to not be included in the tool correctly!
64 //
65 AliasAnalysis::~AliasAnalysis() {}
66
67 /// canBasicBlockModify - Return true if it is possible for execution of the
68 /// specified basic block to modify the value pointed to by Ptr.
69 ///
70 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &bb,
71                                         const Value *Ptr) {
72   CanModify CM(this, Ptr);
73   BasicBlock &BB = const_cast<BasicBlock&>(bb);
74
75   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
76     if (CM.visit(I))        // Check every instruction in the basic block...
77       return true;
78
79   return false;
80 }
81
82 /// canInstructionRangeModify - Return true if it is possible for the execution
83 /// of the specified instructions to modify the value pointed to by Ptr.  The
84 /// instructions to consider are all of the instructions in the range of [I1,I2]
85 /// INCLUSIVE.  I1 and I2 must be in the same basic block.
86 ///
87 bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
88                                               const Instruction &I2,
89                                               const Value *Ptr) {
90   assert(I1.getParent() == I2.getParent() &&
91          "Instructions not in same basic block!");
92   CanModify CM(this, Ptr);
93   BasicBlock::iterator I = const_cast<Instruction*>(&I1);
94   BasicBlock::iterator E = const_cast<Instruction*>(&I2);
95   ++E;  // Convert from inclusive to exclusive range.
96
97   for (; I != E; ++I)
98     if (CM.visit(I))        // Check every instruction in the basic block...
99       return true;
100
101   return false;
102 }
103
104 //===----------------------------------------------------------------------===//
105 // BasicAliasAnalysis Pass Implementation
106 //===----------------------------------------------------------------------===//
107 //
108 // Because of the way .a files work, the implementation of the
109 // BasicAliasAnalysis class MUST be in the AliasAnalysis file itself, or else we
110 // run the risk of AliasAnalysis being used, but the default implementation not
111 // being linked into the tool that uses it.  As such, we register and implement
112 // the class here.
113 //
114 namespace {
115   // Register this pass...
116   RegisterOpt<BasicAliasAnalysis>
117   X("basicaa", "Basic Alias Analysis (default AA impl)");
118
119   // Declare that we implement the AliasAnalysis interface
120   RegisterAnalysisGroup<AliasAnalysis, BasicAliasAnalysis, true> Y;
121 }  // End of anonymous namespace
122
123
124
125 // hasUniqueAddress - Return true if the 
126 static inline bool hasUniqueAddress(const Value *V) {
127   return isa<GlobalValue>(V) || isa<MallocInst>(V) || isa<AllocaInst>(V);
128 }
129
130 static const Value *getUnderlyingObject(const Value *V) {
131   if (!isa<PointerType>(V->getType())) return 0;
132
133   // If we are at some type of object... return it.
134   if (hasUniqueAddress(V)) return V;
135   
136   // Traverse through different addressing mechanisms...
137   if (const Instruction *I = dyn_cast<Instruction>(V)) {
138     if (isa<CastInst>(I) || isa<GetElementPtrInst>(I))
139       return getUnderlyingObject(I->getOperand(0));
140   }
141   return 0;
142 }
143
144
145 // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such
146 // as array references.  Note that this function is heavily tail recursive.
147 // Hopefully we have a smart C++ compiler.  :)
148 //
149 AliasAnalysis::Result BasicAliasAnalysis::alias(const Value *V1,
150                                                 const Value *V2) {
151   // Strip off constant pointer refs if they exist
152   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V1))
153     V1 = CPR->getValue();
154   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V2))
155     V2 = CPR->getValue();
156
157   // Are we checking for alias of the same value?
158   if (V1 == V2) return MustAlias;
159
160   if ((!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType())) &&
161       V1->getType() != Type::LongTy && V2->getType() != Type::LongTy)
162     return NoAlias;  // Scalars cannot alias each other
163
164   // Strip off cast instructions...
165   if (const Instruction *I = dyn_cast<CastInst>(V1))
166     return alias(I->getOperand(0), V2);
167   if (const Instruction *I = dyn_cast<CastInst>(V2))
168     return alias(V1, I->getOperand(0));
169
170   // If we have two gep instructions with identical indices, return an alias
171   // result equal to the alias result of the original pointer...
172   //
173   if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(V1))
174     if (const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(V2))
175       if (GEP1->getNumOperands() == GEP2->getNumOperands() &&
176           GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType()) {
177         if (std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
178           return alias(GEP1->getOperand(0), GEP2->getOperand(0));
179
180         // If all of the indexes to the getelementptr are constant, but
181         // different (well we already know they are different), then we know
182         // that there cannot be an alias here if the two base pointers DO alias.
183         //
184         bool AllConstant = true;
185         for (unsigned i = 1, e = GEP1->getNumOperands(); i != e; ++i)
186           if (!isa<Constant>(GEP1->getOperand(i)) ||
187               !isa<Constant>(GEP2->getOperand(i))) {
188             AllConstant = false;
189             break;
190           }
191
192         // If we are all constant, then look at where the the base pointers
193         // alias.  If they are known not to alias, then we are dealing with two
194         // different arrays or something, so no alias is possible.  If they are
195         // known to be the same object, then we cannot alias because we are
196         // indexing into a different part of the object.  As usual, MayAlias
197         // doesn't tell us anything.
198         //
199         if (AllConstant &&
200             alias(GEP1->getOperand(0), GEP2->getOperand(0)) != MayAlias)
201             return NoAlias;
202       }
203
204   // Figure out what objects these things are pointing to if we can...
205   const Value *O1 = getUnderlyingObject(V1);
206   const Value *O2 = getUnderlyingObject(V2);
207
208   // Pointing at a discernable object?
209   if (O1 && O2) {
210     // If they are two different objects, we know that we have no alias...
211     if (O1 != O2) return NoAlias;
212
213     // If they are the same object, they we can look at the indexes.  If they
214     // index off of the object is the same for both pointers, they must alias.
215     // If they are provably different, they must not alias.  Otherwise, we can't
216     // tell anything.
217   } else if (O1 && isa<ConstantPointerNull>(V2)) {
218     return NoAlias;                    // Unique values don't alias null
219   } else if (O2 && isa<ConstantPointerNull>(V1)) {
220     return NoAlias;                    // Unique values don't alias null
221   }
222
223   // Check to see if these two pointers are related by a getelementptr
224   // instruction.  If one pointer is a GEP with a non-zero index of the other
225   // pointer, we know they cannot alias.
226   //
227   if (isa<GetElementPtrInst>(V2))
228     std::swap(V1, V2);
229
230   if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V1))
231     if (GEP->getOperand(0) == V2) {
232       // If there is at least one non-zero constant index, we know they cannot
233       // alias.
234       for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
235         if (const Constant *C = dyn_cast<Constant>(GEP->getOperand(i)))
236           if (!C->isNullValue())
237             return NoAlias;
238     }
239
240   return MayAlias;
241 }