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/SmallSet.h" 17 #include "llvm/ADT/StringSwitch.h" 18 #include "llvm/BinaryFormat/Dwarf.h" 19 #include "llvm/IR/Function.h" 20 #include "llvm/IR/Type.h" 21 #include "llvm/IR/Value.h" 22 23 #include <numeric> 24 25 using namespace llvm; 26 27 namespace llvm { 28 // Use FS-AFDO discriminator. 29 cl::opt<bool> EnableFSDiscriminator( 30 "enable-fs-discriminator", cl::Hidden, cl::init(false), 31 cl::desc("Enable adding flow sensitive discriminators")); 32 } // namespace llvm 33 34 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = { 35 std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()}; 36 37 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line, 38 unsigned Column, ArrayRef<Metadata *> MDs, 39 bool ImplicitCode) 40 : MDNode(C, DILocationKind, Storage, MDs) { 41 assert((MDs.size() == 1 || MDs.size() == 2) && 42 "Expected a scope and optional inlined-at"); 43 44 // Set line and column. 45 assert(Column < (1u << 16) && "Expected 16-bit column"); 46 47 SubclassData32 = Line; 48 SubclassData16 = Column; 49 50 setImplicitCode(ImplicitCode); 51 } 52 53 static void adjustColumn(unsigned &Column) { 54 // Set to unknown on overflow. We only have 16 bits to play with here. 55 if (Column >= (1u << 16)) 56 Column = 0; 57 } 58 59 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line, 60 unsigned Column, Metadata *Scope, 61 Metadata *InlinedAt, bool ImplicitCode, 62 StorageType Storage, bool ShouldCreate) { 63 // Fixup column. 64 adjustColumn(Column); 65 66 if (Storage == Uniqued) { 67 if (auto *N = getUniqued(Context.pImpl->DILocations, 68 DILocationInfo::KeyTy(Line, Column, Scope, 69 InlinedAt, ImplicitCode))) 70 return N; 71 if (!ShouldCreate) 72 return nullptr; 73 } else { 74 assert(ShouldCreate && "Expected non-uniqued nodes to always be created"); 75 } 76 77 SmallVector<Metadata *, 2> Ops; 78 Ops.push_back(Scope); 79 if (InlinedAt) 80 Ops.push_back(InlinedAt); 81 return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column, 82 Ops, ImplicitCode), 83 Storage, Context.pImpl->DILocations); 84 } 85 86 const DILocation * 87 DILocation::getMergedLocations(ArrayRef<const DILocation *> Locs) { 88 if (Locs.empty()) 89 return nullptr; 90 if (Locs.size() == 1) 91 return Locs[0]; 92 auto *Merged = Locs[0]; 93 for (const DILocation *L : llvm::drop_begin(Locs)) { 94 Merged = getMergedLocation(Merged, L); 95 if (Merged == nullptr) 96 break; 97 } 98 return Merged; 99 } 100 101 const DILocation *DILocation::getMergedLocation(const DILocation *LocA, 102 const DILocation *LocB) { 103 if (!LocA || !LocB) 104 return nullptr; 105 106 if (LocA == LocB) 107 return LocA; 108 109 SmallPtrSet<DILocation *, 5> InlinedLocationsA; 110 for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt()) 111 InlinedLocationsA.insert(L); 112 SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations; 113 DIScope *S = LocA->getScope(); 114 DILocation *L = LocA->getInlinedAt(); 115 while (S) { 116 Locations.insert(std::make_pair(S, L)); 117 S = S->getScope(); 118 if (!S && L) { 119 S = L->getScope(); 120 L = L->getInlinedAt(); 121 } 122 } 123 const DILocation *Result = LocB; 124 S = LocB->getScope(); 125 L = LocB->getInlinedAt(); 126 while (S) { 127 if (Locations.count(std::make_pair(S, L))) 128 break; 129 S = S->getScope(); 130 if (!S && L) { 131 S = L->getScope(); 132 L = L->getInlinedAt(); 133 } 134 } 135 136 // If the two locations are irreconsilable, just pick one. This is misleading, 137 // but on the other hand, it's a "line 0" location. 138 if (!S || !isa<DILocalScope>(S)) 139 S = LocA->getScope(); 140 return DILocation::get(Result->getContext(), 0, 0, S, L); 141 } 142 143 Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF, 144 unsigned CI) { 145 std::array<unsigned, 3> Components = {BD, DF, CI}; 146 uint64_t RemainingWork = 0U; 147 // We use RemainingWork to figure out if we have no remaining components to 148 // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to 149 // encode anything for the latter 2. 150 // Since any of the input components is at most 32 bits, their sum will be 151 // less than 34 bits, and thus RemainingWork won't overflow. 152 RemainingWork = 153 std::accumulate(Components.begin(), Components.end(), RemainingWork); 154 155 int I = 0; 156 unsigned Ret = 0; 157 unsigned NextBitInsertionIndex = 0; 158 while (RemainingWork > 0) { 159 unsigned C = Components[I++]; 160 RemainingWork -= C; 161 unsigned EC = encodeComponent(C); 162 Ret |= (EC << NextBitInsertionIndex); 163 NextBitInsertionIndex += encodingBits(C); 164 } 165 166 // Encoding may be unsuccessful because of overflow. We determine success by 167 // checking equivalence of components before & after encoding. Alternatively, 168 // we could determine Success during encoding, but the current alternative is 169 // simpler. 170 unsigned TBD, TDF, TCI = 0; 171 decodeDiscriminator(Ret, TBD, TDF, TCI); 172 if (TBD == BD && TDF == DF && TCI == CI) 173 return Ret; 174 return None; 175 } 176 177 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF, 178 unsigned &CI) { 179 BD = getUnsignedFromPrefixEncoding(D); 180 DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D)); 181 CI = getUnsignedFromPrefixEncoding( 182 getNextComponentInDiscriminator(getNextComponentInDiscriminator(D))); 183 } 184 dwarf::Tag DINode::getTag() const { return (dwarf::Tag)SubclassData16; } 185 186 DINode::DIFlags DINode::getFlag(StringRef Flag) { 187 return StringSwitch<DIFlags>(Flag) 188 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME) 189 #include "llvm/IR/DebugInfoFlags.def" 190 .Default(DINode::FlagZero); 191 } 192 193 StringRef DINode::getFlagString(DIFlags Flag) { 194 switch (Flag) { 195 #define HANDLE_DI_FLAG(ID, NAME) \ 196 case Flag##NAME: \ 197 return "DIFlag" #NAME; 198 #include "llvm/IR/DebugInfoFlags.def" 199 } 200 return ""; 201 } 202 203 DINode::DIFlags DINode::splitFlags(DIFlags Flags, 204 SmallVectorImpl<DIFlags> &SplitFlags) { 205 // Flags that are packed together need to be specially handled, so 206 // that, for example, we emit "DIFlagPublic" and not 207 // "DIFlagPrivate | DIFlagProtected". 208 if (DIFlags A = Flags & FlagAccessibility) { 209 if (A == FlagPrivate) 210 SplitFlags.push_back(FlagPrivate); 211 else if (A == FlagProtected) 212 SplitFlags.push_back(FlagProtected); 213 else 214 SplitFlags.push_back(FlagPublic); 215 Flags &= ~A; 216 } 217 if (DIFlags R = Flags & FlagPtrToMemberRep) { 218 if (R == FlagSingleInheritance) 219 SplitFlags.push_back(FlagSingleInheritance); 220 else if (R == FlagMultipleInheritance) 221 SplitFlags.push_back(FlagMultipleInheritance); 222 else 223 SplitFlags.push_back(FlagVirtualInheritance); 224 Flags &= ~R; 225 } 226 if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) { 227 Flags &= ~FlagIndirectVirtualBase; 228 SplitFlags.push_back(FlagIndirectVirtualBase); 229 } 230 231 #define HANDLE_DI_FLAG(ID, NAME) \ 232 if (DIFlags Bit = Flags & Flag##NAME) { \ 233 SplitFlags.push_back(Bit); \ 234 Flags &= ~Bit; \ 235 } 236 #include "llvm/IR/DebugInfoFlags.def" 237 return Flags; 238 } 239 240 DIScope *DIScope::getScope() const { 241 if (auto *T = dyn_cast<DIType>(this)) 242 return T->getScope(); 243 244 if (auto *SP = dyn_cast<DISubprogram>(this)) 245 return SP->getScope(); 246 247 if (auto *LB = dyn_cast<DILexicalBlockBase>(this)) 248 return LB->getScope(); 249 250 if (auto *NS = dyn_cast<DINamespace>(this)) 251 return NS->getScope(); 252 253 if (auto *CB = dyn_cast<DICommonBlock>(this)) 254 return CB->getScope(); 255 256 if (auto *M = dyn_cast<DIModule>(this)) 257 return M->getScope(); 258 259 assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) && 260 "Unhandled type of scope."); 261 return nullptr; 262 } 263 264 StringRef DIScope::getName() const { 265 if (auto *T = dyn_cast<DIType>(this)) 266 return T->getName(); 267 if (auto *SP = dyn_cast<DISubprogram>(this)) 268 return SP->getName(); 269 if (auto *NS = dyn_cast<DINamespace>(this)) 270 return NS->getName(); 271 if (auto *CB = dyn_cast<DICommonBlock>(this)) 272 return CB->getName(); 273 if (auto *M = dyn_cast<DIModule>(this)) 274 return M->getName(); 275 assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) || 276 isa<DICompileUnit>(this)) && 277 "Unhandled type of scope."); 278 return ""; 279 } 280 281 #ifndef NDEBUG 282 static bool isCanonical(const MDString *S) { 283 return !S || !S->getString().empty(); 284 } 285 #endif 286 287 dwarf::Tag GenericDINode::getTag() const { return (dwarf::Tag)SubclassData16; } 288 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag, 289 MDString *Header, 290 ArrayRef<Metadata *> DwarfOps, 291 StorageType Storage, bool ShouldCreate) { 292 unsigned Hash = 0; 293 if (Storage == Uniqued) { 294 GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps); 295 if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key)) 296 return N; 297 if (!ShouldCreate) 298 return nullptr; 299 Hash = Key.getHash(); 300 } else { 301 assert(ShouldCreate && "Expected non-uniqued nodes to always be created"); 302 } 303 304 // Use a nullptr for empty headers. 305 assert(isCanonical(Header) && "Expected canonical MDString"); 306 Metadata *PreOps[] = {Header}; 307 return storeImpl(new (DwarfOps.size() + 1) GenericDINode( 308 Context, Storage, Hash, Tag, PreOps, DwarfOps), 309 Storage, Context.pImpl->GenericDINodes); 310 } 311 312 void GenericDINode::recalculateHash() { 313 setHash(GenericDINodeInfo::KeyTy::calculateHash(this)); 314 } 315 316 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__ 317 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS 318 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS) \ 319 do { \ 320 if (Storage == Uniqued) { \ 321 if (auto *N = getUniqued(Context.pImpl->CLASS##s, \ 322 CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS)))) \ 323 return N; \ 324 if (!ShouldCreate) \ 325 return nullptr; \ 326 } else { \ 327 assert(ShouldCreate && \ 328 "Expected non-uniqued nodes to always be created"); \ 329 } \ 330 } while (false) 331 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \ 332 return storeImpl(new (array_lengthof(OPS)) \ 333 CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \ 334 Storage, Context.pImpl->CLASS##s) 335 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \ 336 return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \ 337 Storage, Context.pImpl->CLASS##s) 338 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \ 339 return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS), \ 340 Storage, Context.pImpl->CLASS##s) 341 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS) \ 342 return storeImpl(new (NUM_OPS) \ 343 CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \ 344 Storage, Context.pImpl->CLASS##s) 345 346 DISubrange::DISubrange(LLVMContext &C, StorageType Storage, 347 ArrayRef<Metadata *> Ops) 348 : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {} 349 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo, 350 StorageType Storage, bool ShouldCreate) { 351 auto *CountNode = ConstantAsMetadata::get( 352 ConstantInt::getSigned(Type::getInt64Ty(Context), Count)); 353 auto *LB = ConstantAsMetadata::get( 354 ConstantInt::getSigned(Type::getInt64Ty(Context), Lo)); 355 return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage, 356 ShouldCreate); 357 } 358 359 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 360 int64_t Lo, StorageType Storage, 361 bool ShouldCreate) { 362 auto *LB = ConstantAsMetadata::get( 363 ConstantInt::getSigned(Type::getInt64Ty(Context), Lo)); 364 return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage, 365 ShouldCreate); 366 } 367 368 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 369 Metadata *LB, Metadata *UB, Metadata *Stride, 370 StorageType Storage, bool ShouldCreate) { 371 DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride)); 372 Metadata *Ops[] = {CountNode, LB, UB, Stride}; 373 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops); 374 } 375 376 DISubrange::BoundType DISubrange::getCount() const { 377 Metadata *CB = getRawCountNode(); 378 if (!CB) 379 return BoundType(); 380 381 assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) || 382 isa<DIExpression>(CB)) && 383 "Count must be signed constant or DIVariable or DIExpression"); 384 385 if (auto *MD = dyn_cast<ConstantAsMetadata>(CB)) 386 return BoundType(cast<ConstantInt>(MD->getValue())); 387 388 if (auto *MD = dyn_cast<DIVariable>(CB)) 389 return BoundType(MD); 390 391 if (auto *MD = dyn_cast<DIExpression>(CB)) 392 return BoundType(MD); 393 394 return BoundType(); 395 } 396 397 DISubrange::BoundType DISubrange::getLowerBound() const { 398 Metadata *LB = getRawLowerBound(); 399 if (!LB) 400 return BoundType(); 401 402 assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) || 403 isa<DIExpression>(LB)) && 404 "LowerBound must be signed constant or DIVariable or DIExpression"); 405 406 if (auto *MD = dyn_cast<ConstantAsMetadata>(LB)) 407 return BoundType(cast<ConstantInt>(MD->getValue())); 408 409 if (auto *MD = dyn_cast<DIVariable>(LB)) 410 return BoundType(MD); 411 412 if (auto *MD = dyn_cast<DIExpression>(LB)) 413 return BoundType(MD); 414 415 return BoundType(); 416 } 417 418 DISubrange::BoundType DISubrange::getUpperBound() const { 419 Metadata *UB = getRawUpperBound(); 420 if (!UB) 421 return BoundType(); 422 423 assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) || 424 isa<DIExpression>(UB)) && 425 "UpperBound must be signed constant or DIVariable or DIExpression"); 426 427 if (auto *MD = dyn_cast<ConstantAsMetadata>(UB)) 428 return BoundType(cast<ConstantInt>(MD->getValue())); 429 430 if (auto *MD = dyn_cast<DIVariable>(UB)) 431 return BoundType(MD); 432 433 if (auto *MD = dyn_cast<DIExpression>(UB)) 434 return BoundType(MD); 435 436 return BoundType(); 437 } 438 439 DISubrange::BoundType DISubrange::getStride() const { 440 Metadata *ST = getRawStride(); 441 if (!ST) 442 return BoundType(); 443 444 assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) || 445 isa<DIExpression>(ST)) && 446 "Stride must be signed constant or DIVariable or DIExpression"); 447 448 if (auto *MD = dyn_cast<ConstantAsMetadata>(ST)) 449 return BoundType(cast<ConstantInt>(MD->getValue())); 450 451 if (auto *MD = dyn_cast<DIVariable>(ST)) 452 return BoundType(MD); 453 454 if (auto *MD = dyn_cast<DIExpression>(ST)) 455 return BoundType(MD); 456 457 return BoundType(); 458 } 459 DIGenericSubrange::DIGenericSubrange(LLVMContext &C, StorageType Storage, 460 ArrayRef<Metadata *> Ops) 461 : DINode(C, DIGenericSubrangeKind, Storage, dwarf::DW_TAG_generic_subrange, 462 Ops) {} 463 464 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context, 465 Metadata *CountNode, Metadata *LB, 466 Metadata *UB, Metadata *Stride, 467 StorageType Storage, 468 bool ShouldCreate) { 469 DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride)); 470 Metadata *Ops[] = {CountNode, LB, UB, Stride}; 471 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops); 472 } 473 474 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const { 475 Metadata *CB = getRawCountNode(); 476 if (!CB) 477 return BoundType(); 478 479 assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) && 480 "Count must be signed constant or DIVariable or DIExpression"); 481 482 if (auto *MD = dyn_cast<DIVariable>(CB)) 483 return BoundType(MD); 484 485 if (auto *MD = dyn_cast<DIExpression>(CB)) 486 return BoundType(MD); 487 488 return BoundType(); 489 } 490 491 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const { 492 Metadata *LB = getRawLowerBound(); 493 if (!LB) 494 return BoundType(); 495 496 assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) && 497 "LowerBound must be signed constant or DIVariable or DIExpression"); 498 499 if (auto *MD = dyn_cast<DIVariable>(LB)) 500 return BoundType(MD); 501 502 if (auto *MD = dyn_cast<DIExpression>(LB)) 503 return BoundType(MD); 504 505 return BoundType(); 506 } 507 508 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const { 509 Metadata *UB = getRawUpperBound(); 510 if (!UB) 511 return BoundType(); 512 513 assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) && 514 "UpperBound must be signed constant or DIVariable or DIExpression"); 515 516 if (auto *MD = dyn_cast<DIVariable>(UB)) 517 return BoundType(MD); 518 519 if (auto *MD = dyn_cast<DIExpression>(UB)) 520 return BoundType(MD); 521 522 return BoundType(); 523 } 524 525 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const { 526 Metadata *ST = getRawStride(); 527 if (!ST) 528 return BoundType(); 529 530 assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) && 531 "Stride must be signed constant or DIVariable or DIExpression"); 532 533 if (auto *MD = dyn_cast<DIVariable>(ST)) 534 return BoundType(MD); 535 536 if (auto *MD = dyn_cast<DIExpression>(ST)) 537 return BoundType(MD); 538 539 return BoundType(); 540 } 541 542 DIEnumerator::DIEnumerator(LLVMContext &C, StorageType Storage, 543 const APInt &Value, bool IsUnsigned, 544 ArrayRef<Metadata *> Ops) 545 : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops), 546 Value(Value) { 547 SubclassData32 = IsUnsigned; 548 } 549 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value, 550 bool IsUnsigned, MDString *Name, 551 StorageType Storage, bool ShouldCreate) { 552 assert(isCanonical(Name) && "Expected canonical MDString"); 553 DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name)); 554 Metadata *Ops[] = {Name}; 555 DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops); 556 } 557 558 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag, 559 MDString *Name, uint64_t SizeInBits, 560 uint32_t AlignInBits, unsigned Encoding, 561 DIFlags Flags, StorageType Storage, 562 bool ShouldCreate) { 563 assert(isCanonical(Name) && "Expected canonical MDString"); 564 DEFINE_GETIMPL_LOOKUP(DIBasicType, 565 (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags)); 566 Metadata *Ops[] = {nullptr, nullptr, Name}; 567 DEFINE_GETIMPL_STORE(DIBasicType, 568 (Tag, SizeInBits, AlignInBits, Encoding, Flags), Ops); 569 } 570 571 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const { 572 switch (getEncoding()) { 573 case dwarf::DW_ATE_signed: 574 case dwarf::DW_ATE_signed_char: 575 return Signedness::Signed; 576 case dwarf::DW_ATE_unsigned: 577 case dwarf::DW_ATE_unsigned_char: 578 return Signedness::Unsigned; 579 default: 580 return None; 581 } 582 } 583 584 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag, 585 MDString *Name, Metadata *StringLength, 586 Metadata *StringLengthExp, 587 Metadata *StringLocationExp, 588 uint64_t SizeInBits, uint32_t AlignInBits, 589 unsigned Encoding, StorageType Storage, 590 bool ShouldCreate) { 591 assert(isCanonical(Name) && "Expected canonical MDString"); 592 DEFINE_GETIMPL_LOOKUP(DIStringType, 593 (Tag, Name, StringLength, StringLengthExp, 594 StringLocationExp, SizeInBits, AlignInBits, Encoding)); 595 Metadata *Ops[] = {nullptr, nullptr, Name, 596 StringLength, StringLengthExp, StringLocationExp}; 597 DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding), 598 Ops); 599 } 600 DIType *DIDerivedType::getClassType() const { 601 assert(getTag() == dwarf::DW_TAG_ptr_to_member_type); 602 return cast_or_null<DIType>(getExtraData()); 603 } 604 uint32_t DIDerivedType::getVBPtrOffset() const { 605 assert(getTag() == dwarf::DW_TAG_inheritance); 606 if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData())) 607 if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue())) 608 return static_cast<uint32_t>(CI->getZExtValue()); 609 return 0; 610 } 611 Constant *DIDerivedType::getStorageOffsetInBits() const { 612 assert(getTag() == dwarf::DW_TAG_member && isBitField()); 613 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 614 return C->getValue(); 615 return nullptr; 616 } 617 618 Constant *DIDerivedType::getConstant() const { 619 assert(getTag() == dwarf::DW_TAG_member && isStaticMember()); 620 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 621 return C->getValue(); 622 return nullptr; 623 } 624 Constant *DIDerivedType::getDiscriminantValue() const { 625 assert(getTag() == dwarf::DW_TAG_member && !isStaticMember()); 626 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 627 return C->getValue(); 628 return nullptr; 629 } 630 631 DIDerivedType *DIDerivedType::getImpl( 632 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 633 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 634 uint32_t AlignInBits, uint64_t OffsetInBits, 635 Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData, 636 Metadata *Annotations, StorageType Storage, bool ShouldCreate) { 637 assert(isCanonical(Name) && "Expected canonical MDString"); 638 DEFINE_GETIMPL_LOOKUP(DIDerivedType, 639 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, 640 AlignInBits, OffsetInBits, DWARFAddressSpace, Flags, 641 ExtraData, Annotations)); 642 Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations}; 643 DEFINE_GETIMPL_STORE(DIDerivedType, 644 (Tag, Line, SizeInBits, AlignInBits, OffsetInBits, 645 DWARFAddressSpace, Flags), 646 Ops); 647 } 648 649 DICompositeType *DICompositeType::getImpl( 650 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 651 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 652 uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, 653 Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, 654 Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator, 655 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 656 Metadata *Rank, Metadata *Annotations, StorageType Storage, 657 bool ShouldCreate) { 658 assert(isCanonical(Name) && "Expected canonical MDString"); 659 660 // Keep this in sync with buildODRType. 661 DEFINE_GETIMPL_LOOKUP(DICompositeType, 662 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, 663 AlignInBits, OffsetInBits, Flags, Elements, 664 RuntimeLang, VTableHolder, TemplateParams, Identifier, 665 Discriminator, DataLocation, Associated, Allocated, 666 Rank, Annotations)); 667 Metadata *Ops[] = {File, Scope, Name, BaseType, 668 Elements, VTableHolder, TemplateParams, Identifier, 669 Discriminator, DataLocation, Associated, Allocated, 670 Rank, Annotations}; 671 DEFINE_GETIMPL_STORE( 672 DICompositeType, 673 (Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, Flags), 674 Ops); 675 } 676 677 DICompositeType *DICompositeType::buildODRType( 678 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 679 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 680 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 681 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, 682 Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, 683 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 684 Metadata *Rank, Metadata *Annotations) { 685 assert(!Identifier.getString().empty() && "Expected valid identifier"); 686 if (!Context.isODRUniquingDebugTypes()) 687 return nullptr; 688 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 689 if (!CT) 690 return CT = DICompositeType::getDistinct( 691 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 692 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 693 VTableHolder, TemplateParams, &Identifier, Discriminator, 694 DataLocation, Associated, Allocated, Rank, Annotations); 695 696 if (CT->getTag() != Tag) 697 return nullptr; 698 699 // Only mutate CT if it's a forward declaration and the new operands aren't. 700 assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?"); 701 if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl)) 702 return CT; 703 704 // Mutate CT in place. Keep this in sync with getImpl. 705 CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, 706 Flags); 707 Metadata *Ops[] = {File, Scope, Name, BaseType, 708 Elements, VTableHolder, TemplateParams, &Identifier, 709 Discriminator, DataLocation, Associated, Allocated, 710 Rank, Annotations}; 711 assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() && 712 "Mismatched number of operands"); 713 for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I) 714 if (Ops[I] != CT->getOperand(I)) 715 CT->setOperand(I, Ops[I]); 716 return CT; 717 } 718 719 DICompositeType *DICompositeType::getODRType( 720 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 721 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 722 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 723 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, 724 Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, 725 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 726 Metadata *Rank, Metadata *Annotations) { 727 assert(!Identifier.getString().empty() && "Expected valid identifier"); 728 if (!Context.isODRUniquingDebugTypes()) 729 return nullptr; 730 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 731 if (!CT) { 732 CT = DICompositeType::getDistinct( 733 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 734 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, 735 TemplateParams, &Identifier, Discriminator, DataLocation, Associated, 736 Allocated, Rank, Annotations); 737 } else { 738 if (CT->getTag() != Tag) 739 return nullptr; 740 } 741 return CT; 742 } 743 744 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context, 745 MDString &Identifier) { 746 assert(!Identifier.getString().empty() && "Expected valid identifier"); 747 if (!Context.isODRUniquingDebugTypes()) 748 return nullptr; 749 return Context.pImpl->DITypeMap->lookup(&Identifier); 750 } 751 DISubroutineType::DISubroutineType(LLVMContext &C, StorageType Storage, 752 DIFlags Flags, uint8_t CC, 753 ArrayRef<Metadata *> Ops) 754 : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type, 0, 755 0, 0, 0, Flags, Ops), 756 CC(CC) {} 757 758 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags, 759 uint8_t CC, Metadata *TypeArray, 760 StorageType Storage, 761 bool ShouldCreate) { 762 DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray)); 763 Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray}; 764 DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops); 765 } 766 767 DIFile::DIFile(LLVMContext &C, StorageType Storage, 768 Optional<ChecksumInfo<MDString *>> CS, Optional<MDString *> Src, 769 ArrayRef<Metadata *> Ops) 770 : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops), 771 Checksum(CS), Source(Src) {} 772 773 // FIXME: Implement this string-enum correspondence with a .def file and macros, 774 // so that the association is explicit rather than implied. 775 static const char *ChecksumKindName[DIFile::CSK_Last] = { 776 "CSK_MD5", 777 "CSK_SHA1", 778 "CSK_SHA256", 779 }; 780 781 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) { 782 assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind"); 783 // The first space was originally the CSK_None variant, which is now 784 // obsolete, but the space is still reserved in ChecksumKind, so we account 785 // for it here. 786 return ChecksumKindName[CSKind - 1]; 787 } 788 789 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) { 790 return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr) 791 .Case("CSK_MD5", DIFile::CSK_MD5) 792 .Case("CSK_SHA1", DIFile::CSK_SHA1) 793 .Case("CSK_SHA256", DIFile::CSK_SHA256) 794 .Default(None); 795 } 796 797 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename, 798 MDString *Directory, 799 Optional<DIFile::ChecksumInfo<MDString *>> CS, 800 Optional<MDString *> Source, StorageType Storage, 801 bool ShouldCreate) { 802 assert(isCanonical(Filename) && "Expected canonical MDString"); 803 assert(isCanonical(Directory) && "Expected canonical MDString"); 804 assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString"); 805 assert((!Source || isCanonical(*Source)) && "Expected canonical MDString"); 806 DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source)); 807 Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr, 808 Source.getValueOr(nullptr)}; 809 DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops); 810 } 811 DICompileUnit::DICompileUnit(LLVMContext &C, StorageType Storage, 812 unsigned SourceLanguage, bool IsOptimized, 813 unsigned RuntimeVersion, unsigned EmissionKind, 814 uint64_t DWOId, bool SplitDebugInlining, 815 bool DebugInfoForProfiling, unsigned NameTableKind, 816 bool RangesBaseAddress, ArrayRef<Metadata *> Ops) 817 : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops), 818 SourceLanguage(SourceLanguage), IsOptimized(IsOptimized), 819 RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind), DWOId(DWOId), 820 SplitDebugInlining(SplitDebugInlining), 821 DebugInfoForProfiling(DebugInfoForProfiling), 822 NameTableKind(NameTableKind), RangesBaseAddress(RangesBaseAddress) { 823 assert(Storage != Uniqued); 824 } 825 826 DICompileUnit *DICompileUnit::getImpl( 827 LLVMContext &Context, unsigned SourceLanguage, Metadata *File, 828 MDString *Producer, bool IsOptimized, MDString *Flags, 829 unsigned RuntimeVersion, MDString *SplitDebugFilename, 830 unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes, 831 Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros, 832 uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling, 833 unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot, 834 MDString *SDK, StorageType Storage, bool ShouldCreate) { 835 assert(Storage != Uniqued && "Cannot unique DICompileUnit"); 836 assert(isCanonical(Producer) && "Expected canonical MDString"); 837 assert(isCanonical(Flags) && "Expected canonical MDString"); 838 assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString"); 839 840 Metadata *Ops[] = {File, 841 Producer, 842 Flags, 843 SplitDebugFilename, 844 EnumTypes, 845 RetainedTypes, 846 GlobalVariables, 847 ImportedEntities, 848 Macros, 849 SysRoot, 850 SDK}; 851 return storeImpl(new (array_lengthof(Ops)) DICompileUnit( 852 Context, Storage, SourceLanguage, IsOptimized, 853 RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining, 854 DebugInfoForProfiling, NameTableKind, RangesBaseAddress, 855 Ops), 856 Storage); 857 } 858 859 Optional<DICompileUnit::DebugEmissionKind> 860 DICompileUnit::getEmissionKind(StringRef Str) { 861 return StringSwitch<Optional<DebugEmissionKind>>(Str) 862 .Case("NoDebug", NoDebug) 863 .Case("FullDebug", FullDebug) 864 .Case("LineTablesOnly", LineTablesOnly) 865 .Case("DebugDirectivesOnly", DebugDirectivesOnly) 866 .Default(None); 867 } 868 869 Optional<DICompileUnit::DebugNameTableKind> 870 DICompileUnit::getNameTableKind(StringRef Str) { 871 return StringSwitch<Optional<DebugNameTableKind>>(Str) 872 .Case("Default", DebugNameTableKind::Default) 873 .Case("GNU", DebugNameTableKind::GNU) 874 .Case("None", DebugNameTableKind::None) 875 .Default(None); 876 } 877 878 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) { 879 switch (EK) { 880 case NoDebug: 881 return "NoDebug"; 882 case FullDebug: 883 return "FullDebug"; 884 case LineTablesOnly: 885 return "LineTablesOnly"; 886 case DebugDirectivesOnly: 887 return "DebugDirectivesOnly"; 888 } 889 return nullptr; 890 } 891 892 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) { 893 switch (NTK) { 894 case DebugNameTableKind::Default: 895 return nullptr; 896 case DebugNameTableKind::GNU: 897 return "GNU"; 898 case DebugNameTableKind::None: 899 return "None"; 900 } 901 return nullptr; 902 } 903 DISubprogram::DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line, 904 unsigned ScopeLine, unsigned VirtualIndex, 905 int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, 906 ArrayRef<Metadata *> Ops) 907 : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram, Ops), 908 Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex), 909 ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) { 910 static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range"); 911 } 912 DISubprogram::DISPFlags 913 DISubprogram::toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, 914 unsigned Virtuality, bool IsMainSubprogram) { 915 // We're assuming virtuality is the low-order field. 916 static_assert(int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) && 917 int(SPFlagPureVirtual) == 918 int(dwarf::DW_VIRTUALITY_pure_virtual), 919 "Virtuality constant mismatch"); 920 return static_cast<DISPFlags>( 921 (Virtuality & SPFlagVirtuality) | 922 (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) | 923 (IsDefinition ? SPFlagDefinition : SPFlagZero) | 924 (IsOptimized ? SPFlagOptimized : SPFlagZero) | 925 (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero)); 926 } 927 928 DISubprogram *DILocalScope::getSubprogram() const { 929 if (auto *Block = dyn_cast<DILexicalBlockBase>(this)) 930 return Block->getScope()->getSubprogram(); 931 return const_cast<DISubprogram *>(cast<DISubprogram>(this)); 932 } 933 934 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const { 935 if (auto *File = dyn_cast<DILexicalBlockFile>(this)) 936 return File->getScope()->getNonLexicalBlockFileScope(); 937 return const_cast<DILocalScope *>(this); 938 } 939 940 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) { 941 return StringSwitch<DISPFlags>(Flag) 942 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME) 943 #include "llvm/IR/DebugInfoFlags.def" 944 .Default(SPFlagZero); 945 } 946 947 StringRef DISubprogram::getFlagString(DISPFlags Flag) { 948 switch (Flag) { 949 // Appease a warning. 950 case SPFlagVirtuality: 951 return ""; 952 #define HANDLE_DISP_FLAG(ID, NAME) \ 953 case SPFlag##NAME: \ 954 return "DISPFlag" #NAME; 955 #include "llvm/IR/DebugInfoFlags.def" 956 } 957 return ""; 958 } 959 960 DISubprogram::DISPFlags 961 DISubprogram::splitFlags(DISPFlags Flags, 962 SmallVectorImpl<DISPFlags> &SplitFlags) { 963 // Multi-bit fields can require special handling. In our case, however, the 964 // only multi-bit field is virtuality, and all its values happen to be 965 // single-bit values, so the right behavior just falls out. 966 #define HANDLE_DISP_FLAG(ID, NAME) \ 967 if (DISPFlags Bit = Flags & SPFlag##NAME) { \ 968 SplitFlags.push_back(Bit); \ 969 Flags &= ~Bit; \ 970 } 971 #include "llvm/IR/DebugInfoFlags.def" 972 return Flags; 973 } 974 975 DISubprogram *DISubprogram::getImpl( 976 LLVMContext &Context, Metadata *Scope, MDString *Name, 977 MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type, 978 unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex, 979 int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit, 980 Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes, 981 Metadata *ThrownTypes, Metadata *Annotations, StorageType Storage, 982 bool ShouldCreate) { 983 assert(isCanonical(Name) && "Expected canonical MDString"); 984 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 985 DEFINE_GETIMPL_LOOKUP(DISubprogram, 986 (Scope, Name, LinkageName, File, Line, Type, ScopeLine, 987 ContainingType, VirtualIndex, ThisAdjustment, Flags, 988 SPFlags, Unit, TemplateParams, Declaration, 989 RetainedNodes, ThrownTypes, Annotations)); 990 SmallVector<Metadata *, 12> Ops = { 991 File, Scope, Name, LinkageName, 992 Type, Unit, Declaration, RetainedNodes, 993 ContainingType, TemplateParams, ThrownTypes, Annotations}; 994 if (!Annotations) { 995 Ops.pop_back(); 996 if (!ThrownTypes) { 997 Ops.pop_back(); 998 if (!TemplateParams) { 999 Ops.pop_back(); 1000 if (!ContainingType) 1001 Ops.pop_back(); 1002 } 1003 } 1004 } 1005 DEFINE_GETIMPL_STORE_N( 1006 DISubprogram, 1007 (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops, 1008 Ops.size()); 1009 } 1010 1011 bool DISubprogram::describes(const Function *F) const { 1012 assert(F && "Invalid function"); 1013 return F->getSubprogram() == this; 1014 } 1015 DILexicalBlockBase::DILexicalBlockBase(LLVMContext &C, unsigned ID, 1016 StorageType Storage, 1017 ArrayRef<Metadata *> Ops) 1018 : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {} 1019 1020 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope, 1021 Metadata *File, unsigned Line, 1022 unsigned Column, StorageType Storage, 1023 bool ShouldCreate) { 1024 // Fixup column. 1025 adjustColumn(Column); 1026 1027 assert(Scope && "Expected scope"); 1028 DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column)); 1029 Metadata *Ops[] = {File, Scope}; 1030 DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops); 1031 } 1032 1033 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context, 1034 Metadata *Scope, Metadata *File, 1035 unsigned Discriminator, 1036 StorageType Storage, 1037 bool ShouldCreate) { 1038 assert(Scope && "Expected scope"); 1039 DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator)); 1040 Metadata *Ops[] = {File, Scope}; 1041 DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops); 1042 } 1043 1044 DINamespace::DINamespace(LLVMContext &Context, StorageType Storage, 1045 bool ExportSymbols, ArrayRef<Metadata *> Ops) 1046 : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace, Ops), 1047 ExportSymbols(ExportSymbols) {} 1048 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope, 1049 MDString *Name, bool ExportSymbols, 1050 StorageType Storage, bool ShouldCreate) { 1051 assert(isCanonical(Name) && "Expected canonical MDString"); 1052 DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols)); 1053 // The nullptr is for DIScope's File operand. This should be refactored. 1054 Metadata *Ops[] = {nullptr, Scope, Name}; 1055 DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops); 1056 } 1057 1058 DICommonBlock::DICommonBlock(LLVMContext &Context, StorageType Storage, 1059 unsigned LineNo, ArrayRef<Metadata *> Ops) 1060 : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block, 1061 Ops), 1062 LineNo(LineNo) {} 1063 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope, 1064 Metadata *Decl, MDString *Name, 1065 Metadata *File, unsigned LineNo, 1066 StorageType Storage, bool ShouldCreate) { 1067 assert(isCanonical(Name) && "Expected canonical MDString"); 1068 DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo)); 1069 // The nullptr is for DIScope's File operand. This should be refactored. 1070 Metadata *Ops[] = {Scope, Decl, Name, File}; 1071 DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops); 1072 } 1073 1074 DIModule::DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo, 1075 bool IsDecl, ArrayRef<Metadata *> Ops) 1076 : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops), 1077 LineNo(LineNo), IsDecl(IsDecl) {} 1078 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File, 1079 Metadata *Scope, MDString *Name, 1080 MDString *ConfigurationMacros, 1081 MDString *IncludePath, MDString *APINotesFile, 1082 unsigned LineNo, bool IsDecl, StorageType Storage, 1083 bool ShouldCreate) { 1084 assert(isCanonical(Name) && "Expected canonical MDString"); 1085 DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros, 1086 IncludePath, APINotesFile, LineNo, IsDecl)); 1087 Metadata *Ops[] = {File, Scope, Name, ConfigurationMacros, 1088 IncludePath, APINotesFile}; 1089 DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops); 1090 } 1091 DITemplateTypeParameter::DITemplateTypeParameter(LLVMContext &Context, 1092 StorageType Storage, 1093 bool IsDefault, 1094 ArrayRef<Metadata *> Ops) 1095 : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage, 1096 dwarf::DW_TAG_template_type_parameter, IsDefault, 1097 Ops) {} 1098 1099 DITemplateTypeParameter * 1100 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name, 1101 Metadata *Type, bool isDefault, 1102 StorageType Storage, bool ShouldCreate) { 1103 assert(isCanonical(Name) && "Expected canonical MDString"); 1104 DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault)); 1105 Metadata *Ops[] = {Name, Type}; 1106 DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops); 1107 } 1108 1109 DITemplateValueParameter *DITemplateValueParameter::getImpl( 1110 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type, 1111 bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) { 1112 assert(isCanonical(Name) && "Expected canonical MDString"); 1113 DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, 1114 (Tag, Name, Type, isDefault, Value)); 1115 Metadata *Ops[] = {Name, Type, Value}; 1116 DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops); 1117 } 1118 1119 DIGlobalVariable * 1120 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1121 MDString *LinkageName, Metadata *File, unsigned Line, 1122 Metadata *Type, bool IsLocalToUnit, bool IsDefinition, 1123 Metadata *StaticDataMemberDeclaration, 1124 Metadata *TemplateParams, uint32_t AlignInBits, 1125 Metadata *Annotations, StorageType Storage, 1126 bool ShouldCreate) { 1127 assert(isCanonical(Name) && "Expected canonical MDString"); 1128 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 1129 DEFINE_GETIMPL_LOOKUP( 1130 DIGlobalVariable, 1131 (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, 1132 StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations)); 1133 Metadata *Ops[] = {Scope, 1134 Name, 1135 File, 1136 Type, 1137 Name, 1138 LinkageName, 1139 StaticDataMemberDeclaration, 1140 TemplateParams, 1141 Annotations}; 1142 DEFINE_GETIMPL_STORE(DIGlobalVariable, 1143 (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops); 1144 } 1145 1146 DILocalVariable * 1147 DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1148 Metadata *File, unsigned Line, Metadata *Type, 1149 unsigned Arg, DIFlags Flags, uint32_t AlignInBits, 1150 Metadata *Annotations, StorageType Storage, 1151 bool ShouldCreate) { 1152 // 64K ought to be enough for any frontend. 1153 assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits"); 1154 1155 assert(Scope && "Expected scope"); 1156 assert(isCanonical(Name) && "Expected canonical MDString"); 1157 DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Scope, Name, File, Line, Type, Arg, 1158 Flags, AlignInBits, Annotations)); 1159 Metadata *Ops[] = {Scope, Name, File, Type, Annotations}; 1160 DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops); 1161 } 1162 1163 DIVariable::DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, 1164 signed Line, ArrayRef<Metadata *> Ops, 1165 uint32_t AlignInBits) 1166 : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line), 1167 AlignInBits(AlignInBits) {} 1168 Optional<uint64_t> DIVariable::getSizeInBits() const { 1169 // This is used by the Verifier so be mindful of broken types. 1170 const Metadata *RawType = getRawType(); 1171 while (RawType) { 1172 // Try to get the size directly. 1173 if (auto *T = dyn_cast<DIType>(RawType)) 1174 if (uint64_t Size = T->getSizeInBits()) 1175 return Size; 1176 1177 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 1178 // Look at the base type. 1179 RawType = DT->getRawBaseType(); 1180 continue; 1181 } 1182 1183 // Missing type or size. 1184 break; 1185 } 1186 1187 // Fail gracefully. 1188 return None; 1189 } 1190 1191 DILabel::DILabel(LLVMContext &C, StorageType Storage, unsigned Line, 1192 ArrayRef<Metadata *> Ops) 1193 : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops), Line(Line) {} 1194 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1195 Metadata *File, unsigned Line, StorageType Storage, 1196 bool ShouldCreate) { 1197 assert(Scope && "Expected scope"); 1198 assert(isCanonical(Name) && "Expected canonical MDString"); 1199 DEFINE_GETIMPL_LOOKUP(DILabel, (Scope, Name, File, Line)); 1200 Metadata *Ops[] = {Scope, Name, File}; 1201 DEFINE_GETIMPL_STORE(DILabel, (Line), Ops); 1202 } 1203 1204 DIExpression *DIExpression::getImpl(LLVMContext &Context, 1205 ArrayRef<uint64_t> Elements, 1206 StorageType Storage, bool ShouldCreate) { 1207 DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements)); 1208 DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements)); 1209 } 1210 bool DIExpression::isEntryValue() const { 1211 return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_LLVM_entry_value; 1212 } 1213 bool DIExpression::startsWithDeref() const { 1214 return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref; 1215 } 1216 1217 unsigned DIExpression::ExprOperand::getSize() const { 1218 uint64_t Op = getOp(); 1219 1220 if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31) 1221 return 2; 1222 1223 switch (Op) { 1224 case dwarf::DW_OP_LLVM_convert: 1225 case dwarf::DW_OP_LLVM_fragment: 1226 case dwarf::DW_OP_bregx: 1227 return 3; 1228 case dwarf::DW_OP_constu: 1229 case dwarf::DW_OP_consts: 1230 case dwarf::DW_OP_deref_size: 1231 case dwarf::DW_OP_plus_uconst: 1232 case dwarf::DW_OP_LLVM_tag_offset: 1233 case dwarf::DW_OP_LLVM_entry_value: 1234 case dwarf::DW_OP_LLVM_arg: 1235 case dwarf::DW_OP_regx: 1236 return 2; 1237 default: 1238 return 1; 1239 } 1240 } 1241 1242 bool DIExpression::isValid() const { 1243 for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) { 1244 // Check that there's space for the operand. 1245 if (I->get() + I->getSize() > E->get()) 1246 return false; 1247 1248 uint64_t Op = I->getOp(); 1249 if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) || 1250 (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)) 1251 return true; 1252 1253 // Check that the operand is valid. 1254 switch (Op) { 1255 default: 1256 return false; 1257 case dwarf::DW_OP_LLVM_fragment: 1258 // A fragment operator must appear at the end. 1259 return I->get() + I->getSize() == E->get(); 1260 case dwarf::DW_OP_stack_value: { 1261 // Must be the last one or followed by a DW_OP_LLVM_fragment. 1262 if (I->get() + I->getSize() == E->get()) 1263 break; 1264 auto J = I; 1265 if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment) 1266 return false; 1267 break; 1268 } 1269 case dwarf::DW_OP_swap: { 1270 // Must be more than one implicit element on the stack. 1271 1272 // FIXME: A better way to implement this would be to add a local variable 1273 // that keeps track of the stack depth and introduce something like a 1274 // DW_LLVM_OP_implicit_location as a placeholder for the location this 1275 // DIExpression is attached to, or else pass the number of implicit stack 1276 // elements into isValid. 1277 if (getNumElements() == 1) 1278 return false; 1279 break; 1280 } 1281 case dwarf::DW_OP_LLVM_entry_value: { 1282 // An entry value operator must appear at the beginning and the number of 1283 // operations it cover can currently only be 1, because we support only 1284 // entry values of a simple register location. One reason for this is that 1285 // we currently can't calculate the size of the resulting DWARF block for 1286 // other expressions. 1287 return I->get() == expr_op_begin()->get() && I->getArg(0) == 1; 1288 } 1289 case dwarf::DW_OP_LLVM_implicit_pointer: 1290 case dwarf::DW_OP_LLVM_convert: 1291 case dwarf::DW_OP_LLVM_arg: 1292 case dwarf::DW_OP_LLVM_tag_offset: 1293 case dwarf::DW_OP_constu: 1294 case dwarf::DW_OP_plus_uconst: 1295 case dwarf::DW_OP_plus: 1296 case dwarf::DW_OP_minus: 1297 case dwarf::DW_OP_mul: 1298 case dwarf::DW_OP_div: 1299 case dwarf::DW_OP_mod: 1300 case dwarf::DW_OP_or: 1301 case dwarf::DW_OP_and: 1302 case dwarf::DW_OP_xor: 1303 case dwarf::DW_OP_shl: 1304 case dwarf::DW_OP_shr: 1305 case dwarf::DW_OP_shra: 1306 case dwarf::DW_OP_deref: 1307 case dwarf::DW_OP_deref_size: 1308 case dwarf::DW_OP_xderef: 1309 case dwarf::DW_OP_lit0: 1310 case dwarf::DW_OP_not: 1311 case dwarf::DW_OP_dup: 1312 case dwarf::DW_OP_regx: 1313 case dwarf::DW_OP_bregx: 1314 case dwarf::DW_OP_push_object_address: 1315 case dwarf::DW_OP_over: 1316 case dwarf::DW_OP_consts: 1317 break; 1318 } 1319 } 1320 return true; 1321 } 1322 1323 bool DIExpression::isImplicit() const { 1324 if (!isValid()) 1325 return false; 1326 1327 if (getNumElements() == 0) 1328 return false; 1329 1330 for (const auto &It : expr_ops()) { 1331 switch (It.getOp()) { 1332 default: 1333 break; 1334 case dwarf::DW_OP_stack_value: 1335 case dwarf::DW_OP_LLVM_tag_offset: 1336 return true; 1337 } 1338 } 1339 1340 return false; 1341 } 1342 1343 bool DIExpression::isComplex() const { 1344 if (!isValid()) 1345 return false; 1346 1347 if (getNumElements() == 0) 1348 return false; 1349 1350 // If there are any elements other than fragment or tag_offset, then some 1351 // kind of complex computation occurs. 1352 for (const auto &It : expr_ops()) { 1353 switch (It.getOp()) { 1354 case dwarf::DW_OP_LLVM_tag_offset: 1355 case dwarf::DW_OP_LLVM_fragment: 1356 continue; 1357 default: 1358 return true; 1359 } 1360 } 1361 1362 return false; 1363 } 1364 1365 Optional<DIExpression::FragmentInfo> 1366 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) { 1367 for (auto I = Start; I != End; ++I) 1368 if (I->getOp() == dwarf::DW_OP_LLVM_fragment) { 1369 DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)}; 1370 return Info; 1371 } 1372 return None; 1373 } 1374 1375 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops, 1376 int64_t Offset) { 1377 if (Offset > 0) { 1378 Ops.push_back(dwarf::DW_OP_plus_uconst); 1379 Ops.push_back(Offset); 1380 } else if (Offset < 0) { 1381 Ops.push_back(dwarf::DW_OP_constu); 1382 Ops.push_back(-Offset); 1383 Ops.push_back(dwarf::DW_OP_minus); 1384 } 1385 } 1386 1387 bool DIExpression::extractIfOffset(int64_t &Offset) const { 1388 if (getNumElements() == 0) { 1389 Offset = 0; 1390 return true; 1391 } 1392 1393 if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) { 1394 Offset = Elements[1]; 1395 return true; 1396 } 1397 1398 if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) { 1399 if (Elements[2] == dwarf::DW_OP_plus) { 1400 Offset = Elements[1]; 1401 return true; 1402 } 1403 if (Elements[2] == dwarf::DW_OP_minus) { 1404 Offset = -Elements[1]; 1405 return true; 1406 } 1407 } 1408 1409 return false; 1410 } 1411 1412 bool DIExpression::hasAllLocationOps(unsigned N) const { 1413 SmallDenseSet<uint64_t, 4> SeenOps; 1414 for (auto ExprOp : expr_ops()) 1415 if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg) 1416 SeenOps.insert(ExprOp.getArg(0)); 1417 for (uint64_t Idx = 0; Idx < N; ++Idx) 1418 if (!is_contained(SeenOps, Idx)) 1419 return false; 1420 return true; 1421 } 1422 1423 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr, 1424 unsigned &AddrClass) { 1425 // FIXME: This seems fragile. Nothing that verifies that these elements 1426 // actually map to ops and not operands. 1427 const unsigned PatternSize = 4; 1428 if (Expr->Elements.size() >= PatternSize && 1429 Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu && 1430 Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap && 1431 Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) { 1432 AddrClass = Expr->Elements[PatternSize - 3]; 1433 1434 if (Expr->Elements.size() == PatternSize) 1435 return nullptr; 1436 return DIExpression::get(Expr->getContext(), 1437 makeArrayRef(&*Expr->Elements.begin(), 1438 Expr->Elements.size() - PatternSize)); 1439 } 1440 return Expr; 1441 } 1442 1443 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags, 1444 int64_t Offset) { 1445 SmallVector<uint64_t, 8> Ops; 1446 if (Flags & DIExpression::DerefBefore) 1447 Ops.push_back(dwarf::DW_OP_deref); 1448 1449 appendOffset(Ops, Offset); 1450 if (Flags & DIExpression::DerefAfter) 1451 Ops.push_back(dwarf::DW_OP_deref); 1452 1453 bool StackValue = Flags & DIExpression::StackValue; 1454 bool EntryValue = Flags & DIExpression::EntryValue; 1455 1456 return prependOpcodes(Expr, Ops, StackValue, EntryValue); 1457 } 1458 1459 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr, 1460 ArrayRef<uint64_t> Ops, 1461 unsigned ArgNo, bool StackValue) { 1462 assert(Expr && "Can't add ops to this expression"); 1463 1464 // Handle non-variadic intrinsics by prepending the opcodes. 1465 if (!any_of(Expr->expr_ops(), 1466 [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) { 1467 assert(ArgNo == 0 && 1468 "Location Index must be 0 for a non-variadic expression."); 1469 SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end()); 1470 return DIExpression::prependOpcodes(Expr, NewOps, StackValue); 1471 } 1472 1473 SmallVector<uint64_t, 8> NewOps; 1474 for (auto Op : Expr->expr_ops()) { 1475 Op.appendToVector(NewOps); 1476 if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo) 1477 NewOps.insert(NewOps.end(), Ops.begin(), Ops.end()); 1478 } 1479 1480 return DIExpression::get(Expr->getContext(), NewOps); 1481 } 1482 1483 DIExpression *DIExpression::replaceArg(const DIExpression *Expr, 1484 uint64_t OldArg, uint64_t NewArg) { 1485 assert(Expr && "Can't replace args in this expression"); 1486 1487 SmallVector<uint64_t, 8> NewOps; 1488 1489 for (auto Op : Expr->expr_ops()) { 1490 if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) { 1491 Op.appendToVector(NewOps); 1492 continue; 1493 } 1494 NewOps.push_back(dwarf::DW_OP_LLVM_arg); 1495 uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0); 1496 // OldArg has been deleted from the Op list, so decrement all indices 1497 // greater than it. 1498 if (Arg > OldArg) 1499 --Arg; 1500 NewOps.push_back(Arg); 1501 } 1502 return DIExpression::get(Expr->getContext(), NewOps); 1503 } 1504 1505 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr, 1506 SmallVectorImpl<uint64_t> &Ops, 1507 bool StackValue, bool EntryValue) { 1508 assert(Expr && "Can't prepend ops to this expression"); 1509 1510 if (EntryValue) { 1511 Ops.push_back(dwarf::DW_OP_LLVM_entry_value); 1512 // Use a block size of 1 for the target register operand. The 1513 // DWARF backend currently cannot emit entry values with a block 1514 // size > 1. 1515 Ops.push_back(1); 1516 } 1517 1518 // If there are no ops to prepend, do not even add the DW_OP_stack_value. 1519 if (Ops.empty()) 1520 StackValue = false; 1521 for (auto Op : Expr->expr_ops()) { 1522 // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment. 1523 if (StackValue) { 1524 if (Op.getOp() == dwarf::DW_OP_stack_value) 1525 StackValue = false; 1526 else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1527 Ops.push_back(dwarf::DW_OP_stack_value); 1528 StackValue = false; 1529 } 1530 } 1531 Op.appendToVector(Ops); 1532 } 1533 if (StackValue) 1534 Ops.push_back(dwarf::DW_OP_stack_value); 1535 return DIExpression::get(Expr->getContext(), Ops); 1536 } 1537 1538 DIExpression *DIExpression::append(const DIExpression *Expr, 1539 ArrayRef<uint64_t> Ops) { 1540 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1541 1542 // Copy Expr's current op list. 1543 SmallVector<uint64_t, 16> NewOps; 1544 for (auto Op : Expr->expr_ops()) { 1545 // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}. 1546 if (Op.getOp() == dwarf::DW_OP_stack_value || 1547 Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1548 NewOps.append(Ops.begin(), Ops.end()); 1549 1550 // Ensure that the new opcodes are only appended once. 1551 Ops = None; 1552 } 1553 Op.appendToVector(NewOps); 1554 } 1555 1556 NewOps.append(Ops.begin(), Ops.end()); 1557 auto *result = DIExpression::get(Expr->getContext(), NewOps); 1558 assert(result->isValid() && "concatenated expression is not valid"); 1559 return result; 1560 } 1561 1562 DIExpression *DIExpression::appendToStack(const DIExpression *Expr, 1563 ArrayRef<uint64_t> Ops) { 1564 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1565 assert(none_of(Ops, 1566 [](uint64_t Op) { 1567 return Op == dwarf::DW_OP_stack_value || 1568 Op == dwarf::DW_OP_LLVM_fragment; 1569 }) && 1570 "Can't append this op"); 1571 1572 // Append a DW_OP_deref after Expr's current op list if it's non-empty and 1573 // has no DW_OP_stack_value. 1574 // 1575 // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?. 1576 Optional<FragmentInfo> FI = Expr->getFragmentInfo(); 1577 unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0; 1578 ArrayRef<uint64_t> ExprOpsBeforeFragment = 1579 Expr->getElements().drop_back(DropUntilStackValue); 1580 bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) && 1581 (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value); 1582 bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty(); 1583 1584 // Append a DW_OP_deref after Expr's current op list if needed, then append 1585 // the new ops, and finally ensure that a single DW_OP_stack_value is present. 1586 SmallVector<uint64_t, 16> NewOps; 1587 if (NeedsDeref) 1588 NewOps.push_back(dwarf::DW_OP_deref); 1589 NewOps.append(Ops.begin(), Ops.end()); 1590 if (NeedsStackValue) 1591 NewOps.push_back(dwarf::DW_OP_stack_value); 1592 return DIExpression::append(Expr, NewOps); 1593 } 1594 1595 Optional<DIExpression *> DIExpression::createFragmentExpression( 1596 const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) { 1597 SmallVector<uint64_t, 8> Ops; 1598 // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment. 1599 if (Expr) { 1600 for (auto Op : Expr->expr_ops()) { 1601 switch (Op.getOp()) { 1602 default: 1603 break; 1604 case dwarf::DW_OP_shr: 1605 case dwarf::DW_OP_shra: 1606 case dwarf::DW_OP_shl: 1607 case dwarf::DW_OP_plus: 1608 case dwarf::DW_OP_plus_uconst: 1609 case dwarf::DW_OP_minus: 1610 // We can't safely split arithmetic or shift operations into multiple 1611 // fragments because we can't express carry-over between fragments. 1612 // 1613 // FIXME: We *could* preserve the lowest fragment of a constant offset 1614 // operation if the offset fits into SizeInBits. 1615 return None; 1616 case dwarf::DW_OP_LLVM_fragment: { 1617 // Make the new offset point into the existing fragment. 1618 uint64_t FragmentOffsetInBits = Op.getArg(0); 1619 uint64_t FragmentSizeInBits = Op.getArg(1); 1620 (void)FragmentSizeInBits; 1621 assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) && 1622 "new fragment outside of original fragment"); 1623 OffsetInBits += FragmentOffsetInBits; 1624 continue; 1625 } 1626 } 1627 Op.appendToVector(Ops); 1628 } 1629 } 1630 assert(Expr && "Unknown DIExpression"); 1631 Ops.push_back(dwarf::DW_OP_LLVM_fragment); 1632 Ops.push_back(OffsetInBits); 1633 Ops.push_back(SizeInBits); 1634 return DIExpression::get(Expr->getContext(), Ops); 1635 } 1636 1637 std::pair<DIExpression *, const ConstantInt *> 1638 DIExpression::constantFold(const ConstantInt *CI) { 1639 // Copy the APInt so we can modify it. 1640 APInt NewInt = CI->getValue(); 1641 SmallVector<uint64_t, 8> Ops; 1642 1643 // Fold operators only at the beginning of the expression. 1644 bool First = true; 1645 bool Changed = false; 1646 for (auto Op : expr_ops()) { 1647 switch (Op.getOp()) { 1648 default: 1649 // We fold only the leading part of the expression; if we get to a part 1650 // that we're going to copy unchanged, and haven't done any folding, 1651 // then the entire expression is unchanged and we can return early. 1652 if (!Changed) 1653 return {this, CI}; 1654 First = false; 1655 break; 1656 case dwarf::DW_OP_LLVM_convert: 1657 if (!First) 1658 break; 1659 Changed = true; 1660 if (Op.getArg(1) == dwarf::DW_ATE_signed) 1661 NewInt = NewInt.sextOrTrunc(Op.getArg(0)); 1662 else { 1663 assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand"); 1664 NewInt = NewInt.zextOrTrunc(Op.getArg(0)); 1665 } 1666 continue; 1667 } 1668 Op.appendToVector(Ops); 1669 } 1670 if (!Changed) 1671 return {this, CI}; 1672 return {DIExpression::get(getContext(), Ops), 1673 ConstantInt::get(getContext(), NewInt)}; 1674 } 1675 1676 uint64_t DIExpression::getNumLocationOperands() const { 1677 uint64_t Result = 0; 1678 for (auto ExprOp : expr_ops()) 1679 if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg) 1680 Result = std::max(Result, ExprOp.getArg(0) + 1); 1681 assert(hasAllLocationOps(Result) && 1682 "Expression is missing one or more location operands."); 1683 return Result; 1684 } 1685 1686 llvm::Optional<DIExpression::SignedOrUnsignedConstant> 1687 DIExpression::isConstant() const { 1688 1689 // Recognize signed and unsigned constants. 1690 // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value 1691 // (DW_OP_LLVM_fragment of Len). 1692 // An unsigned constant can be represented as 1693 // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len). 1694 1695 if ((getNumElements() != 2 && getNumElements() != 3 && 1696 getNumElements() != 6) || 1697 (getElement(0) != dwarf::DW_OP_consts && 1698 getElement(0) != dwarf::DW_OP_constu)) 1699 return None; 1700 1701 if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts) 1702 return SignedOrUnsignedConstant::SignedConstant; 1703 1704 if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) || 1705 (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value || 1706 getElement(3) != dwarf::DW_OP_LLVM_fragment))) 1707 return None; 1708 return getElement(0) == dwarf::DW_OP_constu 1709 ? SignedOrUnsignedConstant::UnsignedConstant 1710 : SignedOrUnsignedConstant::SignedConstant; 1711 } 1712 1713 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize, 1714 bool Signed) { 1715 dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned; 1716 DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK, 1717 dwarf::DW_OP_LLVM_convert, ToSize, TK}}; 1718 return Ops; 1719 } 1720 1721 DIExpression *DIExpression::appendExt(const DIExpression *Expr, 1722 unsigned FromSize, unsigned ToSize, 1723 bool Signed) { 1724 return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed)); 1725 } 1726 1727 DIGlobalVariableExpression * 1728 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable, 1729 Metadata *Expression, StorageType Storage, 1730 bool ShouldCreate) { 1731 DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression)); 1732 Metadata *Ops[] = {Variable, Expression}; 1733 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops); 1734 } 1735 DIObjCProperty::DIObjCProperty(LLVMContext &C, StorageType Storage, 1736 unsigned Line, unsigned Attributes, 1737 ArrayRef<Metadata *> Ops) 1738 : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property, Ops), 1739 Line(Line), Attributes(Attributes) {} 1740 1741 DIObjCProperty *DIObjCProperty::getImpl( 1742 LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line, 1743 MDString *GetterName, MDString *SetterName, unsigned Attributes, 1744 Metadata *Type, StorageType Storage, bool ShouldCreate) { 1745 assert(isCanonical(Name) && "Expected canonical MDString"); 1746 assert(isCanonical(GetterName) && "Expected canonical MDString"); 1747 assert(isCanonical(SetterName) && "Expected canonical MDString"); 1748 DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName, 1749 SetterName, Attributes, Type)); 1750 Metadata *Ops[] = {Name, File, GetterName, SetterName, Type}; 1751 DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops); 1752 } 1753 1754 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag, 1755 Metadata *Scope, Metadata *Entity, 1756 Metadata *File, unsigned Line, 1757 MDString *Name, Metadata *Elements, 1758 StorageType Storage, 1759 bool ShouldCreate) { 1760 assert(isCanonical(Name) && "Expected canonical MDString"); 1761 DEFINE_GETIMPL_LOOKUP(DIImportedEntity, 1762 (Tag, Scope, Entity, File, Line, Name, Elements)); 1763 Metadata *Ops[] = {Scope, Entity, Name, File, Elements}; 1764 DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops); 1765 } 1766 1767 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, unsigned Line, 1768 MDString *Name, MDString *Value, StorageType Storage, 1769 bool ShouldCreate) { 1770 assert(isCanonical(Name) && "Expected canonical MDString"); 1771 DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value)); 1772 Metadata *Ops[] = {Name, Value}; 1773 DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops); 1774 } 1775 1776 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType, 1777 unsigned Line, Metadata *File, 1778 Metadata *Elements, StorageType Storage, 1779 bool ShouldCreate) { 1780 DEFINE_GETIMPL_LOOKUP(DIMacroFile, (MIType, Line, File, Elements)); 1781 Metadata *Ops[] = {File, Elements}; 1782 DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops); 1783 } 1784 1785 DIArgList *DIArgList::getImpl(LLVMContext &Context, 1786 ArrayRef<ValueAsMetadata *> Args, 1787 StorageType Storage, bool ShouldCreate) { 1788 DEFINE_GETIMPL_LOOKUP(DIArgList, (Args)); 1789 DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args)); 1790 } 1791 1792 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) { 1793 ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref); 1794 assert((!New || isa<ValueAsMetadata>(New)) && 1795 "DIArgList must be passed a ValueAsMetadata"); 1796 untrack(); 1797 bool Uniq = isUniqued(); 1798 if (Uniq) { 1799 // We need to update the uniqueness once the Args are updated since they 1800 // form the key to the DIArgLists store. 1801 eraseFromStore(); 1802 } 1803 ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New); 1804 for (ValueAsMetadata *&VM : Args) { 1805 if (&VM == OldVMPtr) { 1806 if (NewVM) 1807 VM = NewVM; 1808 else 1809 VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType())); 1810 } 1811 } 1812 if (Uniq) { 1813 if (uniquify() != this) 1814 storeDistinctInContext(); 1815 } 1816 track(); 1817 } 1818 void DIArgList::track() { 1819 for (ValueAsMetadata *&VAM : Args) 1820 if (VAM) 1821 MetadataTracking::track(&VAM, *VAM, *this); 1822 } 1823 void DIArgList::untrack() { 1824 for (ValueAsMetadata *&VAM : Args) 1825 if (VAM) 1826 MetadataTracking::untrack(&VAM, *VAM); 1827 } 1828 void DIArgList::dropAllReferences() { 1829 untrack(); 1830 Args.clear(); 1831 MDNode::dropAllReferences(); 1832 } 1833