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 // 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 22 // can be dropped. 23 // 24 // The scalar TBAA metadata format is very simple. TBAA MDNodes have up to 25 // three fields, e.g.: 26 // !0 = metadata !{ metadata !"an example type tree" } 27 // !1 = metadata !{ metadata !"int", metadata !0 } 28 // !2 = metadata !{ metadata !"float", metadata !0 } 29 // !3 = metadata !{ metadata !"const float", metadata !2, i64 1 } 30 // 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. 36 // 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. 42 // 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). 47 // 48 // With struct-path aware TBAA, the MDNodes attached to an instruction using 49 // "!tbaa" are called path tag nodes. 50 // 51 // The path tag node has 4 fields with the last field being optional. 52 // 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". 58 // 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 sclar type node), specifying the type of the member, the second 62 // element of each pair is the offset of the member. 63 // 64 // Given an example 65 // typedef struct { 66 // short s; 67 // } A; 68 // typedef struct { 69 // uint16_t s; 70 // A a; 71 // } B; 72 // 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. 76 // 77 // !0 = metadata !{metadata !"Simple C/C++ TBAA"} 78 // !1 = metadata !{metadata !"omnipotent char", metadata !0} // Scalar type node 79 // !2 = metadata !{metadata !"short", metadata !1} // Scalar type node 80 // !3 = metadata !{metadata !"A", metadata !2, i64 0} // Struct type node 81 // !4 = metadata !{metadata !"B", metadata !2, i64 0, metadata !3, i64 4} 82 // // Struct type node 83 // !5 = metadata !{metadata !4, metadata !2, i64 4} // Path tag node 84 // 85 // The struct type nodes and the scalar type nodes form a type DAG. 86 // Root (!0) 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 91 // 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 95 // node. 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 98 // otherwise. 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. 101 // 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. 106 // 107 // TODO: The current metadata format doesn't support struct 108 // fields. For example: 109 // struct X { 110 // double d; 111 // int i; 112 // }; 113 // void foo(struct X *x, struct X *y, double *p) { 114 // *x = *y; 115 // *p = 0.0; 116 // } 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. 121 // 122 //===----------------------------------------------------------------------===// 123 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; 131 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 134 // more convenient. 135 static cl::opt<bool> EnableTBAA("enable-tbaa", cl::init(true)); 136 137 namespace { 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 140 /// in its operands. 141 template<typename MDNodeTy> 142 class TBAANodeImpl { 143 MDNodeTy *Node; 144 145 public: 146 TBAANodeImpl() : Node(nullptr) {} 147 explicit TBAANodeImpl(MDNodeTy *N) : Node(N) {} 148 149 /// getNode - Get the MDNode for this TBAANode. 150 MDNodeTy *getNode() const { return Node; } 151 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)); 157 if (!P) 158 return TBAANodeImpl<MDNodeTy>(); 159 // Ok, this node has a valid parent. Return it. 160 return TBAANodeImpl<MDNodeTy>(P); 161 } 162 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) 168 return false; 169 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(2)); 170 if (!CI) 171 return false; 172 return CI->getValue()[0]; 173 } 174 }; 175 176 /// \name Specializations of \c TBAANodeImpl for const and non const qualified 177 /// \c MDNode. 178 /// @{ 179 typedef TBAANodeImpl<const MDNode> TBAANode; 180 typedef TBAANodeImpl<MDNode> MutableTBAANode; 181 /// @} 182 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. 189 MDNodeTy *Node; 190 191 public: 192 explicit TBAAStructTagNodeImpl(MDNodeTy *N) : Node(N) {} 193 194 /// Get the MDNode for this TBAAStructTagNode. 195 MDNodeTy *getNode() const { return Node; } 196 197 MDNodeTy *getBaseType() const { 198 return dyn_cast_or_null<MDNode>(Node->getOperand(0)); 199 } 200 MDNodeTy *getAccessType() const { 201 return dyn_cast_or_null<MDNode>(Node->getOperand(1)); 202 } 203 uint64_t getOffset() const { 204 return mdconst::extract<ConstantInt>(Node->getOperand(2))->getZExtValue(); 205 } 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) 211 return false; 212 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(3)); 213 if (!CI) 214 return false; 215 return CI->getValue()[0]; 216 } 217 }; 218 219 /// \name Specializations of \c TBAAStructTagNodeImpl for const and non const 220 /// qualified \c MDNods. 221 /// @{ 222 typedef TBAAStructTagNodeImpl<const MDNode> TBAAStructTagNode; 223 typedef TBAAStructTagNodeImpl<MDNode> MutableTBAAStructTagNode; 224 /// @} 225 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. 231 const MDNode *Node; 232 233 public: 234 TBAAStructTypeNode() : Node(nullptr) {} 235 explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {} 236 237 /// Get the MDNode for this TBAAStructTypeNode. 238 const MDNode *getNode() const { return Node; } 239 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(); 246 247 // Fast path for a scalar type node and a struct type node with a single 248 // field. 249 if (Node->getNumOperands() <= 3) { 250 uint64_t Cur = Node->getNumOperands() == 2 251 ? 0 252 : mdconst::extract<ConstantInt>(Node->getOperand(2)) 253 ->getZExtValue(); 254 Offset -= Cur; 255 MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1)); 256 if (!P) 257 return TBAAStructTypeNode(); 258 return TBAAStructTypeNode(P); 259 } 260 261 // Assume the offsets are in order. We return the previous field if 262 // the current offset is bigger than the given offset. 263 unsigned TheIdx = 0; 264 for (unsigned Idx = 1; Idx < Node->getNumOperands(); Idx += 2) { 265 uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(Idx + 1)) 266 ->getZExtValue(); 267 if (Cur > Offset) { 268 assert(Idx >= 3 && 269 "TBAAStructTypeNode::getParent should have an offset match!"); 270 TheIdx = Idx - 2; 271 break; 272 } 273 } 274 // Move along the last field. 275 if (TheIdx == 0) 276 TheIdx = Node->getNumOperands() - 2; 277 uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(TheIdx + 1)) 278 ->getZExtValue(); 279 Offset -= Cur; 280 MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(TheIdx)); 281 if (!P) 282 return TBAAStructTypeNode(); 283 return TBAAStructTypeNode(P); 284 } 285 }; 286 } 287 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 290 /// format. 291 static bool isStructPathTBAA(const MDNode *MD) { 292 // Anonymous TBAA root starts with a MDNode and dragonegg uses it as 293 // a TBAA tag. 294 return isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3; 295 } 296 297 AliasResult TypeBasedAAResult::alias(const MemoryLocation &LocA, 298 const MemoryLocation &LocB) { 299 if (!EnableTBAA) 300 return AAResultBase::alias(LocA, LocB); 301 302 // Get the attached MDNodes. If either value lacks a tbaa MDNode, we must 303 // be conservative. 304 const MDNode *AM = LocA.AATags.TBAA; 305 if (!AM) 306 return AAResultBase::alias(LocA, LocB); 307 const MDNode *BM = LocB.AATags.TBAA; 308 if (!BM) 309 return AAResultBase::alias(LocA, LocB); 310 311 // If they may alias, chain to the next AliasAnalysis. 312 if (Aliases(AM, BM)) 313 return AAResultBase::alias(LocA, LocB); 314 315 // Otherwise return a definitive result. 316 return NoAlias; 317 } 318 319 bool TypeBasedAAResult::pointsToConstantMemory(const MemoryLocation &Loc, 320 bool OrLocal) { 321 if (!EnableTBAA) 322 return AAResultBase::pointsToConstantMemory(Loc, OrLocal); 323 324 const MDNode *M = Loc.AATags.TBAA; 325 if (!M) 326 return AAResultBase::pointsToConstantMemory(Loc, OrLocal); 327 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())) 332 return true; 333 334 return AAResultBase::pointsToConstantMemory(Loc, OrLocal); 335 } 336 337 FunctionModRefBehavior 338 TypeBasedAAResult::getModRefBehavior(ImmutableCallSite CS) { 339 if (!EnableTBAA) 340 return AAResultBase::getModRefBehavior(CS); 341 342 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 343 344 // If this is an "immutable" type, we can assume the call doesn't write 345 // to memory. 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; 350 351 return FunctionModRefBehavior(AAResultBase::getModRefBehavior(CS) & Min); 352 } 353 354 FunctionModRefBehavior TypeBasedAAResult::getModRefBehavior(const Function *F) { 355 // Functions don't have metadata. Just chain to the next implementation. 356 return AAResultBase::getModRefBehavior(F); 357 } 358 359 ModRefInfo TypeBasedAAResult::getModRefInfo(ImmutableCallSite CS, 360 const MemoryLocation &Loc) { 361 if (!EnableTBAA) 362 return AAResultBase::getModRefInfo(CS, Loc); 363 364 if (const MDNode *L = Loc.AATags.TBAA) 365 if (const MDNode *M = 366 CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa)) 367 if (!Aliases(L, M)) 368 return MRI_NoModRef; 369 370 return AAResultBase::getModRefInfo(CS, Loc); 371 } 372 373 ModRefInfo TypeBasedAAResult::getModRefInfo(ImmutableCallSite CS1, 374 ImmutableCallSite CS2) { 375 if (!EnableTBAA) 376 return AAResultBase::getModRefInfo(CS1, CS2); 377 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)) 383 return MRI_NoModRef; 384 385 return AAResultBase::getModRefInfo(CS1, CS2); 386 } 387 388 bool MDNode::isTBAAVtableAccess() const { 389 if (!isStructPathTBAA(this)) { 390 if (getNumOperands() < 1) 391 return false; 392 if (MDString *Tag1 = dyn_cast<MDString>(getOperand(0))) { 393 if (Tag1->getString() == "vtable pointer") 394 return true; 395 } 396 return false; 397 } 398 399 // For struct-path aware TBAA, we use the access type of the tag. 400 if (getNumOperands() < 2) 401 return false; 402 MDNode *Tag = cast_or_null<MDNode>(getOperand(1)); 403 if (!Tag) 404 return false; 405 if (MDString *Tag1 = dyn_cast<MDString>(Tag->getOperand(0))) { 406 if (Tag1->getString() == "vtable pointer") 407 return true; 408 } 409 return false; 410 } 411 412 MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) { 413 if (!A || !B) 414 return nullptr; 415 416 if (A == B) 417 return A; 418 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()); 423 if (!A) 424 return nullptr; 425 B = cast_or_null<MDNode>(MutableTBAAStructTagNode(B).getAccessType()); 426 if (!B) 427 return nullptr; 428 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()); 435 TA = TA.getParent(); 436 } 437 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()); 444 TB = TB.getParent(); 445 } 446 447 int IA = PathA.size() - 1; 448 int IB = PathB.size() - 1; 449 450 MDNode *Ret = nullptr; 451 while (IA >= 0 && IB >= 0) { 452 if (PathA[IA] == PathB[IB]) 453 Ret = PathA[IA]; 454 else 455 break; 456 --IA; 457 --IB; 458 } 459 460 if (!Ret) 461 return nullptr; 462 // We need to convert from a type node to a tag node. 463 Type *Int64 = IntegerType::get(A->getContext(), 64); 464 Metadata *Ops[3] = {Ret, Ret, 465 ConstantAsMetadata::get(ConstantInt::get(Int64, 0))}; 466 return MDNode::get(A->getContext(), Ops); 467 } 468 469 void Instruction::getAAMetadata(AAMDNodes &N, bool Merge) const { 470 if (Merge) 471 N.TBAA = 472 MDNode::getMostGenericTBAA(N.TBAA, getMetadata(LLVMContext::MD_tbaa)); 473 else 474 N.TBAA = getMetadata(LLVMContext::MD_tbaa); 475 476 if (Merge) 477 N.Scope = MDNode::getMostGenericAliasScope( 478 N.Scope, getMetadata(LLVMContext::MD_alias_scope)); 479 else 480 N.Scope = getMetadata(LLVMContext::MD_alias_scope); 481 482 if (Merge) 483 N.NoAlias = 484 MDNode::intersect(N.NoAlias, getMetadata(LLVMContext::MD_noalias)); 485 else 486 N.NoAlias = getMetadata(LLVMContext::MD_noalias); 487 } 488 489 /// Aliases - Test whether the type represented by A may alias the 490 /// type represented by B. 491 bool TypeBasedAAResult::Aliases(const MDNode *A, const MDNode *B) const { 492 // Verify that both input nodes are struct-path aware. Auto-upgrade should 493 // have taken care of this. 494 assert(isStructPathTBAA(A) && "MDNode A is not struct-path aware."); 495 assert(isStructPathTBAA(B) && "MDNode B is not struct-path aware."); 496 497 // Keep track of the root node for A and B. 498 TBAAStructTypeNode RootA, RootB; 499 TBAAStructTagNode TagA(A), TagB(B); 500 501 // TODO: We need to check if AccessType of TagA encloses AccessType of 502 // TagB to support aggregate AccessType. If yes, return true. 503 504 // Start from the base type of A, follow the edge with the correct offset in 505 // the type DAG and adjust the offset until we reach the base type of B or 506 // until we reach the Root node. 507 // Compare the adjusted offset once we have the same base. 508 509 // Climb the type DAG from base type of A to see if we reach base type of B. 510 const MDNode *BaseA = TagA.getBaseType(); 511 const MDNode *BaseB = TagB.getBaseType(); 512 uint64_t OffsetA = TagA.getOffset(), OffsetB = TagB.getOffset(); 513 for (TBAAStructTypeNode T(BaseA);;) { 514 if (T.getNode() == BaseB) 515 // Base type of A encloses base type of B, check if the offsets match. 516 return OffsetA == OffsetB; 517 518 RootA = T; 519 // Follow the edge with the correct offset, OffsetA will be adjusted to 520 // be relative to the field type. 521 T = T.getParent(OffsetA); 522 if (!T.getNode()) 523 break; 524 } 525 526 // Reset OffsetA and climb the type DAG from base type of B to see if we reach 527 // base type of A. 528 OffsetA = TagA.getOffset(); 529 for (TBAAStructTypeNode T(BaseB);;) { 530 if (T.getNode() == BaseA) 531 // Base type of B encloses base type of A, check if the offsets match. 532 return OffsetA == OffsetB; 533 534 RootB = T; 535 // Follow the edge with the correct offset, OffsetB will be adjusted to 536 // be relative to the field type. 537 T = T.getParent(OffsetB); 538 if (!T.getNode()) 539 break; 540 } 541 542 // Neither node is an ancestor of the other. 543 544 // If they have different roots, they're part of different potentially 545 // unrelated type systems, so we must be conservative. 546 if (RootA.getNode() != RootB.getNode()) 547 return true; 548 549 // If they have the same root, then we've proved there's no alias. 550 return false; 551 } 552 553 AnalysisKey TypeBasedAA::Key; 554 555 TypeBasedAAResult TypeBasedAA::run(Function &F, FunctionAnalysisManager &AM) { 556 return TypeBasedAAResult(); 557 } 558 559 char TypeBasedAAWrapperPass::ID = 0; 560 INITIALIZE_PASS(TypeBasedAAWrapperPass, "tbaa", "Type-Based Alias Analysis", 561 false, true) 562 563 ImmutablePass *llvm::createTypeBasedAAWrapperPass() { 564 return new TypeBasedAAWrapperPass(); 565 } 566 567 TypeBasedAAWrapperPass::TypeBasedAAWrapperPass() : ImmutablePass(ID) { 568 initializeTypeBasedAAWrapperPassPass(*PassRegistry::getPassRegistry()); 569 } 570 571 bool TypeBasedAAWrapperPass::doInitialization(Module &M) { 572 Result.reset(new TypeBasedAAResult()); 573 return false; 574 } 575 576 bool TypeBasedAAWrapperPass::doFinalization(Module &M) { 577 Result.reset(); 578 return false; 579 } 580 581 void TypeBasedAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 582 AU.setPreservesAll(); 583 } 584