Implement getModRefBehavior for TypeBasedAliasAnalysis.
[oota-llvm.git] / lib / Analysis / TypeBasedAliasAnalysis.cpp
1 //===- TypeBasedAliasAnalysis.cpp - Type-Based Alias Analysis -------------===//
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 defines the TypeBasedAliasAnalysis pass, which implements
11 // metadata-based TBAA.
12 //
13 // In LLVM IR, memory does not have types, so LLVM's own type system is not
14 // suitable for doing TBAA. Instead, metadata is added to the IR to describe
15 // a type system of a higher level language. This can be used to implement
16 // typical C/C++ TBAA, but it can also be used to implement custom alias
17 // analysis behavior for other languages.
18 //
19 // The current metadata format is very simple. TBAA MDNodes have up to
20 // three fields, e.g.:
21 //   !0 = metadata !{ metadata !"an example type tree" }
22 //   !1 = metadata !{ metadata !"int", metadata !0 }
23 //   !2 = metadata !{ metadata !"float", metadata !0 }
24 //   !3 = metadata !{ metadata !"const float", metadata !2, i64 1 }
25 //
26 // The first field is an identity field. It can be any value, usually
27 // an MDString, which uniquely identifies the type. The most important
28 // name in the tree is the name of the root node. Two trees with
29 // different root node names are entirely disjoint, even if they
30 // have leaves with common names.
31 //
32 // The second field identifies the type's parent node in the tree, or
33 // is null or omitted for a root node. A type is considered to alias
34 // all of its decendents and all of its ancestors in the tree. Also,
35 // a type is considered to alias all types in other trees, so that
36 // bitcode produced from multiple front-ends is handled conservatively.
37 //
38 // If the third field is present, it's an integer which if equal to 1
39 // indicates that the type is "constant" (meaning pointsToConstantMemory
40 // should return true; see
41 // http://llvm.org/docs/AliasAnalysis.html#OtherItfs).
42 //
43 // TODO: The current metadata format doesn't support struct
44 // fields. For example:
45 //   struct X {
46 //     double d;
47 //     int i;
48 //   };
49 //   void foo(struct X *x, struct X *y, double *p) {
50 //     *x = *y;
51 //     *p = 0.0;
52 //   }
53 // Struct X has a double member, so the store to *x can alias the store to *p.
54 // Currently it's not possible to precisely describe all the things struct X
55 // aliases, so struct assignments must use conservative TBAA nodes. There's
56 // no scheme for attaching metadata to @llvm.memcpy yet either.
57 //
58 //===----------------------------------------------------------------------===//
59
60 #include "llvm/Analysis/AliasAnalysis.h"
61 #include "llvm/Analysis/Passes.h"
62 #include "llvm/LLVMContext.h"
63 #include "llvm/Module.h"
64 #include "llvm/Metadata.h"
65 #include "llvm/Pass.h"
66 #include "llvm/Support/CommandLine.h"
67 using namespace llvm;
68
69 // For testing purposes, enable TBAA only via a special option.
70 static cl::opt<bool> EnableTBAA("enable-tbaa");
71
72 namespace {
73   /// TBAANode - This is a simple wrapper around an MDNode which provides a
74   /// higher-level interface by hiding the details of how alias analysis
75   /// information is encoded in its operands.
76   class TBAANode {
77     const MDNode *Node;
78
79   public:
80     TBAANode() : Node(0) {}
81     explicit TBAANode(const MDNode *N) : Node(N) {}
82
83     /// getNode - Get the MDNode for this TBAANode.
84     const MDNode *getNode() const { return Node; }
85
86     /// getParent - Get this TBAANode's Alias tree parent.
87     TBAANode getParent() const {
88       if (Node->getNumOperands() < 2)
89         return TBAANode();
90       MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
91       if (!P)
92         return TBAANode();
93       // Ok, this node has a valid parent. Return it.
94       return TBAANode(P);
95     }
96
97     /// TypeIsImmutable - Test if this TBAANode represents a type for objects
98     /// which are not modified (by any means) in the context where this
99     /// AliasAnalysis is relevant.
100     bool TypeIsImmutable() const {
101       if (Node->getNumOperands() < 3)
102         return false;
103       ConstantInt *CI = dyn_cast<ConstantInt>(Node->getOperand(2));
104       if (!CI)
105         return false;
106       return CI->getValue()[0];
107     }
108   };
109 }
110
111 namespace {
112   /// TypeBasedAliasAnalysis - This is a simple alias analysis
113   /// implementation that uses TypeBased to answer queries.
114   class TypeBasedAliasAnalysis : public ImmutablePass,
115                                  public AliasAnalysis {
116   public:
117     static char ID; // Class identification, replacement for typeinfo
118     TypeBasedAliasAnalysis() : ImmutablePass(ID) {
119       initializeTypeBasedAliasAnalysisPass(*PassRegistry::getPassRegistry());
120     }
121
122     virtual void initializePass() {
123       InitializeAliasAnalysis(this);
124     }
125
126     /// getAdjustedAnalysisPointer - This method is used when a pass implements
127     /// an analysis interface through multiple inheritance.  If needed, it
128     /// should override this to adjust the this pointer as needed for the
129     /// specified pass info.
130     virtual void *getAdjustedAnalysisPointer(const void *PI) {
131       if (PI == &AliasAnalysis::ID)
132         return (AliasAnalysis*)this;
133       return this;
134     }
135
136     bool Aliases(const MDNode *A, const MDNode *B) const;
137
138   private:
139     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
140     virtual AliasResult alias(const Location &LocA, const Location &LocB);
141     virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
142     virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
143     virtual ModRefBehavior getModRefBehavior(const Function *F);
144     virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
145                                        const Location &Loc);
146     virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
147                                        ImmutableCallSite CS2);
148   };
149 }  // End of anonymous namespace
150
151 // Register this pass...
152 char TypeBasedAliasAnalysis::ID = 0;
153 INITIALIZE_AG_PASS(TypeBasedAliasAnalysis, AliasAnalysis, "tbaa",
154                    "Type-Based Alias Analysis", false, true, false)
155
156 ImmutablePass *llvm::createTypeBasedAliasAnalysisPass() {
157   return new TypeBasedAliasAnalysis();
158 }
159
160 void
161 TypeBasedAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
162   AU.setPreservesAll();
163   AliasAnalysis::getAnalysisUsage(AU);
164 }
165
166 /// Aliases - Test whether the type represented by A may alias the
167 /// type represented by B.
168 bool
169 TypeBasedAliasAnalysis::Aliases(const MDNode *A,
170                                 const MDNode *B) const {
171   // Keep track of the root node for A and B.
172   TBAANode RootA, RootB;
173
174   // Climb the tree from A to see if we reach B.
175   for (TBAANode T(A); ; ) {
176     if (T.getNode() == B)
177       // B is an ancestor of A.
178       return true;
179
180     RootA = T;
181     T = T.getParent();
182     if (!T.getNode())
183       break;
184   }
185
186   // Climb the tree from B to see if we reach A.
187   for (TBAANode T(B); ; ) {
188     if (T.getNode() == A)
189       // A is an ancestor of B.
190       return true;
191
192     RootB = T;
193     T = T.getParent();
194     if (!T.getNode())
195       break;
196   }
197
198   // Neither node is an ancestor of the other.
199   
200   // If they have different roots, they're part of different potentially
201   // unrelated type systems, so we must be conservative.
202   if (RootA.getNode() != RootB.getNode())
203     return true;
204
205   // If they have the same root, then we've proved there's no alias.
206   return false;
207 }
208
209 AliasAnalysis::AliasResult
210 TypeBasedAliasAnalysis::alias(const Location &LocA,
211                               const Location &LocB) {
212   if (!EnableTBAA)
213     return AliasAnalysis::alias(LocA, LocB);
214
215   // Get the attached MDNodes. If either value lacks a tbaa MDNode, we must
216   // be conservative.
217   const MDNode *AM = LocA.TBAATag;
218   if (!AM) return AliasAnalysis::alias(LocA, LocB);
219   const MDNode *BM = LocB.TBAATag;
220   if (!BM) return AliasAnalysis::alias(LocA, LocB);
221
222   // If they may alias, chain to the next AliasAnalysis.
223   if (Aliases(AM, BM))
224     return AliasAnalysis::alias(LocA, LocB);
225
226   // Otherwise return a definitive result.
227   return NoAlias;
228 }
229
230 bool TypeBasedAliasAnalysis::pointsToConstantMemory(const Location &Loc,
231                                                     bool OrLocal) {
232   if (!EnableTBAA)
233     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
234
235   const MDNode *M = Loc.TBAATag;
236   if (!M) return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
237
238   // If this is an "immutable" type, we can assume the pointer is pointing
239   // to constant memory.
240   if (TBAANode(M).TypeIsImmutable())
241     return true;
242
243   return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
244 }
245
246 AliasAnalysis::ModRefBehavior
247 TypeBasedAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
248   if (!EnableTBAA)
249     return AliasAnalysis::getModRefBehavior(CS);
250
251   ModRefBehavior Min = UnknownModRefBehavior;
252
253   // If this is an "immutable" type, we can assume the call doesn't write
254   // to memory.
255   if (const MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
256     if (TBAANode(M).TypeIsImmutable())
257       Min = OnlyReadsMemory;
258
259   return std::min(AliasAnalysis::getModRefBehavior(CS), Min);
260 }
261
262 AliasAnalysis::ModRefBehavior
263 TypeBasedAliasAnalysis::getModRefBehavior(const Function *F) {
264   return AliasAnalysis::getModRefBehavior(F);
265 }
266
267 AliasAnalysis::ModRefResult
268 TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
269                                       const Location &Loc) {
270   if (!EnableTBAA)
271     return AliasAnalysis::getModRefInfo(CS, Loc);
272
273   if (const MDNode *L = Loc.TBAATag)
274     if (const MDNode *M =
275           CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
276       if (!Aliases(L, M))
277         return NoModRef;
278
279   return AliasAnalysis::getModRefInfo(CS, Loc);
280 }
281
282 AliasAnalysis::ModRefResult
283 TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
284                                       ImmutableCallSite CS2) {
285   if (!EnableTBAA)
286     return AliasAnalysis::getModRefInfo(CS1, CS2);
287
288   if (const MDNode *M1 =
289         CS1.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
290     if (const MDNode *M2 =
291           CS2.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
292       if (!Aliases(M1, M2))
293         return NoModRef;
294
295   return AliasAnalysis::getModRefInfo(CS1, CS2);
296 }