Struct-path aware TBAA: update getMostGenericTBAA
[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 descendants 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/Passes.h"
61 #include "llvm/Analysis/AliasAnalysis.h"
62 #include "llvm/IR/Constants.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/IR/Metadata.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/Pass.h"
67 #include "llvm/Support/CommandLine.h"
68 using namespace llvm;
69
70 // A handy option for disabling TBAA functionality. The same effect can also be
71 // achieved by stripping the !tbaa tags from IR, but this option is sometimes
72 // more convenient.
73 static cl::opt<bool> EnableTBAA("enable-tbaa", cl::init(true));
74 static cl::opt<bool> EnableStructPathTBAA("struct-path-tbaa", cl::init(false));
75
76 namespace {
77   /// TBAANode - This is a simple wrapper around an MDNode which provides a
78   /// higher-level interface by hiding the details of how alias analysis
79   /// information is encoded in its operands.
80   class TBAANode {
81     const MDNode *Node;
82
83   public:
84     TBAANode() : Node(0) {}
85     explicit TBAANode(const MDNode *N) : Node(N) {}
86
87     /// getNode - Get the MDNode for this TBAANode.
88     const MDNode *getNode() const { return Node; }
89
90     /// getParent - Get this TBAANode's Alias tree parent.
91     TBAANode getParent() const {
92       if (Node->getNumOperands() < 2)
93         return TBAANode();
94       MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
95       if (!P)
96         return TBAANode();
97       // Ok, this node has a valid parent. Return it.
98       return TBAANode(P);
99     }
100
101     /// TypeIsImmutable - Test if this TBAANode represents a type for objects
102     /// which are not modified (by any means) in the context where this
103     /// AliasAnalysis is relevant.
104     bool TypeIsImmutable() const {
105       if (Node->getNumOperands() < 3)
106         return false;
107       ConstantInt *CI = dyn_cast<ConstantInt>(Node->getOperand(2));
108       if (!CI)
109         return false;
110       return CI->getValue()[0];
111     }
112   };
113
114   /// This is a simple wrapper around an MDNode which provides a
115   /// higher-level interface by hiding the details of how alias analysis
116   /// information is encoded in its operands.
117   class TBAAStructTagNode {
118     /// This node should be created with createTBAAStructTagNode.
119     const MDNode *Node;
120
121   public:
122     TBAAStructTagNode() : Node(0) {}
123     explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
124
125     /// Get the MDNode for this TBAAStructTagNode.
126     const MDNode *getNode() const { return Node; }
127
128     const MDNode *getBaseType() const {
129       return dyn_cast_or_null<MDNode>(Node->getOperand(0));
130     }
131     const MDNode *getAccessType() const {
132       return dyn_cast_or_null<MDNode>(Node->getOperand(1));
133     }
134     uint64_t getOffset() const {
135       return cast<ConstantInt>(Node->getOperand(2))->getZExtValue();
136     }
137   };
138
139   /// This is a simple wrapper around an MDNode which provides a
140   /// higher-level interface by hiding the details of how alias analysis
141   /// information is encoded in its operands.
142   class TBAAStructTypeNode {
143     /// This node should be created with createTBAAStructTypeNode.
144     const MDNode *Node;
145
146   public:
147     TBAAStructTypeNode() : Node(0) {}
148     explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
149
150     /// Get the MDNode for this TBAAStructTypeNode.
151     const MDNode *getNode() const { return Node; }
152
153     /// Get this TBAAStructTypeNode's field in the type DAG with
154     /// given offset. Update the offset to be relative to the field type.
155     TBAAStructTypeNode getParent(uint64_t &Offset) const {
156       if (Node->getNumOperands() < 2)
157         return TBAAStructTypeNode();
158
159       // Assume the offsets are in order. We return the previous field if
160       // the current offset is bigger than the given offset.
161       unsigned TheIdx = 0;
162       for (unsigned Idx = 1; Idx < Node->getNumOperands(); Idx += 2) {
163         uint64_t Cur = cast<ConstantInt>(Node->getOperand(Idx))->getZExtValue();
164         if (Cur > Offset) {
165           assert(Idx >= 3 &&
166                  "TBAAStructTypeNode::getParent should have an offset match!");
167           TheIdx = Idx - 2;
168           break;
169         }
170       }
171       // Move along the last field.
172       if (TheIdx == 0)
173         TheIdx = Node->getNumOperands() - 2;
174       uint64_t Cur = cast<ConstantInt>(Node->getOperand(TheIdx))->
175                        getZExtValue();
176       Offset -= Cur;
177       MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(TheIdx + 1));
178       if (!P)
179         return TBAAStructTypeNode();
180       return TBAAStructTypeNode(P);
181     }
182   };
183 }
184
185 namespace {
186   /// TypeBasedAliasAnalysis - This is a simple alias analysis
187   /// implementation that uses TypeBased to answer queries.
188   class TypeBasedAliasAnalysis : public ImmutablePass,
189                                  public AliasAnalysis {
190   public:
191     static char ID; // Class identification, replacement for typeinfo
192     TypeBasedAliasAnalysis() : ImmutablePass(ID) {
193       initializeTypeBasedAliasAnalysisPass(*PassRegistry::getPassRegistry());
194     }
195
196     virtual void initializePass() {
197       InitializeAliasAnalysis(this);
198     }
199
200     /// getAdjustedAnalysisPointer - This method is used when a pass implements
201     /// an analysis interface through multiple inheritance.  If needed, it
202     /// should override this to adjust the this pointer as needed for the
203     /// specified pass info.
204     virtual void *getAdjustedAnalysisPointer(const void *PI) {
205       if (PI == &AliasAnalysis::ID)
206         return (AliasAnalysis*)this;
207       return this;
208     }
209
210     bool Aliases(const MDNode *A, const MDNode *B) const;
211     bool PathAliases(const MDNode *A, const MDNode *B) const;
212
213   private:
214     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
215     virtual AliasResult alias(const Location &LocA, const Location &LocB);
216     virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
217     virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
218     virtual ModRefBehavior getModRefBehavior(const Function *F);
219     virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
220                                        const Location &Loc);
221     virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
222                                        ImmutableCallSite CS2);
223   };
224 }  // End of anonymous namespace
225
226 // Register this pass...
227 char TypeBasedAliasAnalysis::ID = 0;
228 INITIALIZE_AG_PASS(TypeBasedAliasAnalysis, AliasAnalysis, "tbaa",
229                    "Type-Based Alias Analysis", false, true, false)
230
231 ImmutablePass *llvm::createTypeBasedAliasAnalysisPass() {
232   return new TypeBasedAliasAnalysis();
233 }
234
235 void
236 TypeBasedAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
237   AU.setPreservesAll();
238   AliasAnalysis::getAnalysisUsage(AU);
239 }
240
241 /// Aliases - Test whether the type represented by A may alias the
242 /// type represented by B.
243 bool
244 TypeBasedAliasAnalysis::Aliases(const MDNode *A,
245                                 const MDNode *B) const {
246   if (EnableStructPathTBAA)
247     return PathAliases(A, B);
248
249   // Keep track of the root node for A and B.
250   TBAANode RootA, RootB;
251
252   // Climb the tree from A to see if we reach B.
253   for (TBAANode T(A); ; ) {
254     if (T.getNode() == B)
255       // B is an ancestor of A.
256       return true;
257
258     RootA = T;
259     T = T.getParent();
260     if (!T.getNode())
261       break;
262   }
263
264   // Climb the tree from B to see if we reach A.
265   for (TBAANode T(B); ; ) {
266     if (T.getNode() == A)
267       // A is an ancestor of B.
268       return true;
269
270     RootB = T;
271     T = T.getParent();
272     if (!T.getNode())
273       break;
274   }
275
276   // Neither node is an ancestor of the other.
277   
278   // If they have different roots, they're part of different potentially
279   // unrelated type systems, so we must be conservative.
280   if (RootA.getNode() != RootB.getNode())
281     return true;
282
283   // If they have the same root, then we've proved there's no alias.
284   return false;
285 }
286
287 /// Test whether the struct-path tag represented by A may alias the
288 /// struct-path tag represented by B.
289 bool
290 TypeBasedAliasAnalysis::PathAliases(const MDNode *A,
291                                     const MDNode *B) const {
292   // Keep track of the root node for A and B.
293   TBAAStructTypeNode RootA, RootB;
294   TBAAStructTagNode TagA(A), TagB(B);
295
296   // TODO: We need to check if AccessType of TagA encloses AccessType of
297   // TagB to support aggregate AccessType. If yes, return true.
298
299   // Start from the base type of A, follow the edge with the correct offset in
300   // the type DAG and adjust the offset until we reach the base type of B or
301   // until we reach the Root node.
302   // Compare the adjusted offset once we have the same base.
303
304   // Climb the type DAG from base type of A to see if we reach base type of B.
305   const MDNode *BaseA = TagA.getBaseType();
306   const MDNode *BaseB = TagB.getBaseType();
307   uint64_t OffsetA = TagA.getOffset(), OffsetB = TagB.getOffset();
308   for (TBAAStructTypeNode T(BaseA); ; ) {
309     if (T.getNode() == BaseB)
310       // Base type of A encloses base type of B, check if the offsets match.
311       return OffsetA == OffsetB;
312
313     RootA = T;
314     // Follow the edge with the correct offset, OffsetA will be adjusted to
315     // be relative to the field type.
316     T = T.getParent(OffsetA);
317     if (!T.getNode())
318       break;
319   }
320
321   // Reset OffsetA and climb the type DAG from base type of B to see if we reach
322   // base type of A.
323   OffsetA = TagA.getOffset();
324   for (TBAAStructTypeNode T(BaseB); ; ) {
325     if (T.getNode() == BaseA)
326       // Base type of B encloses base type of A, check if the offsets match.
327       return OffsetA == OffsetB;
328
329     RootB = T;
330     // Follow the edge with the correct offset, OffsetB will be adjusted to
331     // be relative to the field type.
332     T = T.getParent(OffsetB);
333     if (!T.getNode())
334       break;
335   }
336
337   // Neither node is an ancestor of the other.
338
339   // If they have different roots, they're part of different potentially
340   // unrelated type systems, so we must be conservative.
341   if (RootA.getNode() != RootB.getNode())
342     return true;
343
344   // If they have the same root, then we've proved there's no alias.
345   return false;
346 }
347
348 AliasAnalysis::AliasResult
349 TypeBasedAliasAnalysis::alias(const Location &LocA,
350                               const Location &LocB) {
351   if (!EnableTBAA)
352     return AliasAnalysis::alias(LocA, LocB);
353
354   // Get the attached MDNodes. If either value lacks a tbaa MDNode, we must
355   // be conservative.
356   const MDNode *AM = LocA.TBAATag;
357   if (!AM) return AliasAnalysis::alias(LocA, LocB);
358   const MDNode *BM = LocB.TBAATag;
359   if (!BM) return AliasAnalysis::alias(LocA, LocB);
360
361   // If they may alias, chain to the next AliasAnalysis.
362   if (Aliases(AM, BM))
363     return AliasAnalysis::alias(LocA, LocB);
364
365   // Otherwise return a definitive result.
366   return NoAlias;
367 }
368
369 bool TypeBasedAliasAnalysis::pointsToConstantMemory(const Location &Loc,
370                                                     bool OrLocal) {
371   if (!EnableTBAA)
372     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
373
374   const MDNode *M = Loc.TBAATag;
375   if (!M) return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
376
377   // If this is an "immutable" type, we can assume the pointer is pointing
378   // to constant memory.
379   if (!EnableStructPathTBAA && TBAANode(M).TypeIsImmutable())
380     return true;
381
382   return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
383 }
384
385 AliasAnalysis::ModRefBehavior
386 TypeBasedAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
387   if (!EnableTBAA)
388     return AliasAnalysis::getModRefBehavior(CS);
389
390   ModRefBehavior Min = UnknownModRefBehavior;
391
392   // If this is an "immutable" type, we can assume the call doesn't write
393   // to memory.
394   if (const MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
395     if (!EnableStructPathTBAA && TBAANode(M).TypeIsImmutable())
396       Min = OnlyReadsMemory;
397
398   return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
399 }
400
401 AliasAnalysis::ModRefBehavior
402 TypeBasedAliasAnalysis::getModRefBehavior(const Function *F) {
403   // Functions don't have metadata. Just chain to the next implementation.
404   return AliasAnalysis::getModRefBehavior(F);
405 }
406
407 AliasAnalysis::ModRefResult
408 TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
409                                       const Location &Loc) {
410   if (!EnableTBAA)
411     return AliasAnalysis::getModRefInfo(CS, Loc);
412
413   if (const MDNode *L = Loc.TBAATag)
414     if (const MDNode *M =
415           CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
416       if (!Aliases(L, M))
417         return NoModRef;
418
419   return AliasAnalysis::getModRefInfo(CS, Loc);
420 }
421
422 AliasAnalysis::ModRefResult
423 TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
424                                       ImmutableCallSite CS2) {
425   if (!EnableTBAA)
426     return AliasAnalysis::getModRefInfo(CS1, CS2);
427
428   if (const MDNode *M1 =
429         CS1.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
430     if (const MDNode *M2 =
431           CS2.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
432       if (!Aliases(M1, M2))
433         return NoModRef;
434
435   return AliasAnalysis::getModRefInfo(CS1, CS2);
436 }
437
438 MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
439   if (!A || !B)
440     return NULL;
441
442   if (A == B)
443     return A;
444
445   // For struct-path aware TBAA, we use the access type of the tag.
446   if (EnableStructPathTBAA) {
447     A = cast_or_null<MDNode>(A->getOperand(1));
448     if (!A) return 0;
449     B = cast_or_null<MDNode>(B->getOperand(1));
450     if (!B) return 0;
451   }
452
453   SmallVector<MDNode *, 4> PathA;
454   MDNode *T = A;
455   while (T) {
456     PathA.push_back(T);
457     if (EnableStructPathTBAA)
458       T = T->getNumOperands() >= 3 ? cast_or_null<MDNode>(T->getOperand(2)) : 0;
459     else
460       T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
461   }
462
463   SmallVector<MDNode *, 4> PathB;
464   T = B;
465   while (T) {
466     PathB.push_back(T);
467     if (EnableStructPathTBAA)
468       T = T->getNumOperands() >= 3 ? cast_or_null<MDNode>(T->getOperand(2)) : 0;
469     else
470       T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
471   }
472
473   int IA = PathA.size() - 1;
474   int IB = PathB.size() - 1;
475
476   MDNode *Ret = 0;
477   while (IA >= 0 && IB >=0) {
478     if (PathA[IA] == PathB[IB])
479       Ret = PathA[IA];
480     else
481       break;
482     --IA;
483     --IB;
484   }
485   if (!EnableStructPathTBAA)
486     return Ret;
487
488   if (!Ret)
489     return 0;
490   // We need to convert from a type node to a tag node.
491   Type *Int64 = IntegerType::get(A->getContext(), 64);
492   Value *Ops[3] = { Ret, Ret, ConstantInt::get(Int64, 0) };
493   return MDNode::get(A->getContext(), Ops);
494 }