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