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 // We now support two types of metadata format: scalar TBAA and struct-path
20 // aware TBAA. After all testing cases are upgraded to use struct-path aware
21 // TBAA and we can auto-upgrade existing bc files, the support for scalar TBAA
24 // The scalar TBAA metadata format is very simple. TBAA MDNodes have up to
25 // three fields, e.g.:
26 // !0 = !{ !"an example type tree" }
27 // !1 = !{ !"int", !0 }
28 // !2 = !{ !"float", !0 }
29 // !3 = !{ !"const float", !2, i64 1 }
31 // The first field is an identity field. It can be any value, usually
32 // an MDString, which uniquely identifies the type. The most important
33 // name in the tree is the name of the root node. Two trees with
34 // different root node names are entirely disjoint, even if they
35 // have leaves with common names.
37 // The second field identifies the type's parent node in the tree, or
38 // is null or omitted for a root node. A type is considered to alias
39 // all of its descendants and all of its ancestors in the tree. Also,
40 // a type is considered to alias all types in other trees, so that
41 // bitcode produced from multiple front-ends is handled conservatively.
43 // If the third field is present, it's an integer which if equal to 1
44 // indicates that the type is "constant" (meaning pointsToConstantMemory
45 // should return true; see
46 // http://llvm.org/docs/AliasAnalysis.html#OtherItfs).
48 // With struct-path aware TBAA, the MDNodes attached to an instruction using
49 // "!tbaa" are called path tag nodes.
51 // The path tag node has 4 fields with the last field being optional.
53 // The first field is the base type node, it can be a struct type node
54 // or a scalar type node. The second field is the access type node, it
55 // must be a scalar type node. The third field is the offset into the base type.
56 // The last field has the same meaning as the last field of our scalar TBAA:
57 // it's an integer which if equal to 1 indicates that the access is "constant".
59 // The struct type node has a name and a list of pairs, one pair for each member
60 // of the struct. The first element of each pair is a type node (a struct type
61 // node or a scalar type node), specifying the type of the member, the second
62 // element of each pair is the offset of the member.
73 // For an access to B.a.s, we attach !5 (a path tag node) to the load/store
74 // instruction. The base type is !4 (struct B), the access type is !2 (scalar
75 // type short) and the offset is 4.
77 // !0 = !{!"Simple C/C++ TBAA"}
78 // !1 = !{!"omnipotent char", !0} // Scalar type node
79 // !2 = !{!"short", !1} // Scalar type node
80 // !3 = !{!"A", !2, i64 0} // Struct type node
81 // !4 = !{!"B", !2, i64 0, !3, i64 4}
82 // // Struct type node
83 // !5 = !{!4, !2, i64 4} // Path tag node
85 // The struct type nodes and the scalar type nodes form a type DAG.
87 // char (!1) -- edge to Root
88 // short (!2) -- edge to char
89 // A (!3) -- edge with offset 0 to short
90 // B (!4) -- edge with offset 0 to short and edge with offset 4 to A
92 // To check if two tags (tagX and tagY) can alias, we start from the base type
93 // of tagX, follow the edge with the correct offset in the type DAG and adjust
94 // the offset until we reach the base type of tagY or until we reach the Root
96 // If we reach the base type of tagY, compare the adjusted offset with
97 // offset of tagY, return Alias if the offsets are the same, return NoAlias
99 // If we reach the Root node, perform the above starting from base type of tagY
100 // to see if we reach base type of tagX.
102 // If they have different roots, they're part of different potentially
103 // unrelated type systems, so we return Alias to be conservative.
104 // If neither node is an ancestor of the other and they have the same root,
105 // then we say NoAlias.
107 // TODO: The current metadata format doesn't support struct
108 // fields. For example:
113 // void foo(struct X *x, struct X *y, double *p) {
117 // Struct X has a double member, so the store to *x can alias the store to *p.
118 // Currently it's not possible to precisely describe all the things struct X
119 // aliases, so struct assignments must use conservative TBAA nodes. There's
120 // no scheme for attaching metadata to @llvm.memcpy yet either.
122 //===----------------------------------------------------------------------===//
124 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
125 #include "llvm/ADT/SetVector.h"
126 #include "llvm/IR/Constants.h"
127 #include "llvm/IR/LLVMContext.h"
128 #include "llvm/IR/Module.h"
129 #include "llvm/Support/CommandLine.h"
130 using namespace llvm;
132 // A handy option for disabling TBAA functionality. The same effect can also be
133 // achieved by stripping the !tbaa tags from IR, but this option is sometimes
135 static cl::opt<bool> EnableTBAA("enable-tbaa", cl::init(true));
138 /// This is a simple wrapper around an MDNode which provides a higher-level
139 /// interface by hiding the details of how alias analysis information is encoded
141 template<typename MDNodeTy>
146 TBAANodeImpl() : Node(nullptr) {}
147 explicit TBAANodeImpl(MDNodeTy *N) : Node(N) {}
149 /// getNode - Get the MDNode for this TBAANode.
150 MDNodeTy *getNode() const { return Node; }
152 /// getParent - Get this TBAANode's Alias tree parent.
153 TBAANodeImpl<MDNodeTy> getParent() const {
154 if (Node->getNumOperands() < 2)
155 return TBAANodeImpl<MDNodeTy>();
156 MDNodeTy *P = dyn_cast_or_null<MDNodeTy>(Node->getOperand(1));
158 return TBAANodeImpl<MDNodeTy>();
159 // Ok, this node has a valid parent. Return it.
160 return TBAANodeImpl<MDNodeTy>(P);
163 /// Test if this TBAANode represents a type for objects which are
164 /// not modified (by any means) in the context where this
165 /// AliasAnalysis is relevant.
166 bool isTypeImmutable() const {
167 if (Node->getNumOperands() < 3)
169 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(2));
172 return CI->getValue()[0];
176 /// \name Specializations of \c TBAANodeImpl for const and non const qualified
179 typedef TBAANodeImpl<const MDNode> TBAANode;
180 typedef TBAANodeImpl<MDNode> MutableTBAANode;
183 /// This is a simple wrapper around an MDNode which provides a
184 /// higher-level interface by hiding the details of how alias analysis
185 /// information is encoded in its operands.
186 template<typename MDNodeTy>
187 class TBAAStructTagNodeImpl {
188 /// This node should be created with createTBAAStructTagNode.
192 explicit TBAAStructTagNodeImpl(MDNodeTy *N) : Node(N) {}
194 /// Get the MDNode for this TBAAStructTagNode.
195 MDNodeTy *getNode() const { return Node; }
197 MDNodeTy *getBaseType() const {
198 return dyn_cast_or_null<MDNode>(Node->getOperand(0));
200 MDNodeTy *getAccessType() const {
201 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
203 uint64_t getOffset() const {
204 return mdconst::extract<ConstantInt>(Node->getOperand(2))->getZExtValue();
206 /// Test if this TBAAStructTagNode represents a type for objects
207 /// which are not modified (by any means) in the context where this
208 /// AliasAnalysis is relevant.
209 bool isTypeImmutable() const {
210 if (Node->getNumOperands() < 4)
212 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(3));
215 return CI->getValue()[0];
219 /// \name Specializations of \c TBAAStructTagNodeImpl for const and non const
220 /// qualified \c MDNods.
222 typedef TBAAStructTagNodeImpl<const MDNode> TBAAStructTagNode;
223 typedef TBAAStructTagNodeImpl<MDNode> MutableTBAAStructTagNode;
226 /// This is a simple wrapper around an MDNode which provides a
227 /// higher-level interface by hiding the details of how alias analysis
228 /// information is encoded in its operands.
229 class TBAAStructTypeNode {
230 /// This node should be created with createTBAAStructTypeNode.
234 TBAAStructTypeNode() : Node(nullptr) {}
235 explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
237 /// Get the MDNode for this TBAAStructTypeNode.
238 const MDNode *getNode() const { return Node; }
240 /// Get this TBAAStructTypeNode's field in the type DAG with
241 /// given offset. Update the offset to be relative to the field type.
242 TBAAStructTypeNode getParent(uint64_t &Offset) const {
243 // Parent can be omitted for the root node.
244 if (Node->getNumOperands() < 2)
245 return TBAAStructTypeNode();
247 // Fast path for a scalar type node and a struct type node with a single
249 if (Node->getNumOperands() <= 3) {
250 uint64_t Cur = Node->getNumOperands() == 2
252 : mdconst::extract<ConstantInt>(Node->getOperand(2))
255 MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
257 return TBAAStructTypeNode();
258 return TBAAStructTypeNode(P);
261 // Assume the offsets are in order. We return the previous field if
262 // the current offset is bigger than the given offset.
264 for (unsigned Idx = 1; Idx < Node->getNumOperands(); Idx += 2) {
265 uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(Idx + 1))
269 "TBAAStructTypeNode::getParent should have an offset match!");
274 // Move along the last field.
276 TheIdx = Node->getNumOperands() - 2;
277 uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(TheIdx + 1))
280 MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(TheIdx));
282 return TBAAStructTypeNode();
283 return TBAAStructTypeNode(P);
288 /// Check the first operand of the tbaa tag node, if it is a MDNode, we treat
289 /// it as struct-path aware TBAA format, otherwise, we treat it as scalar TBAA
291 static bool isStructPathTBAA(const MDNode *MD) {
292 // Anonymous TBAA root starts with a MDNode and dragonegg uses it as
294 return isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
297 AliasResult TypeBasedAAResult::alias(const MemoryLocation &LocA,
298 const MemoryLocation &LocB) {
300 return AAResultBase::alias(LocA, LocB);
302 // Get the attached MDNodes. If either value lacks a tbaa MDNode, we must
304 const MDNode *AM = LocA.AATags.TBAA;
306 return AAResultBase::alias(LocA, LocB);
307 const MDNode *BM = LocB.AATags.TBAA;
309 return AAResultBase::alias(LocA, LocB);
311 // If they may alias, chain to the next AliasAnalysis.
313 return AAResultBase::alias(LocA, LocB);
315 // Otherwise return a definitive result.
319 bool TypeBasedAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
322 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
324 const MDNode *M = Loc.AATags.TBAA;
326 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
328 // If this is an "immutable" type, we can assume the pointer is pointing
329 // to constant memory.
330 if ((!isStructPathTBAA(M) && TBAANode(M).isTypeImmutable()) ||
331 (isStructPathTBAA(M) && TBAAStructTagNode(M).isTypeImmutable()))
334 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
337 FunctionModRefBehavior
338 TypeBasedAAResult::getModRefBehavior(ImmutableCallSite CS) {
340 return AAResultBase::getModRefBehavior(CS);
342 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
344 // If this is an "immutable" type, we can assume the call doesn't write
346 if (const MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
347 if ((!isStructPathTBAA(M) && TBAANode(M).isTypeImmutable()) ||
348 (isStructPathTBAA(M) && TBAAStructTagNode(M).isTypeImmutable()))
349 Min = FMRB_OnlyReadsMemory;
351 return FunctionModRefBehavior(AAResultBase::getModRefBehavior(CS) & Min);
354 FunctionModRefBehavior TypeBasedAAResult::getModRefBehavior(const Function *F) {
355 // Functions don't have metadata. Just chain to the next implementation.
356 return AAResultBase::getModRefBehavior(F);
359 ModRefInfo TypeBasedAAResult::getModRefInfo(ImmutableCallSite CS,
360 const MemoryLocation &Loc) {
362 return AAResultBase::getModRefInfo(CS, Loc);
364 if (const MDNode *L = Loc.AATags.TBAA)
365 if (const MDNode *M =
366 CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
370 return AAResultBase::getModRefInfo(CS, Loc);
373 ModRefInfo TypeBasedAAResult::getModRefInfo(ImmutableCallSite CS1,
374 ImmutableCallSite CS2) {
376 return AAResultBase::getModRefInfo(CS1, CS2);
378 if (const MDNode *M1 =
379 CS1.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
380 if (const MDNode *M2 =
381 CS2.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
382 if (!Aliases(M1, M2))
385 return AAResultBase::getModRefInfo(CS1, CS2);
388 bool MDNode::isTBAAVtableAccess() const {
389 if (!isStructPathTBAA(this)) {
390 if (getNumOperands() < 1)
392 if (MDString *Tag1 = dyn_cast<MDString>(getOperand(0))) {
393 if (Tag1->getString() == "vtable pointer")
399 // For struct-path aware TBAA, we use the access type of the tag.
400 if (getNumOperands() < 2)
402 MDNode *Tag = cast_or_null<MDNode>(getOperand(1));
405 if (MDString *Tag1 = dyn_cast<MDString>(Tag->getOperand(0))) {
406 if (Tag1->getString() == "vtable pointer")
412 MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
419 // For struct-path aware TBAA, we use the access type of the tag.
420 assert(isStructPathTBAA(A) && isStructPathTBAA(B) &&
421 "Auto upgrade should have taken care of this!");
422 A = cast_or_null<MDNode>(MutableTBAAStructTagNode(A).getAccessType());
425 B = cast_or_null<MDNode>(MutableTBAAStructTagNode(B).getAccessType());
429 SmallSetVector<MDNode *, 4> PathA;
430 MutableTBAANode TA(A);
431 while (TA.getNode()) {
432 if (PathA.count(TA.getNode()))
433 report_fatal_error("Cycle found in TBAA metadata.");
434 PathA.insert(TA.getNode());
438 SmallSetVector<MDNode *, 4> PathB;
439 MutableTBAANode TB(B);
440 while (TB.getNode()) {
441 if (PathB.count(TB.getNode()))
442 report_fatal_error("Cycle found in TBAA metadata.");
443 PathB.insert(TB.getNode());
447 int IA = PathA.size() - 1;
448 int IB = PathB.size() - 1;
450 MDNode *Ret = nullptr;
451 while (IA >= 0 && IB >= 0) {
452 if (PathA[IA] == PathB[IB])
460 // We either did not find a match, or the only common base "type" is
461 // the root node. In either case, we don't have any useful TBAA
462 // metadata to attach.
463 if (!Ret || Ret->getNumOperands() < 2)
466 // We need to convert from a type node to a tag node.
467 Type *Int64 = IntegerType::get(A->getContext(), 64);
468 Metadata *Ops[3] = {Ret, Ret,
469 ConstantAsMetadata::get(ConstantInt::get(Int64, 0))};
470 return MDNode::get(A->getContext(), Ops);
473 void Instruction::getAAMetadata(AAMDNodes &N, bool Merge) const {
476 MDNode::getMostGenericTBAA(N.TBAA, getMetadata(LLVMContext::MD_tbaa));
478 N.TBAA = getMetadata(LLVMContext::MD_tbaa);
481 N.Scope = MDNode::getMostGenericAliasScope(
482 N.Scope, getMetadata(LLVMContext::MD_alias_scope));
484 N.Scope = getMetadata(LLVMContext::MD_alias_scope);
488 MDNode::intersect(N.NoAlias, getMetadata(LLVMContext::MD_noalias));
490 N.NoAlias = getMetadata(LLVMContext::MD_noalias);
493 /// Aliases - Test whether the type represented by A may alias the
494 /// type represented by B.
495 bool TypeBasedAAResult::Aliases(const MDNode *A, const MDNode *B) const {
496 // Verify that both input nodes are struct-path aware. Auto-upgrade should
497 // have taken care of this.
498 assert(isStructPathTBAA(A) && "MDNode A is not struct-path aware.");
499 assert(isStructPathTBAA(B) && "MDNode B is not struct-path aware.");
501 // Keep track of the root node for A and B.
502 TBAAStructTypeNode RootA, RootB;
503 TBAAStructTagNode TagA(A), TagB(B);
505 // TODO: We need to check if AccessType of TagA encloses AccessType of
506 // TagB to support aggregate AccessType. If yes, return true.
508 // Start from the base type of A, follow the edge with the correct offset in
509 // the type DAG and adjust the offset until we reach the base type of B or
510 // until we reach the Root node.
511 // Compare the adjusted offset once we have the same base.
513 // Climb the type DAG from base type of A to see if we reach base type of B.
514 const MDNode *BaseA = TagA.getBaseType();
515 const MDNode *BaseB = TagB.getBaseType();
516 uint64_t OffsetA = TagA.getOffset(), OffsetB = TagB.getOffset();
517 for (TBAAStructTypeNode T(BaseA);;) {
518 if (T.getNode() == BaseB)
519 // Base type of A encloses base type of B, check if the offsets match.
520 return OffsetA == OffsetB;
523 // Follow the edge with the correct offset, OffsetA will be adjusted to
524 // be relative to the field type.
525 T = T.getParent(OffsetA);
530 // Reset OffsetA and climb the type DAG from base type of B to see if we reach
532 OffsetA = TagA.getOffset();
533 for (TBAAStructTypeNode T(BaseB);;) {
534 if (T.getNode() == BaseA)
535 // Base type of B encloses base type of A, check if the offsets match.
536 return OffsetA == OffsetB;
539 // Follow the edge with the correct offset, OffsetB will be adjusted to
540 // be relative to the field type.
541 T = T.getParent(OffsetB);
546 // Neither node is an ancestor of the other.
548 // If they have different roots, they're part of different potentially
549 // unrelated type systems, so we must be conservative.
550 if (RootA.getNode() != RootB.getNode())
553 // If they have the same root, then we've proved there's no alias.
557 AnalysisKey TypeBasedAA::Key;
559 TypeBasedAAResult TypeBasedAA::run(Function &F, FunctionAnalysisManager &AM) {
560 return TypeBasedAAResult();
563 char TypeBasedAAWrapperPass::ID = 0;
564 INITIALIZE_PASS(TypeBasedAAWrapperPass, "tbaa", "Type-Based Alias Analysis",
567 ImmutablePass *llvm::createTypeBasedAAWrapperPass() {
568 return new TypeBasedAAWrapperPass();
571 TypeBasedAAWrapperPass::TypeBasedAAWrapperPass() : ImmutablePass(ID) {
572 initializeTypeBasedAAWrapperPassPass(*PassRegistry::getPassRegistry());
575 bool TypeBasedAAWrapperPass::doInitialization(Module &M) {
576 Result.reset(new TypeBasedAAResult());
580 bool TypeBasedAAWrapperPass::doFinalization(Module &M) {
585 void TypeBasedAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
586 AU.setPreservesAll();