1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===// 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 DIBuilder. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/DIBuilder.h" 14 #include "LLVMContextImpl.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/APSInt.h" 17 #include "llvm/BinaryFormat/Dwarf.h" 18 #include "llvm/IR/Constants.h" 19 #include "llvm/IR/DebugInfo.h" 20 #include "llvm/IR/IRBuilder.h" 21 #include "llvm/IR/Module.h" 22 #include "llvm/Support/CommandLine.h" 23 #include <optional> 24 25 using namespace llvm; 26 using namespace llvm::dwarf; 27 28 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes, DICompileUnit *CU) 29 : M(m), VMContext(M.getContext()), CUNode(CU), DeclareFn(nullptr), 30 ValueFn(nullptr), LabelFn(nullptr), AssignFn(nullptr), 31 AllowUnresolvedNodes(AllowUnresolvedNodes) { 32 if (CUNode) { 33 if (const auto &ETs = CUNode->getEnumTypes()) 34 AllEnumTypes.assign(ETs.begin(), ETs.end()); 35 if (const auto &RTs = CUNode->getRetainedTypes()) 36 AllRetainTypes.assign(RTs.begin(), RTs.end()); 37 if (const auto &GVs = CUNode->getGlobalVariables()) 38 AllGVs.assign(GVs.begin(), GVs.end()); 39 if (const auto &IMs = CUNode->getImportedEntities()) 40 ImportedModules.assign(IMs.begin(), IMs.end()); 41 if (const auto &MNs = CUNode->getMacros()) 42 AllMacrosPerParent.insert({nullptr, {MNs.begin(), MNs.end()}}); 43 } 44 } 45 46 void DIBuilder::trackIfUnresolved(MDNode *N) { 47 if (!N) 48 return; 49 if (N->isResolved()) 50 return; 51 52 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes"); 53 UnresolvedNodes.emplace_back(N); 54 } 55 56 void DIBuilder::finalizeSubprogram(DISubprogram *SP) { 57 auto PN = SubprogramTrackedNodes.find(SP); 58 if (PN != SubprogramTrackedNodes.end()) 59 SP->replaceRetainedNodes( 60 MDTuple::get(VMContext, SmallVector<Metadata *, 16>(PN->second.begin(), 61 PN->second.end()))); 62 } 63 64 void DIBuilder::finalize() { 65 if (!CUNode) { 66 assert(!AllowUnresolvedNodes && 67 "creating type nodes without a CU is not supported"); 68 return; 69 } 70 71 if (!AllEnumTypes.empty()) 72 CUNode->replaceEnumTypes(MDTuple::get( 73 VMContext, SmallVector<Metadata *, 16>(AllEnumTypes.begin(), 74 AllEnumTypes.end()))); 75 76 SmallVector<Metadata *, 16> RetainValues; 77 // Declarations and definitions of the same type may be retained. Some 78 // clients RAUW these pairs, leaving duplicates in the retained types 79 // list. Use a set to remove the duplicates while we transform the 80 // TrackingVHs back into Values. 81 SmallPtrSet<Metadata *, 16> RetainSet; 82 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++) 83 if (RetainSet.insert(AllRetainTypes[I]).second) 84 RetainValues.push_back(AllRetainTypes[I]); 85 86 if (!RetainValues.empty()) 87 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues)); 88 89 for (auto *SP : AllSubprograms) 90 finalizeSubprogram(SP); 91 for (auto *N : RetainValues) 92 if (auto *SP = dyn_cast<DISubprogram>(N)) 93 finalizeSubprogram(SP); 94 95 if (!AllGVs.empty()) 96 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs)); 97 98 if (!ImportedModules.empty()) 99 CUNode->replaceImportedEntities(MDTuple::get( 100 VMContext, SmallVector<Metadata *, 16>(ImportedModules.begin(), 101 ImportedModules.end()))); 102 103 for (const auto &I : AllMacrosPerParent) { 104 // DIMacroNode's with nullptr parent are DICompileUnit direct children. 105 if (!I.first) { 106 CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef())); 107 continue; 108 } 109 // Otherwise, it must be a temporary DIMacroFile that need to be resolved. 110 auto *TMF = cast<DIMacroFile>(I.first); 111 auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file, 112 TMF->getLine(), TMF->getFile(), 113 getOrCreateMacroArray(I.second.getArrayRef())); 114 replaceTemporary(llvm::TempDIMacroNode(TMF), MF); 115 } 116 117 // Now that all temp nodes have been replaced or deleted, resolve remaining 118 // cycles. 119 for (const auto &N : UnresolvedNodes) 120 if (N && !N->isResolved()) 121 N->resolveCycles(); 122 UnresolvedNodes.clear(); 123 124 // Can't handle unresolved nodes anymore. 125 AllowUnresolvedNodes = false; 126 } 127 128 /// If N is compile unit return NULL otherwise return N. 129 static DIScope *getNonCompileUnitScope(DIScope *N) { 130 if (!N || isa<DICompileUnit>(N)) 131 return nullptr; 132 return cast<DIScope>(N); 133 } 134 135 DICompileUnit *DIBuilder::createCompileUnit( 136 unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized, 137 StringRef Flags, unsigned RunTimeVer, StringRef SplitName, 138 DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId, 139 bool SplitDebugInlining, bool DebugInfoForProfiling, 140 DICompileUnit::DebugNameTableKind NameTableKind, bool RangesBaseAddress, 141 StringRef SysRoot, StringRef SDK) { 142 143 assert(((Lang <= dwarf::DW_LANG_Mojo && Lang >= dwarf::DW_LANG_C89) || 144 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && 145 "Invalid Language tag"); 146 147 assert(!CUNode && "Can only make one compile unit per DIBuilder instance"); 148 CUNode = DICompileUnit::getDistinct( 149 VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer, 150 SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId, 151 SplitDebugInlining, DebugInfoForProfiling, NameTableKind, 152 RangesBaseAddress, SysRoot, SDK); 153 154 // Create a named metadata so that it is easier to find cu in a module. 155 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); 156 NMD->addOperand(CUNode); 157 trackIfUnresolved(CUNode); 158 return CUNode; 159 } 160 161 static DIImportedEntity * 162 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context, 163 Metadata *NS, DIFile *File, unsigned Line, StringRef Name, 164 DINodeArray Elements, 165 SmallVectorImpl<TrackingMDNodeRef> &ImportedModules) { 166 if (Line) 167 assert(File && "Source location has line number but no file"); 168 unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size(); 169 auto *M = DIImportedEntity::get(C, Tag, Context, cast_or_null<DINode>(NS), 170 File, Line, Name, Elements); 171 if (EntitiesCount < C.pImpl->DIImportedEntitys.size()) 172 // A new Imported Entity was just added to the context. 173 // Add it to the Imported Modules list. 174 ImportedModules.emplace_back(M); 175 return M; 176 } 177 178 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 179 DINamespace *NS, DIFile *File, 180 unsigned Line, 181 DINodeArray Elements) { 182 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 183 Context, NS, File, Line, StringRef(), Elements, 184 getImportTrackingVector(Context)); 185 } 186 187 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 188 DIImportedEntity *NS, 189 DIFile *File, unsigned Line, 190 DINodeArray Elements) { 191 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 192 Context, NS, File, Line, StringRef(), Elements, 193 getImportTrackingVector(Context)); 194 } 195 196 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M, 197 DIFile *File, unsigned Line, 198 DINodeArray Elements) { 199 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 200 Context, M, File, Line, StringRef(), Elements, 201 getImportTrackingVector(Context)); 202 } 203 204 DIImportedEntity * 205 DIBuilder::createImportedDeclaration(DIScope *Context, DINode *Decl, 206 DIFile *File, unsigned Line, 207 StringRef Name, DINodeArray Elements) { 208 // Make sure to use the unique identifier based metadata reference for 209 // types that have one. 210 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration, 211 Context, Decl, File, Line, Name, Elements, 212 getImportTrackingVector(Context)); 213 } 214 215 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory, 216 std::optional<DIFile::ChecksumInfo<StringRef>> CS, 217 std::optional<StringRef> Source) { 218 return DIFile::get(VMContext, Filename, Directory, CS, Source); 219 } 220 221 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber, 222 unsigned MacroType, StringRef Name, 223 StringRef Value) { 224 assert(!Name.empty() && "Unable to create macro without name"); 225 assert((MacroType == dwarf::DW_MACINFO_undef || 226 MacroType == dwarf::DW_MACINFO_define) && 227 "Unexpected macro type"); 228 auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value); 229 AllMacrosPerParent[Parent].insert(M); 230 return M; 231 } 232 233 DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent, 234 unsigned LineNumber, DIFile *File) { 235 auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file, 236 LineNumber, File, DIMacroNodeArray()) 237 .release(); 238 AllMacrosPerParent[Parent].insert(MF); 239 // Add the new temporary DIMacroFile to the macro per parent map as a parent. 240 // This is needed to assure DIMacroFile with no children to have an entry in 241 // the map. Otherwise, it will not be resolved in DIBuilder::finalize(). 242 AllMacrosPerParent.insert({MF, {}}); 243 return MF; 244 } 245 246 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, uint64_t Val, 247 bool IsUnsigned) { 248 assert(!Name.empty() && "Unable to create enumerator without name"); 249 return DIEnumerator::get(VMContext, APInt(64, Val, !IsUnsigned), IsUnsigned, 250 Name); 251 } 252 253 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, const APSInt &Value) { 254 assert(!Name.empty() && "Unable to create enumerator without name"); 255 return DIEnumerator::get(VMContext, APInt(Value), Value.isUnsigned(), Name); 256 } 257 258 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) { 259 assert(!Name.empty() && "Unable to create type without name"); 260 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name); 261 } 262 263 DIBasicType *DIBuilder::createNullPtrType() { 264 return createUnspecifiedType("decltype(nullptr)"); 265 } 266 267 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits, 268 unsigned Encoding, 269 DINode::DIFlags Flags) { 270 assert(!Name.empty() && "Unable to create type without name"); 271 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits, 272 0, Encoding, Flags); 273 } 274 275 DIStringType *DIBuilder::createStringType(StringRef Name, uint64_t SizeInBits) { 276 assert(!Name.empty() && "Unable to create type without name"); 277 return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name, 278 SizeInBits, 0); 279 } 280 281 DIStringType *DIBuilder::createStringType(StringRef Name, 282 DIVariable *StringLength, 283 DIExpression *StrLocationExp) { 284 assert(!Name.empty() && "Unable to create type without name"); 285 return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name, 286 StringLength, nullptr, StrLocationExp, 0, 0, 0); 287 } 288 289 DIStringType *DIBuilder::createStringType(StringRef Name, 290 DIExpression *StringLengthExp, 291 DIExpression *StrLocationExp) { 292 assert(!Name.empty() && "Unable to create type without name"); 293 return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name, nullptr, 294 StringLengthExp, StrLocationExp, 0, 0, 0); 295 } 296 297 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) { 298 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0, 299 0, 0, std::nullopt, DINode::FlagZero); 300 } 301 302 DIDerivedType * 303 DIBuilder::createPointerType(DIType *PointeeTy, uint64_t SizeInBits, 304 uint32_t AlignInBits, 305 std::optional<unsigned> DWARFAddressSpace, 306 StringRef Name, DINodeArray Annotations) { 307 // FIXME: Why is there a name here? 308 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name, 309 nullptr, 0, nullptr, PointeeTy, SizeInBits, 310 AlignInBits, 0, DWARFAddressSpace, DINode::FlagZero, 311 nullptr, Annotations); 312 } 313 314 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy, 315 DIType *Base, 316 uint64_t SizeInBits, 317 uint32_t AlignInBits, 318 DINode::DIFlags Flags) { 319 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "", 320 nullptr, 0, nullptr, PointeeTy, SizeInBits, 321 AlignInBits, 0, std::nullopt, Flags, Base); 322 } 323 324 DIDerivedType * 325 DIBuilder::createReferenceType(unsigned Tag, DIType *RTy, uint64_t SizeInBits, 326 uint32_t AlignInBits, 327 std::optional<unsigned> DWARFAddressSpace) { 328 assert(RTy && "Unable to create reference type"); 329 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy, 330 SizeInBits, AlignInBits, 0, DWARFAddressSpace, 331 DINode::FlagZero); 332 } 333 334 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name, 335 DIFile *File, unsigned LineNo, 336 DIScope *Context, uint32_t AlignInBits, 337 DINode::DIFlags Flags, 338 DINodeArray Annotations) { 339 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File, 340 LineNo, getNonCompileUnitScope(Context), Ty, 0, 341 AlignInBits, 0, std::nullopt, Flags, nullptr, 342 Annotations); 343 } 344 345 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) { 346 assert(Ty && "Invalid type!"); 347 assert(FriendTy && "Invalid friend type!"); 348 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty, 349 FriendTy, 0, 0, 0, std::nullopt, DINode::FlagZero); 350 } 351 352 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy, 353 uint64_t BaseOffset, 354 uint32_t VBPtrOffset, 355 DINode::DIFlags Flags) { 356 assert(Ty && "Unable to create inheritance"); 357 Metadata *ExtraData = ConstantAsMetadata::get( 358 ConstantInt::get(IntegerType::get(VMContext, 32), VBPtrOffset)); 359 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr, 360 0, Ty, BaseTy, 0, 0, BaseOffset, std::nullopt, 361 Flags, ExtraData); 362 } 363 364 DIDerivedType *DIBuilder::createMemberType( 365 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 366 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 367 DINode::DIFlags Flags, DIType *Ty, DINodeArray Annotations) { 368 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 369 LineNumber, getNonCompileUnitScope(Scope), Ty, 370 SizeInBits, AlignInBits, OffsetInBits, std::nullopt, 371 Flags, nullptr, Annotations); 372 } 373 374 static ConstantAsMetadata *getConstantOrNull(Constant *C) { 375 if (C) 376 return ConstantAsMetadata::get(C); 377 return nullptr; 378 } 379 380 DIDerivedType *DIBuilder::createVariantMemberType( 381 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 382 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 383 Constant *Discriminant, DINode::DIFlags Flags, DIType *Ty) { 384 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 385 LineNumber, getNonCompileUnitScope(Scope), Ty, 386 SizeInBits, AlignInBits, OffsetInBits, std::nullopt, 387 Flags, getConstantOrNull(Discriminant)); 388 } 389 390 DIDerivedType *DIBuilder::createBitFieldMemberType( 391 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 392 uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits, 393 DINode::DIFlags Flags, DIType *Ty, DINodeArray Annotations) { 394 Flags |= DINode::FlagBitField; 395 return DIDerivedType::get( 396 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 397 getNonCompileUnitScope(Scope), Ty, SizeInBits, /*AlignInBits=*/0, 398 OffsetInBits, std::nullopt, Flags, 399 ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64), 400 StorageOffsetInBits)), 401 Annotations); 402 } 403 404 DIDerivedType * 405 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File, 406 unsigned LineNumber, DIType *Ty, 407 DINode::DIFlags Flags, llvm::Constant *Val, 408 unsigned Tag, uint32_t AlignInBits) { 409 Flags |= DINode::FlagStaticMember; 410 return DIDerivedType::get(VMContext, Tag, Name, File, LineNumber, 411 getNonCompileUnitScope(Scope), Ty, 0, AlignInBits, 412 0, std::nullopt, Flags, getConstantOrNull(Val)); 413 } 414 415 DIDerivedType * 416 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber, 417 uint64_t SizeInBits, uint32_t AlignInBits, 418 uint64_t OffsetInBits, DINode::DIFlags Flags, 419 DIType *Ty, MDNode *PropertyNode) { 420 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 421 LineNumber, getNonCompileUnitScope(File), Ty, 422 SizeInBits, AlignInBits, OffsetInBits, std::nullopt, 423 Flags, PropertyNode); 424 } 425 426 DIObjCProperty * 427 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber, 428 StringRef GetterName, StringRef SetterName, 429 unsigned PropertyAttributes, DIType *Ty) { 430 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName, 431 SetterName, PropertyAttributes, Ty); 432 } 433 434 DITemplateTypeParameter * 435 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name, 436 DIType *Ty, bool isDefault) { 437 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 438 return DITemplateTypeParameter::get(VMContext, Name, Ty, isDefault); 439 } 440 441 static DITemplateValueParameter * 442 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag, 443 DIScope *Context, StringRef Name, DIType *Ty, 444 bool IsDefault, Metadata *MD) { 445 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 446 return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, IsDefault, MD); 447 } 448 449 DITemplateValueParameter * 450 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name, 451 DIType *Ty, bool isDefault, 452 Constant *Val) { 453 return createTemplateValueParameterHelper( 454 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, 455 isDefault, getConstantOrNull(Val)); 456 } 457 458 DITemplateValueParameter * 459 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name, 460 DIType *Ty, StringRef Val, 461 bool IsDefault) { 462 return createTemplateValueParameterHelper( 463 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty, 464 IsDefault, MDString::get(VMContext, Val)); 465 } 466 467 DITemplateValueParameter * 468 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name, 469 DIType *Ty, DINodeArray Val) { 470 return createTemplateValueParameterHelper( 471 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty, 472 false, Val.get()); 473 } 474 475 DICompositeType *DIBuilder::createClassType( 476 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 477 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 478 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements, 479 unsigned RunTimeLang, DIType *VTableHolder, MDNode *TemplateParams, 480 StringRef UniqueIdentifier) { 481 assert((!Context || isa<DIScope>(Context)) && 482 "createClassType should be called with a valid Context"); 483 484 auto *R = DICompositeType::get( 485 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 486 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 487 OffsetInBits, Flags, Elements, RunTimeLang, VTableHolder, 488 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier); 489 trackIfUnresolved(R); 490 return R; 491 } 492 493 DICompositeType *DIBuilder::createStructType( 494 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 495 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, 496 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang, 497 DIType *VTableHolder, StringRef UniqueIdentifier) { 498 auto *R = DICompositeType::get( 499 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 500 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0, 501 Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier); 502 trackIfUnresolved(R); 503 return R; 504 } 505 506 DICompositeType *DIBuilder::createUnionType( 507 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 508 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, 509 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) { 510 auto *R = DICompositeType::get( 511 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber, 512 getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags, 513 Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier); 514 trackIfUnresolved(R); 515 return R; 516 } 517 518 DICompositeType * 519 DIBuilder::createVariantPart(DIScope *Scope, StringRef Name, DIFile *File, 520 unsigned LineNumber, uint64_t SizeInBits, 521 uint32_t AlignInBits, DINode::DIFlags Flags, 522 DIDerivedType *Discriminator, DINodeArray Elements, 523 StringRef UniqueIdentifier) { 524 auto *R = DICompositeType::get( 525 VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber, 526 getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags, 527 Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator); 528 trackIfUnresolved(R); 529 return R; 530 } 531 532 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes, 533 DINode::DIFlags Flags, 534 unsigned CC) { 535 return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes); 536 } 537 538 DICompositeType * 539 DIBuilder::createEnumerationType(DIScope *Scope, StringRef Name, DIFile *File, 540 unsigned LineNumber, uint64_t SizeInBits, 541 uint32_t AlignInBits, DINodeArray Elements, 542 DIType *UnderlyingType, unsigned RunTimeLang, 543 StringRef UniqueIdentifier, bool IsScoped) { 544 auto *CTy = DICompositeType::get( 545 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber, 546 getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0, 547 IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 548 RunTimeLang, nullptr, nullptr, UniqueIdentifier); 549 AllEnumTypes.emplace_back(CTy); 550 trackIfUnresolved(CTy); 551 return CTy; 552 } 553 554 DIDerivedType *DIBuilder::createSetType(DIScope *Scope, StringRef Name, 555 DIFile *File, unsigned LineNo, 556 uint64_t SizeInBits, 557 uint32_t AlignInBits, DIType *Ty) { 558 auto *R = 559 DIDerivedType::get(VMContext, dwarf::DW_TAG_set_type, Name, File, LineNo, 560 getNonCompileUnitScope(Scope), Ty, SizeInBits, 561 AlignInBits, 0, std::nullopt, DINode::FlagZero); 562 trackIfUnresolved(R); 563 return R; 564 } 565 566 DICompositeType * 567 DIBuilder::createArrayType(uint64_t Size, uint32_t AlignInBits, DIType *Ty, 568 DINodeArray Subscripts, 569 PointerUnion<DIExpression *, DIVariable *> DL, 570 PointerUnion<DIExpression *, DIVariable *> AS, 571 PointerUnion<DIExpression *, DIVariable *> AL, 572 PointerUnion<DIExpression *, DIVariable *> RK) { 573 auto *R = DICompositeType::get( 574 VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, nullptr, Ty, Size, 575 AlignInBits, 0, DINode::FlagZero, Subscripts, 0, nullptr, nullptr, "", 576 nullptr, 577 isa<DIExpression *>(DL) ? (Metadata *)cast<DIExpression *>(DL) 578 : (Metadata *)cast<DIVariable *>(DL), 579 isa<DIExpression *>(AS) ? (Metadata *)cast<DIExpression *>(AS) 580 : (Metadata *)cast<DIVariable *>(AS), 581 isa<DIExpression *>(AL) ? (Metadata *)cast<DIExpression *>(AL) 582 : (Metadata *)cast<DIVariable *>(AL), 583 isa<DIExpression *>(RK) ? (Metadata *)cast<DIExpression *>(RK) 584 : (Metadata *)cast<DIVariable *>(RK)); 585 trackIfUnresolved(R); 586 return R; 587 } 588 589 DICompositeType *DIBuilder::createVectorType(uint64_t Size, 590 uint32_t AlignInBits, DIType *Ty, 591 DINodeArray Subscripts) { 592 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", 593 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0, 594 DINode::FlagVector, Subscripts, 0, nullptr); 595 trackIfUnresolved(R); 596 return R; 597 } 598 599 DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) { 600 auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial); 601 return MDNode::replaceWithDistinct(std::move(NewSP)); 602 } 603 604 static DIType *createTypeWithFlags(const DIType *Ty, 605 DINode::DIFlags FlagsToSet) { 606 auto NewTy = Ty->cloneWithFlags(Ty->getFlags() | FlagsToSet); 607 return MDNode::replaceWithUniqued(std::move(NewTy)); 608 } 609 610 DIType *DIBuilder::createArtificialType(DIType *Ty) { 611 // FIXME: Restrict this to the nodes where it's valid. 612 if (Ty->isArtificial()) 613 return Ty; 614 return createTypeWithFlags(Ty, DINode::FlagArtificial); 615 } 616 617 DIType *DIBuilder::createObjectPointerType(DIType *Ty) { 618 // FIXME: Restrict this to the nodes where it's valid. 619 if (Ty->isObjectPointer()) 620 return Ty; 621 DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial; 622 return createTypeWithFlags(Ty, Flags); 623 } 624 625 void DIBuilder::retainType(DIScope *T) { 626 assert(T && "Expected non-null type"); 627 assert((isa<DIType>(T) || (isa<DISubprogram>(T) && 628 cast<DISubprogram>(T)->isDefinition() == false)) && 629 "Expected type or subprogram declaration"); 630 AllRetainTypes.emplace_back(T); 631 } 632 633 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; } 634 635 DICompositeType * 636 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope, 637 DIFile *F, unsigned Line, unsigned RuntimeLang, 638 uint64_t SizeInBits, uint32_t AlignInBits, 639 StringRef UniqueIdentifier) { 640 // FIXME: Define in terms of createReplaceableForwardDecl() by calling 641 // replaceWithUniqued(). 642 auto *RetTy = DICompositeType::get( 643 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr, 644 SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, 645 nullptr, nullptr, UniqueIdentifier); 646 trackIfUnresolved(RetTy); 647 return RetTy; 648 } 649 650 DICompositeType *DIBuilder::createReplaceableCompositeType( 651 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line, 652 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, 653 DINode::DIFlags Flags, StringRef UniqueIdentifier, 654 DINodeArray Annotations) { 655 auto *RetTy = 656 DICompositeType::getTemporary( 657 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr, 658 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr, 659 nullptr, UniqueIdentifier, nullptr, nullptr, nullptr, nullptr, 660 nullptr, Annotations) 661 .release(); 662 trackIfUnresolved(RetTy); 663 return RetTy; 664 } 665 666 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) { 667 return MDTuple::get(VMContext, Elements); 668 } 669 670 DIMacroNodeArray 671 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) { 672 return MDTuple::get(VMContext, Elements); 673 } 674 675 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) { 676 SmallVector<llvm::Metadata *, 16> Elts; 677 for (Metadata *E : Elements) { 678 if (isa_and_nonnull<MDNode>(E)) 679 Elts.push_back(cast<DIType>(E)); 680 else 681 Elts.push_back(E); 682 } 683 return DITypeRefArray(MDNode::get(VMContext, Elts)); 684 } 685 686 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) { 687 auto *LB = ConstantAsMetadata::get( 688 ConstantInt::getSigned(Type::getInt64Ty(VMContext), Lo)); 689 auto *CountNode = ConstantAsMetadata::get( 690 ConstantInt::getSigned(Type::getInt64Ty(VMContext), Count)); 691 return DISubrange::get(VMContext, CountNode, LB, nullptr, nullptr); 692 } 693 694 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) { 695 auto *LB = ConstantAsMetadata::get( 696 ConstantInt::getSigned(Type::getInt64Ty(VMContext), Lo)); 697 return DISubrange::get(VMContext, CountNode, LB, nullptr, nullptr); 698 } 699 700 DISubrange *DIBuilder::getOrCreateSubrange(Metadata *CountNode, Metadata *LB, 701 Metadata *UB, Metadata *Stride) { 702 return DISubrange::get(VMContext, CountNode, LB, UB, Stride); 703 } 704 705 DIGenericSubrange *DIBuilder::getOrCreateGenericSubrange( 706 DIGenericSubrange::BoundType CountNode, DIGenericSubrange::BoundType LB, 707 DIGenericSubrange::BoundType UB, DIGenericSubrange::BoundType Stride) { 708 auto ConvToMetadata = [&](DIGenericSubrange::BoundType Bound) -> Metadata * { 709 return isa<DIExpression *>(Bound) ? (Metadata *)cast<DIExpression *>(Bound) 710 : (Metadata *)cast<DIVariable *>(Bound); 711 }; 712 return DIGenericSubrange::get(VMContext, ConvToMetadata(CountNode), 713 ConvToMetadata(LB), ConvToMetadata(UB), 714 ConvToMetadata(Stride)); 715 } 716 717 static void checkGlobalVariableScope(DIScope *Context) { 718 #ifndef NDEBUG 719 if (auto *CT = 720 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context))) 721 assert(CT->getIdentifier().empty() && 722 "Context of a global variable should not be a type with identifier"); 723 #endif 724 } 725 726 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression( 727 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 728 unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, bool isDefined, 729 DIExpression *Expr, MDNode *Decl, MDTuple *TemplateParams, 730 uint32_t AlignInBits, DINodeArray Annotations) { 731 checkGlobalVariableScope(Context); 732 733 auto *GV = DIGlobalVariable::getDistinct( 734 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, 735 LineNumber, Ty, IsLocalToUnit, isDefined, 736 cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits, 737 Annotations); 738 if (!Expr) 739 Expr = createExpression(); 740 auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr); 741 AllGVs.push_back(N); 742 return N; 743 } 744 745 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl( 746 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 747 unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, MDNode *Decl, 748 MDTuple *TemplateParams, uint32_t AlignInBits) { 749 checkGlobalVariableScope(Context); 750 751 return DIGlobalVariable::getTemporary( 752 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, 753 LineNumber, Ty, IsLocalToUnit, false, 754 cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits, 755 nullptr) 756 .release(); 757 } 758 759 static DILocalVariable *createLocalVariable( 760 LLVMContext &VMContext, 761 SmallVectorImpl<TrackingMDNodeRef> &PreservedNodes, 762 DIScope *Context, StringRef Name, unsigned ArgNo, DIFile *File, 763 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags, 764 uint32_t AlignInBits, DINodeArray Annotations = nullptr) { 765 // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT 766 // the only valid scopes)? 767 auto *Scope = cast<DILocalScope>(Context); 768 auto *Node = DILocalVariable::get(VMContext, Scope, Name, File, LineNo, Ty, 769 ArgNo, Flags, AlignInBits, Annotations); 770 if (AlwaysPreserve) { 771 // The optimizer may remove local variables. If there is an interest 772 // to preserve variable info in such situation then stash it in a 773 // named mdnode. 774 PreservedNodes.emplace_back(Node); 775 } 776 return Node; 777 } 778 779 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name, 780 DIFile *File, unsigned LineNo, 781 DIType *Ty, bool AlwaysPreserve, 782 DINode::DIFlags Flags, 783 uint32_t AlignInBits) { 784 assert(Scope && isa<DILocalScope>(Scope) && 785 "Unexpected scope for a local variable."); 786 return createLocalVariable( 787 VMContext, getSubprogramNodesTrackingVector(Scope), Scope, Name, 788 /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve, Flags, AlignInBits); 789 } 790 791 DILocalVariable *DIBuilder::createParameterVariable( 792 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, 793 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags, 794 DINodeArray Annotations) { 795 assert(ArgNo && "Expected non-zero argument number for parameter"); 796 assert(Scope && isa<DILocalScope>(Scope) && 797 "Unexpected scope for a local variable."); 798 return createLocalVariable( 799 VMContext, getSubprogramNodesTrackingVector(Scope), Scope, Name, ArgNo, 800 File, LineNo, Ty, AlwaysPreserve, Flags, /*AlignInBits=*/0, Annotations); 801 } 802 803 DILabel *DIBuilder::createLabel(DIScope *Context, StringRef Name, DIFile *File, 804 unsigned LineNo, bool AlwaysPreserve) { 805 auto *Scope = cast<DILocalScope>(Context); 806 auto *Node = DILabel::get(VMContext, Scope, Name, File, LineNo); 807 808 if (AlwaysPreserve) { 809 /// The optimizer may remove labels. If there is an interest 810 /// to preserve label info in such situation then append it to 811 /// the list of retained nodes of the DISubprogram. 812 getSubprogramNodesTrackingVector(Scope).emplace_back(Node); 813 } 814 return Node; 815 } 816 817 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) { 818 return DIExpression::get(VMContext, Addr); 819 } 820 821 template <class... Ts> 822 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&...Args) { 823 if (IsDistinct) 824 return DISubprogram::getDistinct(std::forward<Ts>(Args)...); 825 return DISubprogram::get(std::forward<Ts>(Args)...); 826 } 827 828 DISubprogram *DIBuilder::createFunction( 829 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 830 unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine, 831 DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags, 832 DITemplateParameterArray TParams, DISubprogram *Decl, 833 DITypeArray ThrownTypes, DINodeArray Annotations, 834 StringRef TargetFuncName) { 835 bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition; 836 auto *Node = getSubprogram( 837 /*IsDistinct=*/IsDefinition, VMContext, getNonCompileUnitScope(Context), 838 Name, LinkageName, File, LineNo, Ty, ScopeLine, nullptr, 0, 0, Flags, 839 SPFlags, IsDefinition ? CUNode : nullptr, TParams, Decl, nullptr, 840 ThrownTypes, Annotations, TargetFuncName); 841 842 if (IsDefinition) 843 AllSubprograms.push_back(Node); 844 trackIfUnresolved(Node); 845 return Node; 846 } 847 848 DISubprogram *DIBuilder::createTempFunctionFwdDecl( 849 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 850 unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine, 851 DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags, 852 DITemplateParameterArray TParams, DISubprogram *Decl, 853 DITypeArray ThrownTypes) { 854 bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition; 855 return DISubprogram::getTemporary(VMContext, getNonCompileUnitScope(Context), 856 Name, LinkageName, File, LineNo, Ty, 857 ScopeLine, nullptr, 0, 0, Flags, SPFlags, 858 IsDefinition ? CUNode : nullptr, TParams, 859 Decl, nullptr, ThrownTypes) 860 .release(); 861 } 862 863 DISubprogram *DIBuilder::createMethod( 864 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 865 unsigned LineNo, DISubroutineType *Ty, unsigned VIndex, int ThisAdjustment, 866 DIType *VTableHolder, DINode::DIFlags Flags, 867 DISubprogram::DISPFlags SPFlags, DITemplateParameterArray TParams, 868 DITypeArray ThrownTypes) { 869 assert(getNonCompileUnitScope(Context) && 870 "Methods should have both a Context and a context that isn't " 871 "the compile unit."); 872 // FIXME: Do we want to use different scope/lines? 873 bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition; 874 auto *SP = getSubprogram( 875 /*IsDistinct=*/IsDefinition, VMContext, cast<DIScope>(Context), Name, 876 LinkageName, F, LineNo, Ty, LineNo, VTableHolder, VIndex, ThisAdjustment, 877 Flags, SPFlags, IsDefinition ? CUNode : nullptr, TParams, nullptr, 878 nullptr, ThrownTypes); 879 880 if (IsDefinition) 881 AllSubprograms.push_back(SP); 882 trackIfUnresolved(SP); 883 return SP; 884 } 885 886 DICommonBlock *DIBuilder::createCommonBlock(DIScope *Scope, 887 DIGlobalVariable *Decl, 888 StringRef Name, DIFile *File, 889 unsigned LineNo) { 890 return DICommonBlock::get(VMContext, Scope, Decl, Name, File, LineNo); 891 } 892 893 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name, 894 bool ExportSymbols) { 895 896 // It is okay to *not* make anonymous top-level namespaces distinct, because 897 // all nodes that have an anonymous namespace as their parent scope are 898 // guaranteed to be unique and/or are linked to their containing 899 // DICompileUnit. This decision is an explicit tradeoff of link time versus 900 // memory usage versus code simplicity and may get revisited in the future. 901 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name, 902 ExportSymbols); 903 } 904 905 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name, 906 StringRef ConfigurationMacros, 907 StringRef IncludePath, StringRef APINotesFile, 908 DIFile *File, unsigned LineNo, bool IsDecl) { 909 return DIModule::get(VMContext, File, getNonCompileUnitScope(Scope), Name, 910 ConfigurationMacros, IncludePath, APINotesFile, LineNo, 911 IsDecl); 912 } 913 914 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope, 915 DIFile *File, 916 unsigned Discriminator) { 917 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator); 918 } 919 920 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File, 921 unsigned Line, unsigned Col) { 922 // Make these distinct, to avoid merging two lexical blocks on the same 923 // file/line/column. 924 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope), 925 File, Line, Col); 926 } 927 928 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 929 DIExpression *Expr, const DILocation *DL, 930 Instruction *InsertBefore) { 931 return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(), 932 InsertBefore); 933 } 934 935 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 936 DIExpression *Expr, const DILocation *DL, 937 BasicBlock *InsertAtEnd) { 938 // If this block already has a terminator then insert this intrinsic before 939 // the terminator. Otherwise, put it at the end of the block. 940 Instruction *InsertBefore = InsertAtEnd->getTerminator(); 941 return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore); 942 } 943 944 DbgAssignIntrinsic * 945 DIBuilder::insertDbgAssign(Instruction *LinkedInstr, Value *Val, 946 DILocalVariable *SrcVar, DIExpression *ValExpr, 947 Value *Addr, DIExpression *AddrExpr, 948 const DILocation *DL) { 949 LLVMContext &Ctx = LinkedInstr->getContext(); 950 Module *M = LinkedInstr->getModule(); 951 if (!AssignFn) 952 AssignFn = Intrinsic::getDeclaration(M, Intrinsic::dbg_assign); 953 954 auto *Link = LinkedInstr->getMetadata(LLVMContext::MD_DIAssignID); 955 assert(Link && "Linked instruction must have DIAssign metadata attached"); 956 957 std::array<Value *, 6> Args = { 958 MetadataAsValue::get(Ctx, ValueAsMetadata::get(Val)), 959 MetadataAsValue::get(Ctx, SrcVar), 960 MetadataAsValue::get(Ctx, ValExpr), 961 MetadataAsValue::get(Ctx, Link), 962 MetadataAsValue::get(Ctx, ValueAsMetadata::get(Addr)), 963 MetadataAsValue::get(Ctx, AddrExpr), 964 }; 965 966 IRBuilder<> B(Ctx); 967 B.SetCurrentDebugLocation(DL); 968 969 auto *DVI = cast<DbgAssignIntrinsic>(B.CreateCall(AssignFn, Args)); 970 DVI->insertAfter(LinkedInstr); 971 return DVI; 972 } 973 974 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL, 975 Instruction *InsertBefore) { 976 return insertLabel(LabelInfo, DL, 977 InsertBefore ? InsertBefore->getParent() : nullptr, 978 InsertBefore); 979 } 980 981 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL, 982 BasicBlock *InsertAtEnd) { 983 return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr); 984 } 985 986 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, 987 DILocalVariable *VarInfo, 988 DIExpression *Expr, 989 const DILocation *DL, 990 Instruction *InsertBefore) { 991 Instruction *DVI = insertDbgValueIntrinsic( 992 V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr, 993 InsertBefore); 994 cast<CallInst>(DVI)->setTailCall(); 995 return DVI; 996 } 997 998 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, 999 DILocalVariable *VarInfo, 1000 DIExpression *Expr, 1001 const DILocation *DL, 1002 BasicBlock *InsertAtEnd) { 1003 return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr); 1004 } 1005 1006 /// Initialize IRBuilder for inserting dbg.declare and dbg.value intrinsics. 1007 /// This abstracts over the various ways to specify an insert position. 1008 static void initIRBuilder(IRBuilder<> &Builder, const DILocation *DL, 1009 BasicBlock *InsertBB, Instruction *InsertBefore) { 1010 if (InsertBefore) 1011 Builder.SetInsertPoint(InsertBefore); 1012 else if (InsertBB) 1013 Builder.SetInsertPoint(InsertBB); 1014 Builder.SetCurrentDebugLocation(DL); 1015 } 1016 1017 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) { 1018 assert(V && "no value passed to dbg intrinsic"); 1019 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V)); 1020 } 1021 1022 static Function *getDeclareIntrin(Module &M) { 1023 return Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 1024 } 1025 1026 Instruction *DIBuilder::insertDbgValueIntrinsic( 1027 llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr, 1028 const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) { 1029 if (!ValueFn) 1030 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 1031 return insertDbgIntrinsic(ValueFn, Val, VarInfo, Expr, DL, InsertBB, 1032 InsertBefore); 1033 } 1034 1035 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 1036 DIExpression *Expr, const DILocation *DL, 1037 BasicBlock *InsertBB, 1038 Instruction *InsertBefore) { 1039 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 1040 assert(DL && "Expected debug loc"); 1041 assert(DL->getScope()->getSubprogram() == 1042 VarInfo->getScope()->getSubprogram() && 1043 "Expected matching subprograms"); 1044 if (!DeclareFn) 1045 DeclareFn = getDeclareIntrin(M); 1046 1047 trackIfUnresolved(VarInfo); 1048 trackIfUnresolved(Expr); 1049 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 1050 MetadataAsValue::get(VMContext, VarInfo), 1051 MetadataAsValue::get(VMContext, Expr)}; 1052 1053 IRBuilder<> B(DL->getContext()); 1054 initIRBuilder(B, DL, InsertBB, InsertBefore); 1055 return B.CreateCall(DeclareFn, Args); 1056 } 1057 1058 Instruction *DIBuilder::insertDbgIntrinsic(llvm::Function *IntrinsicFn, 1059 Value *V, DILocalVariable *VarInfo, 1060 DIExpression *Expr, 1061 const DILocation *DL, 1062 BasicBlock *InsertBB, 1063 Instruction *InsertBefore) { 1064 assert(IntrinsicFn && "must pass a non-null intrinsic function"); 1065 assert(V && "must pass a value to a dbg intrinsic"); 1066 assert(VarInfo && 1067 "empty or invalid DILocalVariable* passed to debug intrinsic"); 1068 assert(DL && "Expected debug loc"); 1069 assert(DL->getScope()->getSubprogram() == 1070 VarInfo->getScope()->getSubprogram() && 1071 "Expected matching subprograms"); 1072 1073 trackIfUnresolved(VarInfo); 1074 trackIfUnresolved(Expr); 1075 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 1076 MetadataAsValue::get(VMContext, VarInfo), 1077 MetadataAsValue::get(VMContext, Expr)}; 1078 1079 IRBuilder<> B(DL->getContext()); 1080 initIRBuilder(B, DL, InsertBB, InsertBefore); 1081 return B.CreateCall(IntrinsicFn, Args); 1082 } 1083 1084 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL, 1085 BasicBlock *InsertBB, 1086 Instruction *InsertBefore) { 1087 assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label"); 1088 assert(DL && "Expected debug loc"); 1089 assert(DL->getScope()->getSubprogram() == 1090 LabelInfo->getScope()->getSubprogram() && 1091 "Expected matching subprograms"); 1092 if (!LabelFn) 1093 LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label); 1094 1095 trackIfUnresolved(LabelInfo); 1096 Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)}; 1097 1098 IRBuilder<> B(DL->getContext()); 1099 initIRBuilder(B, DL, InsertBB, InsertBefore); 1100 return B.CreateCall(LabelFn, Args); 1101 } 1102 1103 void DIBuilder::replaceVTableHolder(DICompositeType *&T, DIType *VTableHolder) { 1104 { 1105 TypedTrackingMDRef<DICompositeType> N(T); 1106 N->replaceVTableHolder(VTableHolder); 1107 T = N.get(); 1108 } 1109 1110 // If this didn't create a self-reference, just return. 1111 if (T != VTableHolder) 1112 return; 1113 1114 // Look for unresolved operands. T will drop RAUW support, orphaning any 1115 // cycles underneath it. 1116 if (T->isResolved()) 1117 for (const MDOperand &O : T->operands()) 1118 if (auto *N = dyn_cast_or_null<MDNode>(O)) 1119 trackIfUnresolved(N); 1120 } 1121 1122 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements, 1123 DINodeArray TParams) { 1124 { 1125 TypedTrackingMDRef<DICompositeType> N(T); 1126 if (Elements) 1127 N->replaceElements(Elements); 1128 if (TParams) 1129 N->replaceTemplateParams(DITemplateParameterArray(TParams)); 1130 T = N.get(); 1131 } 1132 1133 // If T isn't resolved, there's no problem. 1134 if (!T->isResolved()) 1135 return; 1136 1137 // If T is resolved, it may be due to a self-reference cycle. Track the 1138 // arrays explicitly if they're unresolved, or else the cycles will be 1139 // orphaned. 1140 if (Elements) 1141 trackIfUnresolved(Elements.get()); 1142 if (TParams) 1143 trackIfUnresolved(TParams.get()); 1144 } 1145