1 //===- TypeBasedAliasAnalysis.cpp - Type-Based Alias Analysis -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the TypeBasedAliasAnalysis pass, which implements
11 // metadata-based TBAA.
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.
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 }
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.
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.
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).
43 // TODO: The current metadata format doesn't support struct
44 // fields. For example:
49 // void foo(struct X *x, struct X *y, double *p) {
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.
58 //===----------------------------------------------------------------------===//
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"
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
73 static cl::opt<bool> EnableTBAA("enable-tbaa", cl::init(true));
74 static cl::opt<bool> EnableStructPathTBAA("struct-path-tbaa", cl::init(false));
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.
84 TBAANode() : Node(0) {}
85 explicit TBAANode(const MDNode *N) : Node(N) {}
87 /// getNode - Get the MDNode for this TBAANode.
88 const MDNode *getNode() const { return Node; }
90 /// getParent - Get this TBAANode's Alias tree parent.
91 TBAANode getParent() const {
92 if (Node->getNumOperands() < 2)
94 MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
97 // Ok, this node has a valid parent. Return it.
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)
107 ConstantInt *CI = dyn_cast<ConstantInt>(Node->getOperand(2));
110 return CI->getValue()[0];
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.
122 TBAAStructTagNode() : Node(0) {}
123 explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
125 /// Get the MDNode for this TBAAStructTagNode.
126 const MDNode *getNode() const { return Node; }
128 const MDNode *getBaseType() const {
129 return dyn_cast_or_null<MDNode>(Node->getOperand(0));
131 const MDNode *getAccessType() const {
132 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
134 uint64_t getOffset() const {
135 return cast<ConstantInt>(Node->getOperand(2))->getZExtValue();
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.
147 TBAAStructTypeNode() : Node(0) {}
148 explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
150 /// Get the MDNode for this TBAAStructTypeNode.
151 const MDNode *getNode() const { return Node; }
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();
159 // Assume the offsets are in order. We return the previous field if
160 // the current offset is bigger than the given offset.
162 for (unsigned Idx = 1; Idx < Node->getNumOperands(); Idx += 2) {
163 uint64_t Cur = cast<ConstantInt>(Node->getOperand(Idx))->getZExtValue();
166 "TBAAStructTypeNode::getParent should have an offset match!");
171 // Move along the last field.
173 TheIdx = Node->getNumOperands() - 2;
174 uint64_t Cur = cast<ConstantInt>(Node->getOperand(TheIdx))->
177 MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(TheIdx + 1));
179 return TBAAStructTypeNode();
180 return TBAAStructTypeNode(P);
186 /// TypeBasedAliasAnalysis - This is a simple alias analysis
187 /// implementation that uses TypeBased to answer queries.
188 class TypeBasedAliasAnalysis : public ImmutablePass,
189 public AliasAnalysis {
191 static char ID; // Class identification, replacement for typeinfo
192 TypeBasedAliasAnalysis() : ImmutablePass(ID) {
193 initializeTypeBasedAliasAnalysisPass(*PassRegistry::getPassRegistry());
196 virtual void initializePass() {
197 InitializeAliasAnalysis(this);
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;
210 bool Aliases(const MDNode *A, const MDNode *B) const;
211 bool PathAliases(const MDNode *A, const MDNode *B) const;
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);
224 } // End of anonymous namespace
226 // Register this pass...
227 char TypeBasedAliasAnalysis::ID = 0;
228 INITIALIZE_AG_PASS(TypeBasedAliasAnalysis, AliasAnalysis, "tbaa",
229 "Type-Based Alias Analysis", false, true, false)
231 ImmutablePass *llvm::createTypeBasedAliasAnalysisPass() {
232 return new TypeBasedAliasAnalysis();
236 TypeBasedAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
237 AU.setPreservesAll();
238 AliasAnalysis::getAnalysisUsage(AU);
241 /// Aliases - Test whether the type represented by A may alias the
242 /// type represented by B.
244 TypeBasedAliasAnalysis::Aliases(const MDNode *A,
245 const MDNode *B) const {
246 if (EnableStructPathTBAA)
247 return PathAliases(A, B);
249 // Keep track of the root node for A and B.
250 TBAANode RootA, RootB;
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.
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.
276 // Neither node is an ancestor of the other.
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())
283 // If they have the same root, then we've proved there's no alias.
287 /// Test whether the struct-path tag represented by A may alias the
288 /// struct-path tag represented by B.
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);
296 // TODO: We need to check if AccessType of TagA encloses AccessType of
297 // TagB to support aggregate AccessType. If yes, return true.
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.
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;
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);
321 // Reset OffsetA and climb the type DAG from base type of B to see if we reach
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;
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);
337 // Neither node is an ancestor of the other.
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())
344 // If they have the same root, then we've proved there's no alias.
348 AliasAnalysis::AliasResult
349 TypeBasedAliasAnalysis::alias(const Location &LocA,
350 const Location &LocB) {
352 return AliasAnalysis::alias(LocA, LocB);
354 // Get the attached MDNodes. If either value lacks a tbaa MDNode, we must
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);
361 // If they may alias, chain to the next AliasAnalysis.
363 return AliasAnalysis::alias(LocA, LocB);
365 // Otherwise return a definitive result.
369 bool TypeBasedAliasAnalysis::pointsToConstantMemory(const Location &Loc,
372 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
374 const MDNode *M = Loc.TBAATag;
375 if (!M) return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
377 // If this is an "immutable" type, we can assume the pointer is pointing
378 // to constant memory.
379 if (!EnableStructPathTBAA && TBAANode(M).TypeIsImmutable())
382 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
385 AliasAnalysis::ModRefBehavior
386 TypeBasedAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
388 return AliasAnalysis::getModRefBehavior(CS);
390 ModRefBehavior Min = UnknownModRefBehavior;
392 // If this is an "immutable" type, we can assume the call doesn't write
394 if (const MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
395 if (!EnableStructPathTBAA && TBAANode(M).TypeIsImmutable())
396 Min = OnlyReadsMemory;
398 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
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);
407 AliasAnalysis::ModRefResult
408 TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
409 const Location &Loc) {
411 return AliasAnalysis::getModRefInfo(CS, Loc);
413 if (const MDNode *L = Loc.TBAATag)
414 if (const MDNode *M =
415 CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
419 return AliasAnalysis::getModRefInfo(CS, Loc);
422 AliasAnalysis::ModRefResult
423 TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
424 ImmutableCallSite CS2) {
426 return AliasAnalysis::getModRefInfo(CS1, CS2);
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))
435 return AliasAnalysis::getModRefInfo(CS1, CS2);
438 MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
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));
449 B = cast_or_null<MDNode>(B->getOperand(1));
453 SmallVector<MDNode *, 4> PathA;
457 if (EnableStructPathTBAA)
458 T = T->getNumOperands() >= 3 ? cast_or_null<MDNode>(T->getOperand(2)) : 0;
460 T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
463 SmallVector<MDNode *, 4> PathB;
467 if (EnableStructPathTBAA)
468 T = T->getNumOperands() >= 3 ? cast_or_null<MDNode>(T->getOperand(2)) : 0;
470 T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
473 int IA = PathA.size() - 1;
474 int IB = PathB.size() - 1;
477 while (IA >= 0 && IB >=0) {
478 if (PathA[IA] == PathB[IB])
485 if (!EnableStructPathTBAA)
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);