1 //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the debug info Metadata classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/DebugInfoMetadata.h" 14 #include "LLVMContextImpl.h" 15 #include "MetadataImpl.h" 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/StringSwitch.h" 18 #include "llvm/BinaryFormat/Dwarf.h" 19 #include "llvm/IR/DebugProgramInstruction.h" 20 #include "llvm/IR/Function.h" 21 #include "llvm/IR/IntrinsicInst.h" 22 #include "llvm/IR/Type.h" 23 #include "llvm/IR/Value.h" 24 25 #include <numeric> 26 #include <optional> 27 28 using namespace llvm; 29 30 namespace llvm { 31 // Use FS-AFDO discriminator. 32 cl::opt<bool> EnableFSDiscriminator( 33 "enable-fs-discriminator", cl::Hidden, 34 cl::desc("Enable adding flow sensitive discriminators")); 35 } // namespace llvm 36 37 uint32_t DIType::getAlignInBits() const { 38 return (getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ? 0 : SubclassData32); 39 } 40 41 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = { 42 std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()}; 43 44 DebugVariable::DebugVariable(const DbgVariableIntrinsic *DII) 45 : Variable(DII->getVariable()), 46 Fragment(DII->getExpression()->getFragmentInfo()), 47 InlinedAt(DII->getDebugLoc().getInlinedAt()) {} 48 49 DebugVariable::DebugVariable(const DbgVariableRecord *DVR) 50 : Variable(DVR->getVariable()), 51 Fragment(DVR->getExpression()->getFragmentInfo()), 52 InlinedAt(DVR->getDebugLoc().getInlinedAt()) {} 53 54 DebugVariableAggregate::DebugVariableAggregate(const DbgVariableIntrinsic *DVI) 55 : DebugVariable(DVI->getVariable(), std::nullopt, 56 DVI->getDebugLoc()->getInlinedAt()) {} 57 58 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line, 59 unsigned Column, ArrayRef<Metadata *> MDs, 60 bool ImplicitCode) 61 : MDNode(C, DILocationKind, Storage, MDs) { 62 assert((MDs.size() == 1 || MDs.size() == 2) && 63 "Expected a scope and optional inlined-at"); 64 65 // Set line and column. 66 assert(Column < (1u << 16) && "Expected 16-bit column"); 67 68 SubclassData32 = Line; 69 SubclassData16 = Column; 70 71 setImplicitCode(ImplicitCode); 72 } 73 74 static void adjustColumn(unsigned &Column) { 75 // Set to unknown on overflow. We only have 16 bits to play with here. 76 if (Column >= (1u << 16)) 77 Column = 0; 78 } 79 80 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line, 81 unsigned Column, Metadata *Scope, 82 Metadata *InlinedAt, bool ImplicitCode, 83 StorageType Storage, bool ShouldCreate) { 84 // Fixup column. 85 adjustColumn(Column); 86 87 if (Storage == Uniqued) { 88 if (auto *N = getUniqued(Context.pImpl->DILocations, 89 DILocationInfo::KeyTy(Line, Column, Scope, 90 InlinedAt, ImplicitCode))) 91 return N; 92 if (!ShouldCreate) 93 return nullptr; 94 } else { 95 assert(ShouldCreate && "Expected non-uniqued nodes to always be created"); 96 } 97 98 SmallVector<Metadata *, 2> Ops; 99 Ops.push_back(Scope); 100 if (InlinedAt) 101 Ops.push_back(InlinedAt); 102 return storeImpl(new (Ops.size(), Storage) DILocation( 103 Context, Storage, Line, Column, Ops, ImplicitCode), 104 Storage, Context.pImpl->DILocations); 105 } 106 107 DILocation *DILocation::getMergedLocations(ArrayRef<DILocation *> Locs) { 108 if (Locs.empty()) 109 return nullptr; 110 if (Locs.size() == 1) 111 return Locs[0]; 112 auto *Merged = Locs[0]; 113 for (DILocation *L : llvm::drop_begin(Locs)) { 114 Merged = getMergedLocation(Merged, L); 115 if (Merged == nullptr) 116 break; 117 } 118 return Merged; 119 } 120 121 DILocation *DILocation::getMergedLocation(DILocation *LocA, DILocation *LocB) { 122 if (!LocA || !LocB) 123 return nullptr; 124 125 if (LocA == LocB) 126 return LocA; 127 128 LLVMContext &C = LocA->getContext(); 129 130 using LocVec = SmallVector<const DILocation *>; 131 LocVec ALocs; 132 LocVec BLocs; 133 SmallDenseMap<std::pair<const DISubprogram *, const DILocation *>, unsigned, 134 4> 135 ALookup; 136 137 // Walk through LocA and its inlined-at locations, populate them in ALocs and 138 // save the index for the subprogram and inlined-at pair, which we use to find 139 // a matching starting location in LocB's chain. 140 for (auto [L, I] = std::make_pair(LocA, 0U); L; L = L->getInlinedAt(), I++) { 141 ALocs.push_back(L); 142 auto Res = ALookup.try_emplace( 143 {L->getScope()->getSubprogram(), L->getInlinedAt()}, I); 144 assert(Res.second && "Multiple <SP, InlinedAt> pairs in a location chain?"); 145 (void)Res; 146 } 147 148 LocVec::reverse_iterator ARIt = ALocs.rend(); 149 LocVec::reverse_iterator BRIt = BLocs.rend(); 150 151 // Populate BLocs and look for a matching starting location, the first 152 // location with the same subprogram and inlined-at location as in LocA's 153 // chain. Since the two locations have the same inlined-at location we do 154 // not need to look at those parts of the chains. 155 for (auto [L, I] = std::make_pair(LocB, 0U); L; L = L->getInlinedAt(), I++) { 156 BLocs.push_back(L); 157 158 if (ARIt != ALocs.rend()) 159 // We have already found a matching starting location. 160 continue; 161 162 auto IT = ALookup.find({L->getScope()->getSubprogram(), L->getInlinedAt()}); 163 if (IT == ALookup.end()) 164 continue; 165 166 // The + 1 is to account for the &*rev_it = &(it - 1) relationship. 167 ARIt = LocVec::reverse_iterator(ALocs.begin() + IT->second + 1); 168 BRIt = LocVec::reverse_iterator(BLocs.begin() + I + 1); 169 170 // If we have found a matching starting location we do not need to add more 171 // locations to BLocs, since we will only look at location pairs preceding 172 // the matching starting location, and adding more elements to BLocs could 173 // invalidate the iterator that we initialized here. 174 break; 175 } 176 177 // Merge the two locations if possible, using the supplied 178 // inlined-at location for the created location. 179 auto MergeLocPair = [&C](const DILocation *L1, const DILocation *L2, 180 DILocation *InlinedAt) -> DILocation * { 181 if (L1 == L2) 182 return DILocation::get(C, L1->getLine(), L1->getColumn(), L1->getScope(), 183 InlinedAt); 184 185 // If the locations originate from different subprograms we can't produce 186 // a common location. 187 if (L1->getScope()->getSubprogram() != L2->getScope()->getSubprogram()) 188 return nullptr; 189 190 // Return the nearest common scope inside a subprogram. 191 auto GetNearestCommonScope = [](DIScope *S1, DIScope *S2) -> DIScope * { 192 SmallPtrSet<DIScope *, 8> Scopes; 193 for (; S1; S1 = S1->getScope()) { 194 Scopes.insert(S1); 195 if (isa<DISubprogram>(S1)) 196 break; 197 } 198 199 for (; S2; S2 = S2->getScope()) { 200 if (Scopes.count(S2)) 201 return S2; 202 if (isa<DISubprogram>(S2)) 203 break; 204 } 205 206 return nullptr; 207 }; 208 209 auto Scope = GetNearestCommonScope(L1->getScope(), L2->getScope()); 210 assert(Scope && "No common scope in the same subprogram?"); 211 212 bool SameLine = L1->getLine() == L2->getLine(); 213 bool SameCol = L1->getColumn() == L2->getColumn(); 214 unsigned Line = SameLine ? L1->getLine() : 0; 215 unsigned Col = SameLine && SameCol ? L1->getColumn() : 0; 216 217 return DILocation::get(C, Line, Col, Scope, InlinedAt); 218 }; 219 220 DILocation *Result = ARIt != ALocs.rend() ? (*ARIt)->getInlinedAt() : nullptr; 221 222 // If we have found a common starting location, walk up the inlined-at chains 223 // and try to produce common locations. 224 for (; ARIt != ALocs.rend() && BRIt != BLocs.rend(); ++ARIt, ++BRIt) { 225 DILocation *Tmp = MergeLocPair(*ARIt, *BRIt, Result); 226 227 if (!Tmp) 228 // We have walked up to a point in the chains where the two locations 229 // are irreconsilable. At this point Result contains the nearest common 230 // location in the inlined-at chains of LocA and LocB, so we break here. 231 break; 232 233 Result = Tmp; 234 } 235 236 if (Result) 237 return Result; 238 239 // We ended up with LocA and LocB as irreconsilable locations. Produce a 240 // location at 0:0 with one of the locations' scope. The function has 241 // historically picked A's scope, and a nullptr inlined-at location, so that 242 // behavior is mimicked here but I am not sure if this is always the correct 243 // way to handle this. 244 return DILocation::get(C, 0, 0, LocA->getScope(), nullptr); 245 } 246 247 std::optional<unsigned> 248 DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) { 249 std::array<unsigned, 3> Components = {BD, DF, CI}; 250 uint64_t RemainingWork = 0U; 251 // We use RemainingWork to figure out if we have no remaining components to 252 // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to 253 // encode anything for the latter 2. 254 // Since any of the input components is at most 32 bits, their sum will be 255 // less than 34 bits, and thus RemainingWork won't overflow. 256 RemainingWork = 257 std::accumulate(Components.begin(), Components.end(), RemainingWork); 258 259 int I = 0; 260 unsigned Ret = 0; 261 unsigned NextBitInsertionIndex = 0; 262 while (RemainingWork > 0) { 263 unsigned C = Components[I++]; 264 RemainingWork -= C; 265 unsigned EC = encodeComponent(C); 266 Ret |= (EC << NextBitInsertionIndex); 267 NextBitInsertionIndex += encodingBits(C); 268 } 269 270 // Encoding may be unsuccessful because of overflow. We determine success by 271 // checking equivalence of components before & after encoding. Alternatively, 272 // we could determine Success during encoding, but the current alternative is 273 // simpler. 274 unsigned TBD, TDF, TCI = 0; 275 decodeDiscriminator(Ret, TBD, TDF, TCI); 276 if (TBD == BD && TDF == DF && TCI == CI) 277 return Ret; 278 return std::nullopt; 279 } 280 281 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF, 282 unsigned &CI) { 283 BD = getUnsignedFromPrefixEncoding(D); 284 DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D)); 285 CI = getUnsignedFromPrefixEncoding( 286 getNextComponentInDiscriminator(getNextComponentInDiscriminator(D))); 287 } 288 dwarf::Tag DINode::getTag() const { return (dwarf::Tag)SubclassData16; } 289 290 DINode::DIFlags DINode::getFlag(StringRef Flag) { 291 return StringSwitch<DIFlags>(Flag) 292 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME) 293 #include "llvm/IR/DebugInfoFlags.def" 294 .Default(DINode::FlagZero); 295 } 296 297 StringRef DINode::getFlagString(DIFlags Flag) { 298 switch (Flag) { 299 #define HANDLE_DI_FLAG(ID, NAME) \ 300 case Flag##NAME: \ 301 return "DIFlag" #NAME; 302 #include "llvm/IR/DebugInfoFlags.def" 303 } 304 return ""; 305 } 306 307 DINode::DIFlags DINode::splitFlags(DIFlags Flags, 308 SmallVectorImpl<DIFlags> &SplitFlags) { 309 // Flags that are packed together need to be specially handled, so 310 // that, for example, we emit "DIFlagPublic" and not 311 // "DIFlagPrivate | DIFlagProtected". 312 if (DIFlags A = Flags & FlagAccessibility) { 313 if (A == FlagPrivate) 314 SplitFlags.push_back(FlagPrivate); 315 else if (A == FlagProtected) 316 SplitFlags.push_back(FlagProtected); 317 else 318 SplitFlags.push_back(FlagPublic); 319 Flags &= ~A; 320 } 321 if (DIFlags R = Flags & FlagPtrToMemberRep) { 322 if (R == FlagSingleInheritance) 323 SplitFlags.push_back(FlagSingleInheritance); 324 else if (R == FlagMultipleInheritance) 325 SplitFlags.push_back(FlagMultipleInheritance); 326 else 327 SplitFlags.push_back(FlagVirtualInheritance); 328 Flags &= ~R; 329 } 330 if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) { 331 Flags &= ~FlagIndirectVirtualBase; 332 SplitFlags.push_back(FlagIndirectVirtualBase); 333 } 334 335 #define HANDLE_DI_FLAG(ID, NAME) \ 336 if (DIFlags Bit = Flags & Flag##NAME) { \ 337 SplitFlags.push_back(Bit); \ 338 Flags &= ~Bit; \ 339 } 340 #include "llvm/IR/DebugInfoFlags.def" 341 return Flags; 342 } 343 344 DIScope *DIScope::getScope() const { 345 if (auto *T = dyn_cast<DIType>(this)) 346 return T->getScope(); 347 348 if (auto *SP = dyn_cast<DISubprogram>(this)) 349 return SP->getScope(); 350 351 if (auto *LB = dyn_cast<DILexicalBlockBase>(this)) 352 return LB->getScope(); 353 354 if (auto *NS = dyn_cast<DINamespace>(this)) 355 return NS->getScope(); 356 357 if (auto *CB = dyn_cast<DICommonBlock>(this)) 358 return CB->getScope(); 359 360 if (auto *M = dyn_cast<DIModule>(this)) 361 return M->getScope(); 362 363 assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) && 364 "Unhandled type of scope."); 365 return nullptr; 366 } 367 368 StringRef DIScope::getName() const { 369 if (auto *T = dyn_cast<DIType>(this)) 370 return T->getName(); 371 if (auto *SP = dyn_cast<DISubprogram>(this)) 372 return SP->getName(); 373 if (auto *NS = dyn_cast<DINamespace>(this)) 374 return NS->getName(); 375 if (auto *CB = dyn_cast<DICommonBlock>(this)) 376 return CB->getName(); 377 if (auto *M = dyn_cast<DIModule>(this)) 378 return M->getName(); 379 assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) || 380 isa<DICompileUnit>(this)) && 381 "Unhandled type of scope."); 382 return ""; 383 } 384 385 #ifndef NDEBUG 386 static bool isCanonical(const MDString *S) { 387 return !S || !S->getString().empty(); 388 } 389 #endif 390 391 dwarf::Tag GenericDINode::getTag() const { return (dwarf::Tag)SubclassData16; } 392 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag, 393 MDString *Header, 394 ArrayRef<Metadata *> DwarfOps, 395 StorageType Storage, bool ShouldCreate) { 396 unsigned Hash = 0; 397 if (Storage == Uniqued) { 398 GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps); 399 if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key)) 400 return N; 401 if (!ShouldCreate) 402 return nullptr; 403 Hash = Key.getHash(); 404 } else { 405 assert(ShouldCreate && "Expected non-uniqued nodes to always be created"); 406 } 407 408 // Use a nullptr for empty headers. 409 assert(isCanonical(Header) && "Expected canonical MDString"); 410 Metadata *PreOps[] = {Header}; 411 return storeImpl(new (DwarfOps.size() + 1, Storage) GenericDINode( 412 Context, Storage, Hash, Tag, PreOps, DwarfOps), 413 Storage, Context.pImpl->GenericDINodes); 414 } 415 416 void GenericDINode::recalculateHash() { 417 setHash(GenericDINodeInfo::KeyTy::calculateHash(this)); 418 } 419 420 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__ 421 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS 422 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS) \ 423 do { \ 424 if (Storage == Uniqued) { \ 425 if (auto *N = getUniqued(Context.pImpl->CLASS##s, \ 426 CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS)))) \ 427 return N; \ 428 if (!ShouldCreate) \ 429 return nullptr; \ 430 } else { \ 431 assert(ShouldCreate && \ 432 "Expected non-uniqued nodes to always be created"); \ 433 } \ 434 } while (false) 435 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \ 436 return storeImpl(new (std::size(OPS), Storage) \ 437 CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \ 438 Storage, Context.pImpl->CLASS##s) 439 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \ 440 return storeImpl(new (0u, Storage) \ 441 CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \ 442 Storage, Context.pImpl->CLASS##s) 443 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \ 444 return storeImpl(new (std::size(OPS), Storage) CLASS(Context, Storage, OPS), \ 445 Storage, Context.pImpl->CLASS##s) 446 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS) \ 447 return storeImpl(new (NUM_OPS, Storage) \ 448 CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \ 449 Storage, Context.pImpl->CLASS##s) 450 451 DISubrange::DISubrange(LLVMContext &C, StorageType Storage, 452 ArrayRef<Metadata *> Ops) 453 : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {} 454 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo, 455 StorageType Storage, bool ShouldCreate) { 456 auto *CountNode = ConstantAsMetadata::get( 457 ConstantInt::getSigned(Type::getInt64Ty(Context), Count)); 458 auto *LB = ConstantAsMetadata::get( 459 ConstantInt::getSigned(Type::getInt64Ty(Context), Lo)); 460 return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage, 461 ShouldCreate); 462 } 463 464 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 465 int64_t Lo, StorageType Storage, 466 bool ShouldCreate) { 467 auto *LB = ConstantAsMetadata::get( 468 ConstantInt::getSigned(Type::getInt64Ty(Context), Lo)); 469 return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage, 470 ShouldCreate); 471 } 472 473 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 474 Metadata *LB, Metadata *UB, Metadata *Stride, 475 StorageType Storage, bool ShouldCreate) { 476 DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride)); 477 Metadata *Ops[] = {CountNode, LB, UB, Stride}; 478 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops); 479 } 480 481 DISubrange::BoundType DISubrange::getCount() const { 482 Metadata *CB = getRawCountNode(); 483 if (!CB) 484 return BoundType(); 485 486 assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) || 487 isa<DIExpression>(CB)) && 488 "Count must be signed constant or DIVariable or DIExpression"); 489 490 if (auto *MD = dyn_cast<ConstantAsMetadata>(CB)) 491 return BoundType(cast<ConstantInt>(MD->getValue())); 492 493 if (auto *MD = dyn_cast<DIVariable>(CB)) 494 return BoundType(MD); 495 496 if (auto *MD = dyn_cast<DIExpression>(CB)) 497 return BoundType(MD); 498 499 return BoundType(); 500 } 501 502 DISubrange::BoundType DISubrange::getLowerBound() const { 503 Metadata *LB = getRawLowerBound(); 504 if (!LB) 505 return BoundType(); 506 507 assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) || 508 isa<DIExpression>(LB)) && 509 "LowerBound must be signed constant or DIVariable or DIExpression"); 510 511 if (auto *MD = dyn_cast<ConstantAsMetadata>(LB)) 512 return BoundType(cast<ConstantInt>(MD->getValue())); 513 514 if (auto *MD = dyn_cast<DIVariable>(LB)) 515 return BoundType(MD); 516 517 if (auto *MD = dyn_cast<DIExpression>(LB)) 518 return BoundType(MD); 519 520 return BoundType(); 521 } 522 523 DISubrange::BoundType DISubrange::getUpperBound() const { 524 Metadata *UB = getRawUpperBound(); 525 if (!UB) 526 return BoundType(); 527 528 assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) || 529 isa<DIExpression>(UB)) && 530 "UpperBound must be signed constant or DIVariable or DIExpression"); 531 532 if (auto *MD = dyn_cast<ConstantAsMetadata>(UB)) 533 return BoundType(cast<ConstantInt>(MD->getValue())); 534 535 if (auto *MD = dyn_cast<DIVariable>(UB)) 536 return BoundType(MD); 537 538 if (auto *MD = dyn_cast<DIExpression>(UB)) 539 return BoundType(MD); 540 541 return BoundType(); 542 } 543 544 DISubrange::BoundType DISubrange::getStride() const { 545 Metadata *ST = getRawStride(); 546 if (!ST) 547 return BoundType(); 548 549 assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) || 550 isa<DIExpression>(ST)) && 551 "Stride must be signed constant or DIVariable or DIExpression"); 552 553 if (auto *MD = dyn_cast<ConstantAsMetadata>(ST)) 554 return BoundType(cast<ConstantInt>(MD->getValue())); 555 556 if (auto *MD = dyn_cast<DIVariable>(ST)) 557 return BoundType(MD); 558 559 if (auto *MD = dyn_cast<DIExpression>(ST)) 560 return BoundType(MD); 561 562 return BoundType(); 563 } 564 DIGenericSubrange::DIGenericSubrange(LLVMContext &C, StorageType Storage, 565 ArrayRef<Metadata *> Ops) 566 : DINode(C, DIGenericSubrangeKind, Storage, dwarf::DW_TAG_generic_subrange, 567 Ops) {} 568 569 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context, 570 Metadata *CountNode, Metadata *LB, 571 Metadata *UB, Metadata *Stride, 572 StorageType Storage, 573 bool ShouldCreate) { 574 DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride)); 575 Metadata *Ops[] = {CountNode, LB, UB, Stride}; 576 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops); 577 } 578 579 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const { 580 Metadata *CB = getRawCountNode(); 581 if (!CB) 582 return BoundType(); 583 584 assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) && 585 "Count must be signed constant or DIVariable or DIExpression"); 586 587 if (auto *MD = dyn_cast<DIVariable>(CB)) 588 return BoundType(MD); 589 590 if (auto *MD = dyn_cast<DIExpression>(CB)) 591 return BoundType(MD); 592 593 return BoundType(); 594 } 595 596 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const { 597 Metadata *LB = getRawLowerBound(); 598 if (!LB) 599 return BoundType(); 600 601 assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) && 602 "LowerBound must be signed constant or DIVariable or DIExpression"); 603 604 if (auto *MD = dyn_cast<DIVariable>(LB)) 605 return BoundType(MD); 606 607 if (auto *MD = dyn_cast<DIExpression>(LB)) 608 return BoundType(MD); 609 610 return BoundType(); 611 } 612 613 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const { 614 Metadata *UB = getRawUpperBound(); 615 if (!UB) 616 return BoundType(); 617 618 assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) && 619 "UpperBound must be signed constant or DIVariable or DIExpression"); 620 621 if (auto *MD = dyn_cast<DIVariable>(UB)) 622 return BoundType(MD); 623 624 if (auto *MD = dyn_cast<DIExpression>(UB)) 625 return BoundType(MD); 626 627 return BoundType(); 628 } 629 630 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const { 631 Metadata *ST = getRawStride(); 632 if (!ST) 633 return BoundType(); 634 635 assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) && 636 "Stride must be signed constant or DIVariable or DIExpression"); 637 638 if (auto *MD = dyn_cast<DIVariable>(ST)) 639 return BoundType(MD); 640 641 if (auto *MD = dyn_cast<DIExpression>(ST)) 642 return BoundType(MD); 643 644 return BoundType(); 645 } 646 647 DIEnumerator::DIEnumerator(LLVMContext &C, StorageType Storage, 648 const APInt &Value, bool IsUnsigned, 649 ArrayRef<Metadata *> Ops) 650 : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops), 651 Value(Value) { 652 SubclassData32 = IsUnsigned; 653 } 654 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value, 655 bool IsUnsigned, MDString *Name, 656 StorageType Storage, bool ShouldCreate) { 657 assert(isCanonical(Name) && "Expected canonical MDString"); 658 DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name)); 659 Metadata *Ops[] = {Name}; 660 DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops); 661 } 662 663 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag, 664 MDString *Name, uint64_t SizeInBits, 665 uint32_t AlignInBits, unsigned Encoding, 666 uint32_t NumExtraInhabitants, DIFlags Flags, 667 StorageType Storage, bool ShouldCreate) { 668 assert(isCanonical(Name) && "Expected canonical MDString"); 669 DEFINE_GETIMPL_LOOKUP(DIBasicType, (Tag, Name, SizeInBits, AlignInBits, 670 Encoding, NumExtraInhabitants, Flags)); 671 Metadata *Ops[] = {nullptr, nullptr, Name}; 672 DEFINE_GETIMPL_STORE( 673 DIBasicType, 674 (Tag, SizeInBits, AlignInBits, Encoding, NumExtraInhabitants, Flags), 675 Ops); 676 } 677 678 std::optional<DIBasicType::Signedness> DIBasicType::getSignedness() const { 679 switch (getEncoding()) { 680 case dwarf::DW_ATE_signed: 681 case dwarf::DW_ATE_signed_char: 682 return Signedness::Signed; 683 case dwarf::DW_ATE_unsigned: 684 case dwarf::DW_ATE_unsigned_char: 685 return Signedness::Unsigned; 686 default: 687 return std::nullopt; 688 } 689 } 690 691 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag, 692 MDString *Name, Metadata *StringLength, 693 Metadata *StringLengthExp, 694 Metadata *StringLocationExp, 695 uint64_t SizeInBits, uint32_t AlignInBits, 696 unsigned Encoding, StorageType Storage, 697 bool ShouldCreate) { 698 assert(isCanonical(Name) && "Expected canonical MDString"); 699 DEFINE_GETIMPL_LOOKUP(DIStringType, 700 (Tag, Name, StringLength, StringLengthExp, 701 StringLocationExp, SizeInBits, AlignInBits, Encoding)); 702 Metadata *Ops[] = {nullptr, nullptr, Name, 703 StringLength, StringLengthExp, StringLocationExp}; 704 DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding), 705 Ops); 706 } 707 DIType *DIDerivedType::getClassType() const { 708 assert(getTag() == dwarf::DW_TAG_ptr_to_member_type); 709 return cast_or_null<DIType>(getExtraData()); 710 } 711 uint32_t DIDerivedType::getVBPtrOffset() const { 712 assert(getTag() == dwarf::DW_TAG_inheritance); 713 if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData())) 714 if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue())) 715 return static_cast<uint32_t>(CI->getZExtValue()); 716 return 0; 717 } 718 Constant *DIDerivedType::getStorageOffsetInBits() const { 719 assert(getTag() == dwarf::DW_TAG_member && isBitField()); 720 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 721 return C->getValue(); 722 return nullptr; 723 } 724 725 Constant *DIDerivedType::getConstant() const { 726 assert((getTag() == dwarf::DW_TAG_member || 727 getTag() == dwarf::DW_TAG_variable) && 728 isStaticMember()); 729 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 730 return C->getValue(); 731 return nullptr; 732 } 733 Constant *DIDerivedType::getDiscriminantValue() const { 734 assert(getTag() == dwarf::DW_TAG_member && !isStaticMember()); 735 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 736 return C->getValue(); 737 return nullptr; 738 } 739 740 DIDerivedType *DIDerivedType::getImpl( 741 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 742 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 743 uint32_t AlignInBits, uint64_t OffsetInBits, 744 std::optional<unsigned> DWARFAddressSpace, 745 std::optional<PtrAuthData> PtrAuthData, DIFlags Flags, Metadata *ExtraData, 746 Metadata *Annotations, StorageType Storage, bool ShouldCreate) { 747 assert(isCanonical(Name) && "Expected canonical MDString"); 748 DEFINE_GETIMPL_LOOKUP(DIDerivedType, 749 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, 750 AlignInBits, OffsetInBits, DWARFAddressSpace, 751 PtrAuthData, Flags, ExtraData, Annotations)); 752 Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations}; 753 DEFINE_GETIMPL_STORE(DIDerivedType, 754 (Tag, Line, SizeInBits, AlignInBits, OffsetInBits, 755 DWARFAddressSpace, PtrAuthData, Flags), 756 Ops); 757 } 758 759 std::optional<DIDerivedType::PtrAuthData> 760 DIDerivedType::getPtrAuthData() const { 761 return getTag() == dwarf::DW_TAG_LLVM_ptrauth_type 762 ? std::optional<PtrAuthData>(PtrAuthData(SubclassData32)) 763 : std::nullopt; 764 } 765 766 DICompositeType *DICompositeType::getImpl( 767 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 768 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 769 uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, 770 Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, 771 Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator, 772 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 773 Metadata *Rank, Metadata *Annotations, Metadata *Specification, 774 uint32_t NumExtraInhabitants, StorageType Storage, bool ShouldCreate) { 775 assert(isCanonical(Name) && "Expected canonical MDString"); 776 777 // Keep this in sync with buildODRType. 778 DEFINE_GETIMPL_LOOKUP( 779 DICompositeType, 780 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, 781 OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, 782 Identifier, Discriminator, DataLocation, Associated, Allocated, Rank, 783 Annotations, Specification, NumExtraInhabitants)); 784 Metadata *Ops[] = {File, Scope, Name, BaseType, 785 Elements, VTableHolder, TemplateParams, Identifier, 786 Discriminator, DataLocation, Associated, Allocated, 787 Rank, Annotations, Specification}; 788 DEFINE_GETIMPL_STORE(DICompositeType, 789 (Tag, Line, RuntimeLang, SizeInBits, AlignInBits, 790 OffsetInBits, NumExtraInhabitants, Flags), 791 Ops); 792 } 793 794 DICompositeType *DICompositeType::buildODRType( 795 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 796 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 797 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 798 Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, 799 Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, 800 Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, 801 Metadata *Associated, Metadata *Allocated, Metadata *Rank, 802 Metadata *Annotations) { 803 assert(!Identifier.getString().empty() && "Expected valid identifier"); 804 if (!Context.isODRUniquingDebugTypes()) 805 return nullptr; 806 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 807 if (!CT) 808 return CT = DICompositeType::getDistinct( 809 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 810 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 811 VTableHolder, TemplateParams, &Identifier, Discriminator, 812 DataLocation, Associated, Allocated, Rank, Annotations, 813 Specification, NumExtraInhabitants); 814 if (CT->getTag() != Tag) 815 return nullptr; 816 817 // Only mutate CT if it's a forward declaration and the new operands aren't. 818 assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?"); 819 if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl)) 820 return CT; 821 822 // Mutate CT in place. Keep this in sync with getImpl. 823 CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, 824 NumExtraInhabitants, Flags); 825 Metadata *Ops[] = {File, Scope, Name, BaseType, 826 Elements, VTableHolder, TemplateParams, &Identifier, 827 Discriminator, DataLocation, Associated, Allocated, 828 Rank, Annotations, Specification}; 829 assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() && 830 "Mismatched number of operands"); 831 for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I) 832 if (Ops[I] != CT->getOperand(I)) 833 CT->setOperand(I, Ops[I]); 834 return CT; 835 } 836 837 DICompositeType *DICompositeType::getODRType( 838 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 839 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 840 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 841 Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, 842 Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, 843 Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, 844 Metadata *Associated, Metadata *Allocated, Metadata *Rank, 845 Metadata *Annotations) { 846 assert(!Identifier.getString().empty() && "Expected valid identifier"); 847 if (!Context.isODRUniquingDebugTypes()) 848 return nullptr; 849 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 850 if (!CT) { 851 CT = DICompositeType::getDistinct( 852 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 853 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, 854 TemplateParams, &Identifier, Discriminator, DataLocation, Associated, 855 Allocated, Rank, Annotations, Specification, NumExtraInhabitants); 856 } else { 857 if (CT->getTag() != Tag) 858 return nullptr; 859 } 860 return CT; 861 } 862 863 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context, 864 MDString &Identifier) { 865 assert(!Identifier.getString().empty() && "Expected valid identifier"); 866 if (!Context.isODRUniquingDebugTypes()) 867 return nullptr; 868 return Context.pImpl->DITypeMap->lookup(&Identifier); 869 } 870 DISubroutineType::DISubroutineType(LLVMContext &C, StorageType Storage, 871 DIFlags Flags, uint8_t CC, 872 ArrayRef<Metadata *> Ops) 873 : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type, 0, 874 0, 0, 0, 0, Flags, Ops), 875 CC(CC) {} 876 877 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags, 878 uint8_t CC, Metadata *TypeArray, 879 StorageType Storage, 880 bool ShouldCreate) { 881 DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray)); 882 Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray}; 883 DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops); 884 } 885 886 DIFile::DIFile(LLVMContext &C, StorageType Storage, 887 std::optional<ChecksumInfo<MDString *>> CS, MDString *Src, 888 ArrayRef<Metadata *> Ops) 889 : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops), 890 Checksum(CS), Source(Src) {} 891 892 // FIXME: Implement this string-enum correspondence with a .def file and macros, 893 // so that the association is explicit rather than implied. 894 static const char *ChecksumKindName[DIFile::CSK_Last] = { 895 "CSK_MD5", 896 "CSK_SHA1", 897 "CSK_SHA256", 898 }; 899 900 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) { 901 assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind"); 902 // The first space was originally the CSK_None variant, which is now 903 // obsolete, but the space is still reserved in ChecksumKind, so we account 904 // for it here. 905 return ChecksumKindName[CSKind - 1]; 906 } 907 908 std::optional<DIFile::ChecksumKind> 909 DIFile::getChecksumKind(StringRef CSKindStr) { 910 return StringSwitch<std::optional<DIFile::ChecksumKind>>(CSKindStr) 911 .Case("CSK_MD5", DIFile::CSK_MD5) 912 .Case("CSK_SHA1", DIFile::CSK_SHA1) 913 .Case("CSK_SHA256", DIFile::CSK_SHA256) 914 .Default(std::nullopt); 915 } 916 917 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename, 918 MDString *Directory, 919 std::optional<DIFile::ChecksumInfo<MDString *>> CS, 920 MDString *Source, StorageType Storage, 921 bool ShouldCreate) { 922 assert(isCanonical(Filename) && "Expected canonical MDString"); 923 assert(isCanonical(Directory) && "Expected canonical MDString"); 924 assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString"); 925 // We do *NOT* expect Source to be a canonical MDString because nullptr 926 // means none, so we need something to represent the empty file. 927 DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source)); 928 Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr, Source}; 929 DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops); 930 } 931 DICompileUnit::DICompileUnit(LLVMContext &C, StorageType Storage, 932 unsigned SourceLanguage, bool IsOptimized, 933 unsigned RuntimeVersion, unsigned EmissionKind, 934 uint64_t DWOId, bool SplitDebugInlining, 935 bool DebugInfoForProfiling, unsigned NameTableKind, 936 bool RangesBaseAddress, ArrayRef<Metadata *> Ops) 937 : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops), 938 SourceLanguage(SourceLanguage), RuntimeVersion(RuntimeVersion), 939 DWOId(DWOId), EmissionKind(EmissionKind), NameTableKind(NameTableKind), 940 IsOptimized(IsOptimized), SplitDebugInlining(SplitDebugInlining), 941 DebugInfoForProfiling(DebugInfoForProfiling), 942 RangesBaseAddress(RangesBaseAddress) { 943 assert(Storage != Uniqued); 944 } 945 946 DICompileUnit *DICompileUnit::getImpl( 947 LLVMContext &Context, unsigned SourceLanguage, Metadata *File, 948 MDString *Producer, bool IsOptimized, MDString *Flags, 949 unsigned RuntimeVersion, MDString *SplitDebugFilename, 950 unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes, 951 Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros, 952 uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling, 953 unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot, 954 MDString *SDK, StorageType Storage, bool ShouldCreate) { 955 assert(Storage != Uniqued && "Cannot unique DICompileUnit"); 956 assert(isCanonical(Producer) && "Expected canonical MDString"); 957 assert(isCanonical(Flags) && "Expected canonical MDString"); 958 assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString"); 959 960 Metadata *Ops[] = {File, 961 Producer, 962 Flags, 963 SplitDebugFilename, 964 EnumTypes, 965 RetainedTypes, 966 GlobalVariables, 967 ImportedEntities, 968 Macros, 969 SysRoot, 970 SDK}; 971 return storeImpl(new (std::size(Ops), Storage) DICompileUnit( 972 Context, Storage, SourceLanguage, IsOptimized, 973 RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining, 974 DebugInfoForProfiling, NameTableKind, RangesBaseAddress, 975 Ops), 976 Storage); 977 } 978 979 std::optional<DICompileUnit::DebugEmissionKind> 980 DICompileUnit::getEmissionKind(StringRef Str) { 981 return StringSwitch<std::optional<DebugEmissionKind>>(Str) 982 .Case("NoDebug", NoDebug) 983 .Case("FullDebug", FullDebug) 984 .Case("LineTablesOnly", LineTablesOnly) 985 .Case("DebugDirectivesOnly", DebugDirectivesOnly) 986 .Default(std::nullopt); 987 } 988 989 std::optional<DICompileUnit::DebugNameTableKind> 990 DICompileUnit::getNameTableKind(StringRef Str) { 991 return StringSwitch<std::optional<DebugNameTableKind>>(Str) 992 .Case("Default", DebugNameTableKind::Default) 993 .Case("GNU", DebugNameTableKind::GNU) 994 .Case("Apple", DebugNameTableKind::Apple) 995 .Case("None", DebugNameTableKind::None) 996 .Default(std::nullopt); 997 } 998 999 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) { 1000 switch (EK) { 1001 case NoDebug: 1002 return "NoDebug"; 1003 case FullDebug: 1004 return "FullDebug"; 1005 case LineTablesOnly: 1006 return "LineTablesOnly"; 1007 case DebugDirectivesOnly: 1008 return "DebugDirectivesOnly"; 1009 } 1010 return nullptr; 1011 } 1012 1013 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) { 1014 switch (NTK) { 1015 case DebugNameTableKind::Default: 1016 return nullptr; 1017 case DebugNameTableKind::GNU: 1018 return "GNU"; 1019 case DebugNameTableKind::Apple: 1020 return "Apple"; 1021 case DebugNameTableKind::None: 1022 return "None"; 1023 } 1024 return nullptr; 1025 } 1026 DISubprogram::DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line, 1027 unsigned ScopeLine, unsigned VirtualIndex, 1028 int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, 1029 ArrayRef<Metadata *> Ops) 1030 : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram, Ops), 1031 Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex), 1032 ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) { 1033 static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range"); 1034 } 1035 DISubprogram::DISPFlags 1036 DISubprogram::toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, 1037 unsigned Virtuality, bool IsMainSubprogram) { 1038 // We're assuming virtuality is the low-order field. 1039 static_assert(int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) && 1040 int(SPFlagPureVirtual) == 1041 int(dwarf::DW_VIRTUALITY_pure_virtual), 1042 "Virtuality constant mismatch"); 1043 return static_cast<DISPFlags>( 1044 (Virtuality & SPFlagVirtuality) | 1045 (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) | 1046 (IsDefinition ? SPFlagDefinition : SPFlagZero) | 1047 (IsOptimized ? SPFlagOptimized : SPFlagZero) | 1048 (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero)); 1049 } 1050 1051 DISubprogram *DILocalScope::getSubprogram() const { 1052 if (auto *Block = dyn_cast<DILexicalBlockBase>(this)) 1053 return Block->getScope()->getSubprogram(); 1054 return const_cast<DISubprogram *>(cast<DISubprogram>(this)); 1055 } 1056 1057 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const { 1058 if (auto *File = dyn_cast<DILexicalBlockFile>(this)) 1059 return File->getScope()->getNonLexicalBlockFileScope(); 1060 return const_cast<DILocalScope *>(this); 1061 } 1062 1063 DILocalScope *DILocalScope::cloneScopeForSubprogram( 1064 DILocalScope &RootScope, DISubprogram &NewSP, LLVMContext &Ctx, 1065 DenseMap<const MDNode *, MDNode *> &Cache) { 1066 SmallVector<DIScope *> ScopeChain; 1067 DIScope *CachedResult = nullptr; 1068 1069 for (DIScope *Scope = &RootScope; !isa<DISubprogram>(Scope); 1070 Scope = Scope->getScope()) { 1071 if (auto It = Cache.find(Scope); It != Cache.end()) { 1072 CachedResult = cast<DIScope>(It->second); 1073 break; 1074 } 1075 ScopeChain.push_back(Scope); 1076 } 1077 1078 // Recreate the scope chain, bottom-up, starting at the new subprogram (or a 1079 // cached result). 1080 DIScope *UpdatedScope = CachedResult ? CachedResult : &NewSP; 1081 for (DIScope *ScopeToUpdate : reverse(ScopeChain)) { 1082 TempMDNode ClonedScope = ScopeToUpdate->clone(); 1083 cast<DILexicalBlockBase>(*ClonedScope).replaceScope(UpdatedScope); 1084 UpdatedScope = 1085 cast<DIScope>(MDNode::replaceWithUniqued(std::move(ClonedScope))); 1086 Cache[ScopeToUpdate] = UpdatedScope; 1087 } 1088 1089 return cast<DILocalScope>(UpdatedScope); 1090 } 1091 1092 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) { 1093 return StringSwitch<DISPFlags>(Flag) 1094 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME) 1095 #include "llvm/IR/DebugInfoFlags.def" 1096 .Default(SPFlagZero); 1097 } 1098 1099 StringRef DISubprogram::getFlagString(DISPFlags Flag) { 1100 switch (Flag) { 1101 // Appease a warning. 1102 case SPFlagVirtuality: 1103 return ""; 1104 #define HANDLE_DISP_FLAG(ID, NAME) \ 1105 case SPFlag##NAME: \ 1106 return "DISPFlag" #NAME; 1107 #include "llvm/IR/DebugInfoFlags.def" 1108 } 1109 return ""; 1110 } 1111 1112 DISubprogram::DISPFlags 1113 DISubprogram::splitFlags(DISPFlags Flags, 1114 SmallVectorImpl<DISPFlags> &SplitFlags) { 1115 // Multi-bit fields can require special handling. In our case, however, the 1116 // only multi-bit field is virtuality, and all its values happen to be 1117 // single-bit values, so the right behavior just falls out. 1118 #define HANDLE_DISP_FLAG(ID, NAME) \ 1119 if (DISPFlags Bit = Flags & SPFlag##NAME) { \ 1120 SplitFlags.push_back(Bit); \ 1121 Flags &= ~Bit; \ 1122 } 1123 #include "llvm/IR/DebugInfoFlags.def" 1124 return Flags; 1125 } 1126 1127 DISubprogram *DISubprogram::getImpl( 1128 LLVMContext &Context, Metadata *Scope, MDString *Name, 1129 MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type, 1130 unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex, 1131 int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit, 1132 Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes, 1133 Metadata *ThrownTypes, Metadata *Annotations, MDString *TargetFuncName, 1134 StorageType Storage, bool ShouldCreate) { 1135 assert(isCanonical(Name) && "Expected canonical MDString"); 1136 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 1137 assert(isCanonical(TargetFuncName) && "Expected canonical MDString"); 1138 DEFINE_GETIMPL_LOOKUP(DISubprogram, 1139 (Scope, Name, LinkageName, File, Line, Type, ScopeLine, 1140 ContainingType, VirtualIndex, ThisAdjustment, Flags, 1141 SPFlags, Unit, TemplateParams, Declaration, 1142 RetainedNodes, ThrownTypes, Annotations, 1143 TargetFuncName)); 1144 SmallVector<Metadata *, 13> Ops = { 1145 File, Scope, Name, LinkageName, 1146 Type, Unit, Declaration, RetainedNodes, 1147 ContainingType, TemplateParams, ThrownTypes, Annotations, 1148 TargetFuncName}; 1149 if (!TargetFuncName) { 1150 Ops.pop_back(); 1151 if (!Annotations) { 1152 Ops.pop_back(); 1153 if (!ThrownTypes) { 1154 Ops.pop_back(); 1155 if (!TemplateParams) { 1156 Ops.pop_back(); 1157 if (!ContainingType) 1158 Ops.pop_back(); 1159 } 1160 } 1161 } 1162 } 1163 DEFINE_GETIMPL_STORE_N( 1164 DISubprogram, 1165 (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops, 1166 Ops.size()); 1167 } 1168 1169 bool DISubprogram::describes(const Function *F) const { 1170 assert(F && "Invalid function"); 1171 return F->getSubprogram() == this; 1172 } 1173 DILexicalBlockBase::DILexicalBlockBase(LLVMContext &C, unsigned ID, 1174 StorageType Storage, 1175 ArrayRef<Metadata *> Ops) 1176 : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {} 1177 1178 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope, 1179 Metadata *File, unsigned Line, 1180 unsigned Column, StorageType Storage, 1181 bool ShouldCreate) { 1182 // Fixup column. 1183 adjustColumn(Column); 1184 1185 assert(Scope && "Expected scope"); 1186 DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column)); 1187 Metadata *Ops[] = {File, Scope}; 1188 DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops); 1189 } 1190 1191 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context, 1192 Metadata *Scope, Metadata *File, 1193 unsigned Discriminator, 1194 StorageType Storage, 1195 bool ShouldCreate) { 1196 assert(Scope && "Expected scope"); 1197 DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator)); 1198 Metadata *Ops[] = {File, Scope}; 1199 DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops); 1200 } 1201 1202 DINamespace::DINamespace(LLVMContext &Context, StorageType Storage, 1203 bool ExportSymbols, ArrayRef<Metadata *> Ops) 1204 : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace, Ops) { 1205 SubclassData1 = ExportSymbols; 1206 } 1207 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope, 1208 MDString *Name, bool ExportSymbols, 1209 StorageType Storage, bool ShouldCreate) { 1210 assert(isCanonical(Name) && "Expected canonical MDString"); 1211 DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols)); 1212 // The nullptr is for DIScope's File operand. This should be refactored. 1213 Metadata *Ops[] = {nullptr, Scope, Name}; 1214 DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops); 1215 } 1216 1217 DICommonBlock::DICommonBlock(LLVMContext &Context, StorageType Storage, 1218 unsigned LineNo, ArrayRef<Metadata *> Ops) 1219 : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block, 1220 Ops) { 1221 SubclassData32 = LineNo; 1222 } 1223 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope, 1224 Metadata *Decl, MDString *Name, 1225 Metadata *File, unsigned LineNo, 1226 StorageType Storage, bool ShouldCreate) { 1227 assert(isCanonical(Name) && "Expected canonical MDString"); 1228 DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo)); 1229 // The nullptr is for DIScope's File operand. This should be refactored. 1230 Metadata *Ops[] = {Scope, Decl, Name, File}; 1231 DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops); 1232 } 1233 1234 DIModule::DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo, 1235 bool IsDecl, ArrayRef<Metadata *> Ops) 1236 : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops) { 1237 SubclassData1 = IsDecl; 1238 SubclassData32 = LineNo; 1239 } 1240 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File, 1241 Metadata *Scope, MDString *Name, 1242 MDString *ConfigurationMacros, 1243 MDString *IncludePath, MDString *APINotesFile, 1244 unsigned LineNo, bool IsDecl, StorageType Storage, 1245 bool ShouldCreate) { 1246 assert(isCanonical(Name) && "Expected canonical MDString"); 1247 DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros, 1248 IncludePath, APINotesFile, LineNo, IsDecl)); 1249 Metadata *Ops[] = {File, Scope, Name, ConfigurationMacros, 1250 IncludePath, APINotesFile}; 1251 DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops); 1252 } 1253 DITemplateTypeParameter::DITemplateTypeParameter(LLVMContext &Context, 1254 StorageType Storage, 1255 bool IsDefault, 1256 ArrayRef<Metadata *> Ops) 1257 : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage, 1258 dwarf::DW_TAG_template_type_parameter, IsDefault, 1259 Ops) {} 1260 1261 DITemplateTypeParameter * 1262 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name, 1263 Metadata *Type, bool isDefault, 1264 StorageType Storage, bool ShouldCreate) { 1265 assert(isCanonical(Name) && "Expected canonical MDString"); 1266 DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault)); 1267 Metadata *Ops[] = {Name, Type}; 1268 DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops); 1269 } 1270 1271 DITemplateValueParameter *DITemplateValueParameter::getImpl( 1272 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type, 1273 bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) { 1274 assert(isCanonical(Name) && "Expected canonical MDString"); 1275 DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, 1276 (Tag, Name, Type, isDefault, Value)); 1277 Metadata *Ops[] = {Name, Type, Value}; 1278 DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops); 1279 } 1280 1281 DIGlobalVariable * 1282 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1283 MDString *LinkageName, Metadata *File, unsigned Line, 1284 Metadata *Type, bool IsLocalToUnit, bool IsDefinition, 1285 Metadata *StaticDataMemberDeclaration, 1286 Metadata *TemplateParams, uint32_t AlignInBits, 1287 Metadata *Annotations, StorageType Storage, 1288 bool ShouldCreate) { 1289 assert(isCanonical(Name) && "Expected canonical MDString"); 1290 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 1291 DEFINE_GETIMPL_LOOKUP( 1292 DIGlobalVariable, 1293 (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, 1294 StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations)); 1295 Metadata *Ops[] = {Scope, 1296 Name, 1297 File, 1298 Type, 1299 Name, 1300 LinkageName, 1301 StaticDataMemberDeclaration, 1302 TemplateParams, 1303 Annotations}; 1304 DEFINE_GETIMPL_STORE(DIGlobalVariable, 1305 (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops); 1306 } 1307 1308 DILocalVariable * 1309 DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1310 Metadata *File, unsigned Line, Metadata *Type, 1311 unsigned Arg, DIFlags Flags, uint32_t AlignInBits, 1312 Metadata *Annotations, StorageType Storage, 1313 bool ShouldCreate) { 1314 // 64K ought to be enough for any frontend. 1315 assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits"); 1316 1317 assert(Scope && "Expected scope"); 1318 assert(isCanonical(Name) && "Expected canonical MDString"); 1319 DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Scope, Name, File, Line, Type, Arg, 1320 Flags, AlignInBits, Annotations)); 1321 Metadata *Ops[] = {Scope, Name, File, Type, Annotations}; 1322 DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops); 1323 } 1324 1325 DIVariable::DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, 1326 signed Line, ArrayRef<Metadata *> Ops, 1327 uint32_t AlignInBits) 1328 : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line) { 1329 SubclassData32 = AlignInBits; 1330 } 1331 std::optional<uint64_t> DIVariable::getSizeInBits() const { 1332 // This is used by the Verifier so be mindful of broken types. 1333 const Metadata *RawType = getRawType(); 1334 while (RawType) { 1335 // Try to get the size directly. 1336 if (auto *T = dyn_cast<DIType>(RawType)) 1337 if (uint64_t Size = T->getSizeInBits()) 1338 return Size; 1339 1340 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 1341 // Look at the base type. 1342 RawType = DT->getRawBaseType(); 1343 continue; 1344 } 1345 1346 // Missing type or size. 1347 break; 1348 } 1349 1350 // Fail gracefully. 1351 return std::nullopt; 1352 } 1353 1354 DILabel::DILabel(LLVMContext &C, StorageType Storage, unsigned Line, 1355 ArrayRef<Metadata *> Ops) 1356 : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops) { 1357 SubclassData32 = Line; 1358 } 1359 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1360 Metadata *File, unsigned Line, StorageType Storage, 1361 bool ShouldCreate) { 1362 assert(Scope && "Expected scope"); 1363 assert(isCanonical(Name) && "Expected canonical MDString"); 1364 DEFINE_GETIMPL_LOOKUP(DILabel, (Scope, Name, File, Line)); 1365 Metadata *Ops[] = {Scope, Name, File}; 1366 DEFINE_GETIMPL_STORE(DILabel, (Line), Ops); 1367 } 1368 1369 DIExpression *DIExpression::getImpl(LLVMContext &Context, 1370 ArrayRef<uint64_t> Elements, 1371 StorageType Storage, bool ShouldCreate) { 1372 DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements)); 1373 DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements)); 1374 } 1375 bool DIExpression::isEntryValue() const { 1376 if (auto singleLocElts = getSingleLocationExpressionElements()) { 1377 return singleLocElts->size() > 0 && 1378 (*singleLocElts)[0] == dwarf::DW_OP_LLVM_entry_value; 1379 } 1380 return false; 1381 } 1382 bool DIExpression::startsWithDeref() const { 1383 if (auto singleLocElts = getSingleLocationExpressionElements()) 1384 return singleLocElts->size() > 0 && 1385 (*singleLocElts)[0] == dwarf::DW_OP_deref; 1386 return false; 1387 } 1388 bool DIExpression::isDeref() const { 1389 if (auto singleLocElts = getSingleLocationExpressionElements()) 1390 return singleLocElts->size() == 1 && 1391 (*singleLocElts)[0] == dwarf::DW_OP_deref; 1392 return false; 1393 } 1394 1395 DIAssignID *DIAssignID::getImpl(LLVMContext &Context, StorageType Storage, 1396 bool ShouldCreate) { 1397 // Uniqued DIAssignID are not supported as the instance address *is* the ID. 1398 assert(Storage != StorageType::Uniqued && "uniqued DIAssignID unsupported"); 1399 return storeImpl(new (0u, Storage) DIAssignID(Context, Storage), Storage); 1400 } 1401 1402 unsigned DIExpression::ExprOperand::getSize() const { 1403 uint64_t Op = getOp(); 1404 1405 if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31) 1406 return 2; 1407 1408 switch (Op) { 1409 case dwarf::DW_OP_LLVM_convert: 1410 case dwarf::DW_OP_LLVM_fragment: 1411 case dwarf::DW_OP_LLVM_extract_bits_sext: 1412 case dwarf::DW_OP_LLVM_extract_bits_zext: 1413 case dwarf::DW_OP_bregx: 1414 return 3; 1415 case dwarf::DW_OP_constu: 1416 case dwarf::DW_OP_consts: 1417 case dwarf::DW_OP_deref_size: 1418 case dwarf::DW_OP_plus_uconst: 1419 case dwarf::DW_OP_LLVM_tag_offset: 1420 case dwarf::DW_OP_LLVM_entry_value: 1421 case dwarf::DW_OP_LLVM_arg: 1422 case dwarf::DW_OP_regx: 1423 return 2; 1424 default: 1425 return 1; 1426 } 1427 } 1428 1429 bool DIExpression::isValid() const { 1430 for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) { 1431 // Check that there's space for the operand. 1432 if (I->get() + I->getSize() > E->get()) 1433 return false; 1434 1435 uint64_t Op = I->getOp(); 1436 if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) || 1437 (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)) 1438 return true; 1439 1440 // Check that the operand is valid. 1441 switch (Op) { 1442 default: 1443 return false; 1444 case dwarf::DW_OP_LLVM_fragment: 1445 // A fragment operator must appear at the end. 1446 return I->get() + I->getSize() == E->get(); 1447 case dwarf::DW_OP_stack_value: { 1448 // Must be the last one or followed by a DW_OP_LLVM_fragment. 1449 if (I->get() + I->getSize() == E->get()) 1450 break; 1451 auto J = I; 1452 if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment) 1453 return false; 1454 break; 1455 } 1456 case dwarf::DW_OP_swap: { 1457 // Must be more than one implicit element on the stack. 1458 1459 // FIXME: A better way to implement this would be to add a local variable 1460 // that keeps track of the stack depth and introduce something like a 1461 // DW_LLVM_OP_implicit_location as a placeholder for the location this 1462 // DIExpression is attached to, or else pass the number of implicit stack 1463 // elements into isValid. 1464 if (getNumElements() == 1) 1465 return false; 1466 break; 1467 } 1468 case dwarf::DW_OP_LLVM_entry_value: { 1469 // An entry value operator must appear at the beginning or immediately 1470 // following `DW_OP_LLVM_arg 0`, and the number of operations it cover can 1471 // currently only be 1, because we support only entry values of a simple 1472 // register location. One reason for this is that we currently can't 1473 // calculate the size of the resulting DWARF block for other expressions. 1474 auto FirstOp = expr_op_begin(); 1475 if (FirstOp->getOp() == dwarf::DW_OP_LLVM_arg && FirstOp->getArg(0) == 0) 1476 ++FirstOp; 1477 return I->get() == FirstOp->get() && I->getArg(0) == 1; 1478 } 1479 case dwarf::DW_OP_LLVM_implicit_pointer: 1480 case dwarf::DW_OP_LLVM_convert: 1481 case dwarf::DW_OP_LLVM_arg: 1482 case dwarf::DW_OP_LLVM_tag_offset: 1483 case dwarf::DW_OP_LLVM_extract_bits_sext: 1484 case dwarf::DW_OP_LLVM_extract_bits_zext: 1485 case dwarf::DW_OP_constu: 1486 case dwarf::DW_OP_plus_uconst: 1487 case dwarf::DW_OP_plus: 1488 case dwarf::DW_OP_minus: 1489 case dwarf::DW_OP_mul: 1490 case dwarf::DW_OP_div: 1491 case dwarf::DW_OP_mod: 1492 case dwarf::DW_OP_or: 1493 case dwarf::DW_OP_and: 1494 case dwarf::DW_OP_xor: 1495 case dwarf::DW_OP_shl: 1496 case dwarf::DW_OP_shr: 1497 case dwarf::DW_OP_shra: 1498 case dwarf::DW_OP_deref: 1499 case dwarf::DW_OP_deref_size: 1500 case dwarf::DW_OP_xderef: 1501 case dwarf::DW_OP_lit0: 1502 case dwarf::DW_OP_not: 1503 case dwarf::DW_OP_dup: 1504 case dwarf::DW_OP_regx: 1505 case dwarf::DW_OP_bregx: 1506 case dwarf::DW_OP_push_object_address: 1507 case dwarf::DW_OP_over: 1508 case dwarf::DW_OP_consts: 1509 case dwarf::DW_OP_eq: 1510 case dwarf::DW_OP_ne: 1511 case dwarf::DW_OP_gt: 1512 case dwarf::DW_OP_ge: 1513 case dwarf::DW_OP_lt: 1514 case dwarf::DW_OP_le: 1515 break; 1516 } 1517 } 1518 return true; 1519 } 1520 1521 bool DIExpression::isImplicit() const { 1522 if (!isValid()) 1523 return false; 1524 1525 if (getNumElements() == 0) 1526 return false; 1527 1528 for (const auto &It : expr_ops()) { 1529 switch (It.getOp()) { 1530 default: 1531 break; 1532 case dwarf::DW_OP_stack_value: 1533 return true; 1534 } 1535 } 1536 1537 return false; 1538 } 1539 1540 bool DIExpression::isComplex() const { 1541 if (!isValid()) 1542 return false; 1543 1544 if (getNumElements() == 0) 1545 return false; 1546 1547 // If there are any elements other than fragment or tag_offset, then some 1548 // kind of complex computation occurs. 1549 for (const auto &It : expr_ops()) { 1550 switch (It.getOp()) { 1551 case dwarf::DW_OP_LLVM_tag_offset: 1552 case dwarf::DW_OP_LLVM_fragment: 1553 case dwarf::DW_OP_LLVM_arg: 1554 continue; 1555 default: 1556 return true; 1557 } 1558 } 1559 1560 return false; 1561 } 1562 1563 bool DIExpression::isSingleLocationExpression() const { 1564 if (!isValid()) 1565 return false; 1566 1567 if (getNumElements() == 0) 1568 return true; 1569 1570 auto ExprOpBegin = expr_ops().begin(); 1571 auto ExprOpEnd = expr_ops().end(); 1572 if (ExprOpBegin->getOp() == dwarf::DW_OP_LLVM_arg) { 1573 if (ExprOpBegin->getArg(0) != 0) 1574 return false; 1575 ++ExprOpBegin; 1576 } 1577 1578 return !std::any_of(ExprOpBegin, ExprOpEnd, [](auto Op) { 1579 return Op.getOp() == dwarf::DW_OP_LLVM_arg; 1580 }); 1581 } 1582 1583 std::optional<ArrayRef<uint64_t>> 1584 DIExpression::getSingleLocationExpressionElements() const { 1585 // Check for `isValid` covered by `isSingleLocationExpression`. 1586 if (!isSingleLocationExpression()) 1587 return std::nullopt; 1588 1589 // An empty expression is already non-variadic. 1590 if (!getNumElements()) 1591 return ArrayRef<uint64_t>(); 1592 1593 // If Expr does not have a leading DW_OP_LLVM_arg then we don't need to do 1594 // anything. 1595 if (getElements()[0] == dwarf::DW_OP_LLVM_arg) 1596 return getElements().drop_front(2); 1597 return getElements(); 1598 } 1599 1600 const DIExpression * 1601 DIExpression::convertToUndefExpression(const DIExpression *Expr) { 1602 SmallVector<uint64_t, 3> UndefOps; 1603 if (auto FragmentInfo = Expr->getFragmentInfo()) { 1604 UndefOps.append({dwarf::DW_OP_LLVM_fragment, FragmentInfo->OffsetInBits, 1605 FragmentInfo->SizeInBits}); 1606 } 1607 return DIExpression::get(Expr->getContext(), UndefOps); 1608 } 1609 1610 const DIExpression * 1611 DIExpression::convertToVariadicExpression(const DIExpression *Expr) { 1612 if (any_of(Expr->expr_ops(), [](auto ExprOp) { 1613 return ExprOp.getOp() == dwarf::DW_OP_LLVM_arg; 1614 })) 1615 return Expr; 1616 SmallVector<uint64_t> NewOps; 1617 NewOps.reserve(Expr->getNumElements() + 2); 1618 NewOps.append({dwarf::DW_OP_LLVM_arg, 0}); 1619 NewOps.append(Expr->elements_begin(), Expr->elements_end()); 1620 return DIExpression::get(Expr->getContext(), NewOps); 1621 } 1622 1623 std::optional<const DIExpression *> 1624 DIExpression::convertToNonVariadicExpression(const DIExpression *Expr) { 1625 if (!Expr) 1626 return std::nullopt; 1627 1628 if (auto Elts = Expr->getSingleLocationExpressionElements()) 1629 return DIExpression::get(Expr->getContext(), *Elts); 1630 1631 return std::nullopt; 1632 } 1633 1634 void DIExpression::canonicalizeExpressionOps(SmallVectorImpl<uint64_t> &Ops, 1635 const DIExpression *Expr, 1636 bool IsIndirect) { 1637 // If Expr is not already variadic, insert the implied `DW_OP_LLVM_arg 0` 1638 // to the existing expression ops. 1639 if (none_of(Expr->expr_ops(), [](auto ExprOp) { 1640 return ExprOp.getOp() == dwarf::DW_OP_LLVM_arg; 1641 })) 1642 Ops.append({dwarf::DW_OP_LLVM_arg, 0}); 1643 // If Expr is not indirect, we only need to insert the expression elements and 1644 // we're done. 1645 if (!IsIndirect) { 1646 Ops.append(Expr->elements_begin(), Expr->elements_end()); 1647 return; 1648 } 1649 // If Expr is indirect, insert the implied DW_OP_deref at the end of the 1650 // expression but before DW_OP_{stack_value, LLVM_fragment} if they are 1651 // present. 1652 for (auto Op : Expr->expr_ops()) { 1653 if (Op.getOp() == dwarf::DW_OP_stack_value || 1654 Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1655 Ops.push_back(dwarf::DW_OP_deref); 1656 IsIndirect = false; 1657 } 1658 Op.appendToVector(Ops); 1659 } 1660 if (IsIndirect) 1661 Ops.push_back(dwarf::DW_OP_deref); 1662 } 1663 1664 bool DIExpression::isEqualExpression(const DIExpression *FirstExpr, 1665 bool FirstIndirect, 1666 const DIExpression *SecondExpr, 1667 bool SecondIndirect) { 1668 SmallVector<uint64_t> FirstOps; 1669 DIExpression::canonicalizeExpressionOps(FirstOps, FirstExpr, FirstIndirect); 1670 SmallVector<uint64_t> SecondOps; 1671 DIExpression::canonicalizeExpressionOps(SecondOps, SecondExpr, 1672 SecondIndirect); 1673 return FirstOps == SecondOps; 1674 } 1675 1676 std::optional<DIExpression::FragmentInfo> 1677 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) { 1678 for (auto I = Start; I != End; ++I) 1679 if (I->getOp() == dwarf::DW_OP_LLVM_fragment) { 1680 DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)}; 1681 return Info; 1682 } 1683 return std::nullopt; 1684 } 1685 1686 std::optional<uint64_t> DIExpression::getActiveBits(DIVariable *Var) { 1687 std::optional<uint64_t> InitialActiveBits = Var->getSizeInBits(); 1688 std::optional<uint64_t> ActiveBits = InitialActiveBits; 1689 for (auto Op : expr_ops()) { 1690 switch (Op.getOp()) { 1691 default: 1692 // We assume the worst case for anything we don't currently handle and 1693 // revert to the initial active bits. 1694 ActiveBits = InitialActiveBits; 1695 break; 1696 case dwarf::DW_OP_LLVM_extract_bits_zext: 1697 case dwarf::DW_OP_LLVM_extract_bits_sext: { 1698 // We can't handle an extract whose sign doesn't match that of the 1699 // variable. 1700 std::optional<DIBasicType::Signedness> VarSign = Var->getSignedness(); 1701 bool VarSigned = (VarSign == DIBasicType::Signedness::Signed); 1702 bool OpSigned = (Op.getOp() == dwarf::DW_OP_LLVM_extract_bits_sext); 1703 if (!VarSign || VarSigned != OpSigned) { 1704 ActiveBits = InitialActiveBits; 1705 break; 1706 } 1707 [[fallthrough]]; 1708 } 1709 case dwarf::DW_OP_LLVM_fragment: 1710 // Extract or fragment narrows the active bits 1711 if (ActiveBits) 1712 ActiveBits = std::min(*ActiveBits, Op.getArg(1)); 1713 else 1714 ActiveBits = Op.getArg(1); 1715 break; 1716 } 1717 } 1718 return ActiveBits; 1719 } 1720 1721 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops, 1722 int64_t Offset) { 1723 if (Offset > 0) { 1724 Ops.push_back(dwarf::DW_OP_plus_uconst); 1725 Ops.push_back(Offset); 1726 } else if (Offset < 0) { 1727 Ops.push_back(dwarf::DW_OP_constu); 1728 // Avoid UB when encountering LLONG_MIN, because in 2's complement 1729 // abs(LLONG_MIN) is LLONG_MAX+1. 1730 uint64_t AbsMinusOne = -(Offset+1); 1731 Ops.push_back(AbsMinusOne + 1); 1732 Ops.push_back(dwarf::DW_OP_minus); 1733 } 1734 } 1735 1736 bool DIExpression::extractIfOffset(int64_t &Offset) const { 1737 auto SingleLocEltsOpt = getSingleLocationExpressionElements(); 1738 if (!SingleLocEltsOpt) 1739 return false; 1740 auto SingleLocElts = *SingleLocEltsOpt; 1741 1742 if (SingleLocElts.size() == 0) { 1743 Offset = 0; 1744 return true; 1745 } 1746 1747 if (SingleLocElts.size() == 2 && 1748 SingleLocElts[0] == dwarf::DW_OP_plus_uconst) { 1749 Offset = SingleLocElts[1]; 1750 return true; 1751 } 1752 1753 if (SingleLocElts.size() == 3 && SingleLocElts[0] == dwarf::DW_OP_constu) { 1754 if (SingleLocElts[2] == dwarf::DW_OP_plus) { 1755 Offset = SingleLocElts[1]; 1756 return true; 1757 } 1758 if (SingleLocElts[2] == dwarf::DW_OP_minus) { 1759 Offset = -SingleLocElts[1]; 1760 return true; 1761 } 1762 } 1763 1764 return false; 1765 } 1766 1767 bool DIExpression::extractLeadingOffset( 1768 int64_t &OffsetInBytes, SmallVectorImpl<uint64_t> &RemainingOps) const { 1769 OffsetInBytes = 0; 1770 RemainingOps.clear(); 1771 1772 auto SingleLocEltsOpt = getSingleLocationExpressionElements(); 1773 if (!SingleLocEltsOpt) 1774 return false; 1775 1776 auto ExprOpEnd = expr_op_iterator(SingleLocEltsOpt->end()); 1777 auto ExprOpIt = expr_op_iterator(SingleLocEltsOpt->begin()); 1778 while (ExprOpIt != ExprOpEnd) { 1779 uint64_t Op = ExprOpIt->getOp(); 1780 if (Op == dwarf::DW_OP_deref || Op == dwarf::DW_OP_deref_size || 1781 Op == dwarf::DW_OP_deref_type || Op == dwarf::DW_OP_LLVM_fragment || 1782 Op == dwarf::DW_OP_LLVM_extract_bits_zext || 1783 Op == dwarf::DW_OP_LLVM_extract_bits_sext) { 1784 break; 1785 } else if (Op == dwarf::DW_OP_plus_uconst) { 1786 OffsetInBytes += ExprOpIt->getArg(0); 1787 } else if (Op == dwarf::DW_OP_constu) { 1788 uint64_t Value = ExprOpIt->getArg(0); 1789 ++ExprOpIt; 1790 if (ExprOpIt->getOp() == dwarf::DW_OP_plus) 1791 OffsetInBytes += Value; 1792 else if (ExprOpIt->getOp() == dwarf::DW_OP_minus) 1793 OffsetInBytes -= Value; 1794 else 1795 return false; 1796 } else { 1797 // Not a const plus/minus operation or deref. 1798 return false; 1799 } 1800 ++ExprOpIt; 1801 } 1802 RemainingOps.append(ExprOpIt.getBase(), ExprOpEnd.getBase()); 1803 return true; 1804 } 1805 1806 bool DIExpression::hasAllLocationOps(unsigned N) const { 1807 SmallDenseSet<uint64_t, 4> SeenOps; 1808 for (auto ExprOp : expr_ops()) 1809 if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg) 1810 SeenOps.insert(ExprOp.getArg(0)); 1811 for (uint64_t Idx = 0; Idx < N; ++Idx) 1812 if (!SeenOps.contains(Idx)) 1813 return false; 1814 return true; 1815 } 1816 1817 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr, 1818 unsigned &AddrClass) { 1819 // FIXME: This seems fragile. Nothing that verifies that these elements 1820 // actually map to ops and not operands. 1821 auto SingleLocEltsOpt = Expr->getSingleLocationExpressionElements(); 1822 if (!SingleLocEltsOpt) 1823 return nullptr; 1824 auto SingleLocElts = *SingleLocEltsOpt; 1825 1826 const unsigned PatternSize = 4; 1827 if (SingleLocElts.size() >= PatternSize && 1828 SingleLocElts[PatternSize - 4] == dwarf::DW_OP_constu && 1829 SingleLocElts[PatternSize - 2] == dwarf::DW_OP_swap && 1830 SingleLocElts[PatternSize - 1] == dwarf::DW_OP_xderef) { 1831 AddrClass = SingleLocElts[PatternSize - 3]; 1832 1833 if (SingleLocElts.size() == PatternSize) 1834 return nullptr; 1835 return DIExpression::get( 1836 Expr->getContext(), 1837 ArrayRef(&*SingleLocElts.begin(), SingleLocElts.size() - PatternSize)); 1838 } 1839 return Expr; 1840 } 1841 1842 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags, 1843 int64_t Offset) { 1844 SmallVector<uint64_t, 8> Ops; 1845 if (Flags & DIExpression::DerefBefore) 1846 Ops.push_back(dwarf::DW_OP_deref); 1847 1848 appendOffset(Ops, Offset); 1849 if (Flags & DIExpression::DerefAfter) 1850 Ops.push_back(dwarf::DW_OP_deref); 1851 1852 bool StackValue = Flags & DIExpression::StackValue; 1853 bool EntryValue = Flags & DIExpression::EntryValue; 1854 1855 return prependOpcodes(Expr, Ops, StackValue, EntryValue); 1856 } 1857 1858 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr, 1859 ArrayRef<uint64_t> Ops, 1860 unsigned ArgNo, bool StackValue) { 1861 assert(Expr && "Can't add ops to this expression"); 1862 1863 // Handle non-variadic intrinsics by prepending the opcodes. 1864 if (!any_of(Expr->expr_ops(), 1865 [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) { 1866 assert(ArgNo == 0 && 1867 "Location Index must be 0 for a non-variadic expression."); 1868 SmallVector<uint64_t, 8> NewOps(Ops); 1869 return DIExpression::prependOpcodes(Expr, NewOps, StackValue); 1870 } 1871 1872 SmallVector<uint64_t, 8> NewOps; 1873 for (auto Op : Expr->expr_ops()) { 1874 // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment. 1875 if (StackValue) { 1876 if (Op.getOp() == dwarf::DW_OP_stack_value) 1877 StackValue = false; 1878 else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1879 NewOps.push_back(dwarf::DW_OP_stack_value); 1880 StackValue = false; 1881 } 1882 } 1883 Op.appendToVector(NewOps); 1884 if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo) 1885 NewOps.insert(NewOps.end(), Ops.begin(), Ops.end()); 1886 } 1887 if (StackValue) 1888 NewOps.push_back(dwarf::DW_OP_stack_value); 1889 1890 return DIExpression::get(Expr->getContext(), NewOps); 1891 } 1892 1893 DIExpression *DIExpression::replaceArg(const DIExpression *Expr, 1894 uint64_t OldArg, uint64_t NewArg) { 1895 assert(Expr && "Can't replace args in this expression"); 1896 1897 SmallVector<uint64_t, 8> NewOps; 1898 1899 for (auto Op : Expr->expr_ops()) { 1900 if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) { 1901 Op.appendToVector(NewOps); 1902 continue; 1903 } 1904 NewOps.push_back(dwarf::DW_OP_LLVM_arg); 1905 uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0); 1906 // OldArg has been deleted from the Op list, so decrement all indices 1907 // greater than it. 1908 if (Arg > OldArg) 1909 --Arg; 1910 NewOps.push_back(Arg); 1911 } 1912 return DIExpression::get(Expr->getContext(), NewOps); 1913 } 1914 1915 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr, 1916 SmallVectorImpl<uint64_t> &Ops, 1917 bool StackValue, bool EntryValue) { 1918 assert(Expr && "Can't prepend ops to this expression"); 1919 1920 if (EntryValue) { 1921 Ops.push_back(dwarf::DW_OP_LLVM_entry_value); 1922 // Use a block size of 1 for the target register operand. The 1923 // DWARF backend currently cannot emit entry values with a block 1924 // size > 1. 1925 Ops.push_back(1); 1926 } 1927 1928 // If there are no ops to prepend, do not even add the DW_OP_stack_value. 1929 if (Ops.empty()) 1930 StackValue = false; 1931 for (auto Op : Expr->expr_ops()) { 1932 // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment. 1933 if (StackValue) { 1934 if (Op.getOp() == dwarf::DW_OP_stack_value) 1935 StackValue = false; 1936 else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1937 Ops.push_back(dwarf::DW_OP_stack_value); 1938 StackValue = false; 1939 } 1940 } 1941 Op.appendToVector(Ops); 1942 } 1943 if (StackValue) 1944 Ops.push_back(dwarf::DW_OP_stack_value); 1945 return DIExpression::get(Expr->getContext(), Ops); 1946 } 1947 1948 DIExpression *DIExpression::append(const DIExpression *Expr, 1949 ArrayRef<uint64_t> Ops) { 1950 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1951 1952 // Copy Expr's current op list. 1953 SmallVector<uint64_t, 16> NewOps; 1954 for (auto Op : Expr->expr_ops()) { 1955 // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}. 1956 if (Op.getOp() == dwarf::DW_OP_stack_value || 1957 Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1958 NewOps.append(Ops.begin(), Ops.end()); 1959 1960 // Ensure that the new opcodes are only appended once. 1961 Ops = {}; 1962 } 1963 Op.appendToVector(NewOps); 1964 } 1965 NewOps.append(Ops.begin(), Ops.end()); 1966 auto *result = 1967 DIExpression::get(Expr->getContext(), NewOps)->foldConstantMath(); 1968 assert(result->isValid() && "concatenated expression is not valid"); 1969 return result; 1970 } 1971 1972 DIExpression *DIExpression::appendToStack(const DIExpression *Expr, 1973 ArrayRef<uint64_t> Ops) { 1974 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1975 assert(std::none_of(expr_op_iterator(Ops.begin()), 1976 expr_op_iterator(Ops.end()), 1977 [](auto Op) { 1978 return Op.getOp() == dwarf::DW_OP_stack_value || 1979 Op.getOp() == dwarf::DW_OP_LLVM_fragment; 1980 }) && 1981 "Can't append this op"); 1982 1983 // Append a DW_OP_deref after Expr's current op list if it's non-empty and 1984 // has no DW_OP_stack_value. 1985 // 1986 // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?. 1987 std::optional<FragmentInfo> FI = Expr->getFragmentInfo(); 1988 unsigned DropUntilStackValue = FI ? 3 : 0; 1989 ArrayRef<uint64_t> ExprOpsBeforeFragment = 1990 Expr->getElements().drop_back(DropUntilStackValue); 1991 bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) && 1992 (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value); 1993 bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty(); 1994 1995 // Append a DW_OP_deref after Expr's current op list if needed, then append 1996 // the new ops, and finally ensure that a single DW_OP_stack_value is present. 1997 SmallVector<uint64_t, 16> NewOps; 1998 if (NeedsDeref) 1999 NewOps.push_back(dwarf::DW_OP_deref); 2000 NewOps.append(Ops.begin(), Ops.end()); 2001 if (NeedsStackValue) 2002 NewOps.push_back(dwarf::DW_OP_stack_value); 2003 return DIExpression::append(Expr, NewOps); 2004 } 2005 2006 std::optional<DIExpression *> DIExpression::createFragmentExpression( 2007 const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) { 2008 SmallVector<uint64_t, 8> Ops; 2009 // Track whether it's safe to split the value at the top of the DWARF stack, 2010 // assuming that it'll be used as an implicit location value. 2011 bool CanSplitValue = true; 2012 // Track whether we need to add a fragment expression to the end of Expr. 2013 bool EmitFragment = true; 2014 // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment. 2015 if (Expr) { 2016 for (auto Op : Expr->expr_ops()) { 2017 switch (Op.getOp()) { 2018 default: 2019 break; 2020 case dwarf::DW_OP_shr: 2021 case dwarf::DW_OP_shra: 2022 case dwarf::DW_OP_shl: 2023 case dwarf::DW_OP_plus: 2024 case dwarf::DW_OP_plus_uconst: 2025 case dwarf::DW_OP_minus: 2026 // We can't safely split arithmetic or shift operations into multiple 2027 // fragments because we can't express carry-over between fragments. 2028 // 2029 // FIXME: We *could* preserve the lowest fragment of a constant offset 2030 // operation if the offset fits into SizeInBits. 2031 CanSplitValue = false; 2032 break; 2033 case dwarf::DW_OP_deref: 2034 case dwarf::DW_OP_deref_size: 2035 case dwarf::DW_OP_deref_type: 2036 case dwarf::DW_OP_xderef: 2037 case dwarf::DW_OP_xderef_size: 2038 case dwarf::DW_OP_xderef_type: 2039 // Preceeding arithmetic operations have been applied to compute an 2040 // address. It's okay to split the value loaded from that address. 2041 CanSplitValue = true; 2042 break; 2043 case dwarf::DW_OP_stack_value: 2044 // Bail if this expression computes a value that cannot be split. 2045 if (!CanSplitValue) 2046 return std::nullopt; 2047 break; 2048 case dwarf::DW_OP_LLVM_fragment: { 2049 // If we've decided we don't need a fragment then give up if we see that 2050 // there's already a fragment expression. 2051 // FIXME: We could probably do better here 2052 if (!EmitFragment) 2053 return std::nullopt; 2054 // Make the new offset point into the existing fragment. 2055 uint64_t FragmentOffsetInBits = Op.getArg(0); 2056 uint64_t FragmentSizeInBits = Op.getArg(1); 2057 (void)FragmentSizeInBits; 2058 assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) && 2059 "new fragment outside of original fragment"); 2060 OffsetInBits += FragmentOffsetInBits; 2061 continue; 2062 } 2063 case dwarf::DW_OP_LLVM_extract_bits_zext: 2064 case dwarf::DW_OP_LLVM_extract_bits_sext: { 2065 // If we're extracting bits from inside of the fragment that we're 2066 // creating then we don't have a fragment after all, and just need to 2067 // adjust the offset that we're extracting from. 2068 uint64_t ExtractOffsetInBits = Op.getArg(0); 2069 uint64_t ExtractSizeInBits = Op.getArg(1); 2070 if (ExtractOffsetInBits >= OffsetInBits && 2071 ExtractOffsetInBits + ExtractSizeInBits <= 2072 OffsetInBits + SizeInBits) { 2073 Ops.push_back(Op.getOp()); 2074 Ops.push_back(ExtractOffsetInBits - OffsetInBits); 2075 Ops.push_back(ExtractSizeInBits); 2076 EmitFragment = false; 2077 continue; 2078 } 2079 // If the extracted bits aren't fully contained within the fragment then 2080 // give up. 2081 // FIXME: We could probably do better here 2082 return std::nullopt; 2083 } 2084 } 2085 Op.appendToVector(Ops); 2086 } 2087 } 2088 assert((!Expr->isImplicit() || CanSplitValue) && "Expr can't be split"); 2089 assert(Expr && "Unknown DIExpression"); 2090 if (EmitFragment) { 2091 Ops.push_back(dwarf::DW_OP_LLVM_fragment); 2092 Ops.push_back(OffsetInBits); 2093 Ops.push_back(SizeInBits); 2094 } 2095 return DIExpression::get(Expr->getContext(), Ops); 2096 } 2097 2098 /// See declaration for more info. 2099 bool DIExpression::calculateFragmentIntersect( 2100 const DataLayout &DL, const Value *SliceStart, uint64_t SliceOffsetInBits, 2101 uint64_t SliceSizeInBits, const Value *DbgPtr, int64_t DbgPtrOffsetInBits, 2102 int64_t DbgExtractOffsetInBits, DIExpression::FragmentInfo VarFrag, 2103 std::optional<DIExpression::FragmentInfo> &Result, 2104 int64_t &OffsetFromLocationInBits) { 2105 2106 if (VarFrag.SizeInBits == 0) 2107 return false; // Variable size is unknown. 2108 2109 // Difference between mem slice start and the dbg location start. 2110 // 0 4 8 12 16 ... 2111 // | | 2112 // dbg location start 2113 // | 2114 // mem slice start 2115 // Here MemStartRelToDbgStartInBits is 8. Note this can be negative. 2116 int64_t MemStartRelToDbgStartInBits; 2117 { 2118 auto MemOffsetFromDbgInBytes = SliceStart->getPointerOffsetFrom(DbgPtr, DL); 2119 if (!MemOffsetFromDbgInBytes) 2120 return false; // Can't calculate difference in addresses. 2121 // Difference between the pointers. 2122 MemStartRelToDbgStartInBits = *MemOffsetFromDbgInBytes * 8; 2123 // Add the difference of the offsets. 2124 MemStartRelToDbgStartInBits += 2125 SliceOffsetInBits - (DbgPtrOffsetInBits + DbgExtractOffsetInBits); 2126 } 2127 2128 // Out-param. Invert offset to get offset from debug location. 2129 OffsetFromLocationInBits = -MemStartRelToDbgStartInBits; 2130 2131 // Check if the variable fragment sits outside (before) this memory slice. 2132 int64_t MemEndRelToDbgStart = MemStartRelToDbgStartInBits + SliceSizeInBits; 2133 if (MemEndRelToDbgStart < 0) { 2134 Result = {0, 0}; // Out-param. 2135 return true; 2136 } 2137 2138 // Work towards creating SliceOfVariable which is the bits of the variable 2139 // that the memory region covers. 2140 // 0 4 8 12 16 ... 2141 // | | 2142 // dbg location start with VarFrag offset=32 2143 // | 2144 // mem slice start: SliceOfVariable offset=40 2145 int64_t MemStartRelToVarInBits = 2146 MemStartRelToDbgStartInBits + VarFrag.OffsetInBits; 2147 int64_t MemEndRelToVarInBits = MemStartRelToVarInBits + SliceSizeInBits; 2148 // If the memory region starts before the debug location the fragment 2149 // offset would be negative, which we can't encode. Limit those to 0. This 2150 // is fine because those bits necessarily don't overlap with the existing 2151 // variable fragment. 2152 int64_t MemFragStart = std::max<int64_t>(0, MemStartRelToVarInBits); 2153 int64_t MemFragSize = 2154 std::max<int64_t>(0, MemEndRelToVarInBits - MemFragStart); 2155 DIExpression::FragmentInfo SliceOfVariable(MemFragSize, MemFragStart); 2156 2157 // Intersect the memory region fragment with the variable location fragment. 2158 DIExpression::FragmentInfo TrimmedSliceOfVariable = 2159 DIExpression::FragmentInfo::intersect(SliceOfVariable, VarFrag); 2160 if (TrimmedSliceOfVariable == VarFrag) 2161 Result = std::nullopt; // Out-param. 2162 else 2163 Result = TrimmedSliceOfVariable; // Out-param. 2164 return true; 2165 } 2166 2167 std::pair<DIExpression *, const ConstantInt *> 2168 DIExpression::constantFold(const ConstantInt *CI) { 2169 // Copy the APInt so we can modify it. 2170 APInt NewInt = CI->getValue(); 2171 SmallVector<uint64_t, 8> Ops; 2172 2173 // Fold operators only at the beginning of the expression. 2174 bool First = true; 2175 bool Changed = false; 2176 for (auto Op : expr_ops()) { 2177 switch (Op.getOp()) { 2178 default: 2179 // We fold only the leading part of the expression; if we get to a part 2180 // that we're going to copy unchanged, and haven't done any folding, 2181 // then the entire expression is unchanged and we can return early. 2182 if (!Changed) 2183 return {this, CI}; 2184 First = false; 2185 break; 2186 case dwarf::DW_OP_LLVM_convert: 2187 if (!First) 2188 break; 2189 Changed = true; 2190 if (Op.getArg(1) == dwarf::DW_ATE_signed) 2191 NewInt = NewInt.sextOrTrunc(Op.getArg(0)); 2192 else { 2193 assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand"); 2194 NewInt = NewInt.zextOrTrunc(Op.getArg(0)); 2195 } 2196 continue; 2197 } 2198 Op.appendToVector(Ops); 2199 } 2200 if (!Changed) 2201 return {this, CI}; 2202 return {DIExpression::get(getContext(), Ops), 2203 ConstantInt::get(getContext(), NewInt)}; 2204 } 2205 2206 uint64_t DIExpression::getNumLocationOperands() const { 2207 uint64_t Result = 0; 2208 for (auto ExprOp : expr_ops()) 2209 if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg) 2210 Result = std::max(Result, ExprOp.getArg(0) + 1); 2211 assert(hasAllLocationOps(Result) && 2212 "Expression is missing one or more location operands."); 2213 return Result; 2214 } 2215 2216 std::optional<DIExpression::SignedOrUnsignedConstant> 2217 DIExpression::isConstant() const { 2218 2219 // Recognize signed and unsigned constants. 2220 // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value 2221 // (DW_OP_LLVM_fragment of Len). 2222 // An unsigned constant can be represented as 2223 // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len). 2224 2225 if ((getNumElements() != 2 && getNumElements() != 3 && 2226 getNumElements() != 6) || 2227 (getElement(0) != dwarf::DW_OP_consts && 2228 getElement(0) != dwarf::DW_OP_constu)) 2229 return std::nullopt; 2230 2231 if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts) 2232 return SignedOrUnsignedConstant::SignedConstant; 2233 2234 if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) || 2235 (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value || 2236 getElement(3) != dwarf::DW_OP_LLVM_fragment))) 2237 return std::nullopt; 2238 return getElement(0) == dwarf::DW_OP_constu 2239 ? SignedOrUnsignedConstant::UnsignedConstant 2240 : SignedOrUnsignedConstant::SignedConstant; 2241 } 2242 2243 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize, 2244 bool Signed) { 2245 dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned; 2246 DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK, 2247 dwarf::DW_OP_LLVM_convert, ToSize, TK}}; 2248 return Ops; 2249 } 2250 2251 DIExpression *DIExpression::appendExt(const DIExpression *Expr, 2252 unsigned FromSize, unsigned ToSize, 2253 bool Signed) { 2254 return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed)); 2255 } 2256 2257 DIGlobalVariableExpression * 2258 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable, 2259 Metadata *Expression, StorageType Storage, 2260 bool ShouldCreate) { 2261 DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression)); 2262 Metadata *Ops[] = {Variable, Expression}; 2263 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops); 2264 } 2265 DIObjCProperty::DIObjCProperty(LLVMContext &C, StorageType Storage, 2266 unsigned Line, unsigned Attributes, 2267 ArrayRef<Metadata *> Ops) 2268 : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property, Ops), 2269 Line(Line), Attributes(Attributes) {} 2270 2271 DIObjCProperty *DIObjCProperty::getImpl( 2272 LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line, 2273 MDString *GetterName, MDString *SetterName, unsigned Attributes, 2274 Metadata *Type, StorageType Storage, bool ShouldCreate) { 2275 assert(isCanonical(Name) && "Expected canonical MDString"); 2276 assert(isCanonical(GetterName) && "Expected canonical MDString"); 2277 assert(isCanonical(SetterName) && "Expected canonical MDString"); 2278 DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName, 2279 SetterName, Attributes, Type)); 2280 Metadata *Ops[] = {Name, File, GetterName, SetterName, Type}; 2281 DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops); 2282 } 2283 2284 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag, 2285 Metadata *Scope, Metadata *Entity, 2286 Metadata *File, unsigned Line, 2287 MDString *Name, Metadata *Elements, 2288 StorageType Storage, 2289 bool ShouldCreate) { 2290 assert(isCanonical(Name) && "Expected canonical MDString"); 2291 DEFINE_GETIMPL_LOOKUP(DIImportedEntity, 2292 (Tag, Scope, Entity, File, Line, Name, Elements)); 2293 Metadata *Ops[] = {Scope, Entity, Name, File, Elements}; 2294 DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops); 2295 } 2296 2297 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, unsigned Line, 2298 MDString *Name, MDString *Value, StorageType Storage, 2299 bool ShouldCreate) { 2300 assert(isCanonical(Name) && "Expected canonical MDString"); 2301 DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value)); 2302 Metadata *Ops[] = {Name, Value}; 2303 DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops); 2304 } 2305 2306 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType, 2307 unsigned Line, Metadata *File, 2308 Metadata *Elements, StorageType Storage, 2309 bool ShouldCreate) { 2310 DEFINE_GETIMPL_LOOKUP(DIMacroFile, (MIType, Line, File, Elements)); 2311 Metadata *Ops[] = {File, Elements}; 2312 DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops); 2313 } 2314 2315 DIArgList *DIArgList::get(LLVMContext &Context, 2316 ArrayRef<ValueAsMetadata *> Args) { 2317 auto ExistingIt = Context.pImpl->DIArgLists.find_as(DIArgListKeyInfo(Args)); 2318 if (ExistingIt != Context.pImpl->DIArgLists.end()) 2319 return *ExistingIt; 2320 DIArgList *NewArgList = new DIArgList(Context, Args); 2321 Context.pImpl->DIArgLists.insert(NewArgList); 2322 return NewArgList; 2323 } 2324 2325 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) { 2326 ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref); 2327 assert((!New || isa<ValueAsMetadata>(New)) && 2328 "DIArgList must be passed a ValueAsMetadata"); 2329 untrack(); 2330 // We need to update the set storage once the Args are updated since they 2331 // form the key to the DIArgLists store. 2332 getContext().pImpl->DIArgLists.erase(this); 2333 ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New); 2334 for (ValueAsMetadata *&VM : Args) { 2335 if (&VM == OldVMPtr) { 2336 if (NewVM) 2337 VM = NewVM; 2338 else 2339 VM = ValueAsMetadata::get(PoisonValue::get(VM->getValue()->getType())); 2340 } 2341 } 2342 // We've changed the contents of this DIArgList, and the set storage may 2343 // already contain a DIArgList with our new set of args; if it does, then we 2344 // must RAUW this with the existing DIArgList, otherwise we simply insert this 2345 // back into the set storage. 2346 DIArgList *ExistingArgList = getUniqued(getContext().pImpl->DIArgLists, this); 2347 if (ExistingArgList) { 2348 replaceAllUsesWith(ExistingArgList); 2349 // Clear this here so we don't try to untrack in the destructor. 2350 Args.clear(); 2351 delete this; 2352 return; 2353 } 2354 getContext().pImpl->DIArgLists.insert(this); 2355 track(); 2356 } 2357 void DIArgList::track() { 2358 for (ValueAsMetadata *&VAM : Args) 2359 if (VAM) 2360 MetadataTracking::track(&VAM, *VAM, *this); 2361 } 2362 void DIArgList::untrack() { 2363 for (ValueAsMetadata *&VAM : Args) 2364 if (VAM) 2365 MetadataTracking::untrack(&VAM, *VAM); 2366 } 2367 void DIArgList::dropAllReferences(bool Untrack) { 2368 if (Untrack) 2369 untrack(); 2370 Args.clear(); 2371 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false); 2372 } 2373