1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the DIBuilder. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/DIBuilder.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/IR/Constants.h" 17 #include "llvm/IR/DebugInfo.h" 18 #include "llvm/IR/IntrinsicInst.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/Dwarf.h" 22 #include "LLVMContextImpl.h" 23 24 using namespace llvm; 25 using namespace llvm::dwarf; 26 27 namespace { 28 class HeaderBuilder { 29 /// \brief Whether there are any fields yet. 30 /// 31 /// Note that this is not equivalent to \c Chars.empty(), since \a concat() 32 /// may have been called already with an empty string. 33 bool IsEmpty; 34 SmallVector<char, 256> Chars; 35 36 public: 37 HeaderBuilder() : IsEmpty(true) {} 38 HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {} 39 HeaderBuilder(HeaderBuilder &&X) 40 : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {} 41 42 template <class Twineable> HeaderBuilder &concat(Twineable &&X) { 43 if (IsEmpty) 44 IsEmpty = false; 45 else 46 Chars.push_back(0); 47 Twine(X).toVector(Chars); 48 return *this; 49 } 50 51 MDString *get(LLVMContext &Context) const { 52 return MDString::get(Context, StringRef(Chars.begin(), Chars.size())); 53 } 54 55 static HeaderBuilder get(unsigned Tag) { 56 return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag)); 57 } 58 }; 59 } 60 61 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes) 62 : M(m), VMContext(M.getContext()), CUNode(nullptr), 63 DeclareFn(nullptr), ValueFn(nullptr), 64 AllowUnresolvedNodes(AllowUnresolvedNodes) {} 65 66 void DIBuilder::trackIfUnresolved(MDNode *N) { 67 if (!N) 68 return; 69 if (N->isResolved()) 70 return; 71 72 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes"); 73 UnresolvedNodes.emplace_back(N); 74 } 75 76 void DIBuilder::finalize() { 77 if (!CUNode) { 78 assert(!AllowUnresolvedNodes && 79 "creating type nodes without a CU is not supported"); 80 return; 81 } 82 83 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes)); 84 85 SmallVector<Metadata *, 16> RetainValues; 86 // Declarations and definitions of the same type may be retained. Some 87 // clients RAUW these pairs, leaving duplicates in the retained types 88 // list. Use a set to remove the duplicates while we transform the 89 // TrackingVHs back into Values. 90 SmallPtrSet<Metadata *, 16> RetainSet; 91 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++) 92 if (RetainSet.insert(AllRetainTypes[I]).second) 93 RetainValues.push_back(AllRetainTypes[I]); 94 95 if (!RetainValues.empty()) 96 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues)); 97 98 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms); 99 auto resolveVariables = [&](DISubprogram *SP) { 100 if (MDTuple *Temp = SP->getVariables().get()) { 101 const auto &PV = PreservedVariables.lookup(SP); 102 SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end()); 103 DINodeArray AV = getOrCreateArray(Variables); 104 TempMDTuple(Temp)->replaceAllUsesWith(AV.get()); 105 } 106 }; 107 for (auto *SP : SPs) 108 resolveVariables(SP); 109 for (auto *N : RetainValues) 110 if (auto *SP = dyn_cast<DISubprogram>(N)) 111 resolveVariables(SP); 112 113 if (!AllGVs.empty()) 114 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs)); 115 116 if (!AllImportedModules.empty()) 117 CUNode->replaceImportedEntities(MDTuple::get( 118 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(), 119 AllImportedModules.end()))); 120 121 // Now that all temp nodes have been replaced or deleted, resolve remaining 122 // cycles. 123 for (const auto &N : UnresolvedNodes) 124 if (N && !N->isResolved()) 125 N->resolveCycles(); 126 UnresolvedNodes.clear(); 127 128 // Can't handle unresolved nodes anymore. 129 AllowUnresolvedNodes = false; 130 } 131 132 /// If N is compile unit return NULL otherwise return N. 133 static DIScope *getNonCompileUnitScope(DIScope *N) { 134 if (!N || isa<DICompileUnit>(N)) 135 return nullptr; 136 return cast<DIScope>(N); 137 } 138 139 DICompileUnit *DIBuilder::createCompileUnit( 140 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer, 141 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName, 142 DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId) { 143 144 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) || 145 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && 146 "Invalid Language tag"); 147 assert(!Filename.empty() && 148 "Unable to create compile unit without filename"); 149 150 assert(!CUNode && "Can only make one compile unit per DIBuilder instance"); 151 CUNode = DICompileUnit::getDistinct( 152 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer, 153 isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr, nullptr, 154 nullptr, nullptr, nullptr, DWOId); 155 156 // Create a named metadata so that it is easier to find cu in a module. 157 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); 158 NMD->addOperand(CUNode); 159 trackIfUnresolved(CUNode); 160 return CUNode; 161 } 162 163 static DIImportedEntity * 164 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context, 165 Metadata *NS, unsigned Line, StringRef Name, 166 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) { 167 unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size(); 168 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name); 169 if (EntitiesCount < C.pImpl->DIImportedEntitys.size()) 170 // A new Imported Entity was just added to the context. 171 // Add it to the Imported Modules list. 172 AllImportedModules.emplace_back(M); 173 return M; 174 } 175 176 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 177 DINamespace *NS, 178 unsigned Line) { 179 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 180 Context, NS, Line, StringRef(), AllImportedModules); 181 } 182 183 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 184 DIImportedEntity *NS, 185 unsigned Line) { 186 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 187 Context, NS, Line, StringRef(), AllImportedModules); 188 } 189 190 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M, 191 unsigned Line) { 192 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 193 Context, M, Line, StringRef(), AllImportedModules); 194 } 195 196 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context, 197 DINode *Decl, 198 unsigned Line, 199 StringRef Name) { 200 // Make sure to use the unique identifier based metadata reference for 201 // types that have one. 202 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration, 203 Context, DINodeRef::get(Decl), Line, Name, 204 AllImportedModules); 205 } 206 207 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) { 208 return DIFile::get(VMContext, Filename, Directory); 209 } 210 211 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) { 212 assert(!Name.empty() && "Unable to create enumerator without name"); 213 return DIEnumerator::get(VMContext, Val, Name); 214 } 215 216 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) { 217 assert(!Name.empty() && "Unable to create type without name"); 218 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name); 219 } 220 221 DIBasicType *DIBuilder::createNullPtrType() { 222 return createUnspecifiedType("decltype(nullptr)"); 223 } 224 225 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits, 226 uint64_t AlignInBits, 227 unsigned Encoding) { 228 assert(!Name.empty() && "Unable to create type without name"); 229 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits, 230 AlignInBits, Encoding); 231 } 232 233 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) { 234 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, 235 DITypeRef::get(FromTy), 0, 0, 0, 0); 236 } 237 238 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy, 239 uint64_t SizeInBits, 240 uint64_t AlignInBits, 241 StringRef Name) { 242 // FIXME: Why is there a name here? 243 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name, 244 nullptr, 0, nullptr, DITypeRef::get(PointeeTy), 245 SizeInBits, AlignInBits, 0, 0); 246 } 247 248 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy, 249 DIType *Base, 250 uint64_t SizeInBits, 251 uint64_t AlignInBits) { 252 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "", 253 nullptr, 0, nullptr, DITypeRef::get(PointeeTy), 254 SizeInBits, AlignInBits, 0, 0, 255 DITypeRef::get(Base)); 256 } 257 258 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy, 259 uint64_t SizeInBits, 260 uint64_t AlignInBits) { 261 assert(RTy && "Unable to create reference type"); 262 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, 263 DITypeRef::get(RTy), SizeInBits, AlignInBits, 0, 0); 264 } 265 266 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name, 267 DIFile *File, unsigned LineNo, 268 DIScope *Context) { 269 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File, 270 LineNo, 271 DIScopeRef::get(getNonCompileUnitScope(Context)), 272 DITypeRef::get(Ty), 0, 0, 0, 0); 273 } 274 275 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) { 276 assert(Ty && "Invalid type!"); 277 assert(FriendTy && "Invalid friend type!"); 278 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, 279 DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0, 280 0, 0); 281 } 282 283 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy, 284 uint64_t BaseOffset, 285 unsigned Flags) { 286 assert(Ty && "Unable to create inheritance"); 287 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr, 288 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0, 289 BaseOffset, Flags); 290 } 291 292 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name, 293 DIFile *File, unsigned LineNumber, 294 uint64_t SizeInBits, 295 uint64_t AlignInBits, 296 uint64_t OffsetInBits, 297 unsigned Flags, DIType *Ty) { 298 return DIDerivedType::get( 299 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 300 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 301 SizeInBits, AlignInBits, OffsetInBits, Flags); 302 } 303 304 static ConstantAsMetadata *getConstantOrNull(Constant *C) { 305 if (C) 306 return ConstantAsMetadata::get(C); 307 return nullptr; 308 } 309 310 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, 311 DIFile *File, 312 unsigned LineNumber, 313 DIType *Ty, unsigned Flags, 314 llvm::Constant *Val) { 315 Flags |= DINode::FlagStaticMember; 316 return DIDerivedType::get( 317 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 318 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0, 319 0, Flags, getConstantOrNull(Val)); 320 } 321 322 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File, 323 unsigned LineNumber, 324 uint64_t SizeInBits, 325 uint64_t AlignInBits, 326 uint64_t OffsetInBits, unsigned Flags, 327 DIType *Ty, MDNode *PropertyNode) { 328 return DIDerivedType::get( 329 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 330 DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty), 331 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode); 332 } 333 334 DIObjCProperty * 335 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber, 336 StringRef GetterName, StringRef SetterName, 337 unsigned PropertyAttributes, DIType *Ty) { 338 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName, 339 SetterName, PropertyAttributes, 340 DITypeRef::get(Ty)); 341 } 342 343 DITemplateTypeParameter * 344 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name, 345 DIType *Ty) { 346 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 347 return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty)); 348 } 349 350 static DITemplateValueParameter * 351 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag, 352 DIScope *Context, StringRef Name, DIType *Ty, 353 Metadata *MD) { 354 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 355 return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty), 356 MD); 357 } 358 359 DITemplateValueParameter * 360 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name, 361 DIType *Ty, Constant *Val) { 362 return createTemplateValueParameterHelper( 363 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, 364 getConstantOrNull(Val)); 365 } 366 367 DITemplateValueParameter * 368 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name, 369 DIType *Ty, StringRef Val) { 370 return createTemplateValueParameterHelper( 371 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty, 372 MDString::get(VMContext, Val)); 373 } 374 375 DITemplateValueParameter * 376 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name, 377 DIType *Ty, DINodeArray Val) { 378 return createTemplateValueParameterHelper( 379 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty, 380 Val.get()); 381 } 382 383 DICompositeType *DIBuilder::createClassType( 384 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 385 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits, 386 unsigned Flags, DIType *DerivedFrom, DINodeArray Elements, 387 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) { 388 assert((!Context || isa<DIScope>(Context)) && 389 "createClassType should be called with a valid Context"); 390 391 auto *R = DICompositeType::get( 392 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 393 DIScopeRef::get(getNonCompileUnitScope(Context)), 394 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags, 395 Elements, 0, DITypeRef::get(VTableHolder), 396 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier); 397 if (!UniqueIdentifier.empty()) 398 retainType(R); 399 trackIfUnresolved(R); 400 return R; 401 } 402 403 DICompositeType *DIBuilder::createStructType( 404 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 405 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags, 406 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang, 407 DIType *VTableHolder, StringRef UniqueIdentifier) { 408 auto *R = DICompositeType::get( 409 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 410 DIScopeRef::get(getNonCompileUnitScope(Context)), 411 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements, 412 RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier); 413 if (!UniqueIdentifier.empty()) 414 retainType(R); 415 trackIfUnresolved(R); 416 return R; 417 } 418 419 DICompositeType *DIBuilder::createUnionType( 420 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 421 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags, 422 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) { 423 auto *R = DICompositeType::get( 424 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber, 425 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits, 426 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr, 427 UniqueIdentifier); 428 if (!UniqueIdentifier.empty()) 429 retainType(R); 430 trackIfUnresolved(R); 431 return R; 432 } 433 434 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes, 435 unsigned Flags) { 436 return DISubroutineType::get(VMContext, Flags, ParameterTypes); 437 } 438 439 DICompositeType *DIBuilder::createExternalTypeRef(unsigned Tag, DIFile *File, 440 StringRef UniqueIdentifier) { 441 assert(!UniqueIdentifier.empty() && "external type ref without uid"); 442 auto *CTy = 443 DICompositeType::get(VMContext, Tag, "", nullptr, 0, nullptr, nullptr, 0, 444 0, 0, DINode::FlagExternalTypeRef, nullptr, 0, 445 nullptr, nullptr, UniqueIdentifier); 446 // Types with unique IDs need to be in the type map. 447 retainType(CTy); 448 return CTy; 449 } 450 451 DICompositeType *DIBuilder::createEnumerationType( 452 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 453 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements, 454 DIType *UnderlyingType, StringRef UniqueIdentifier) { 455 auto *CTy = DICompositeType::get( 456 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber, 457 DIScopeRef::get(getNonCompileUnitScope(Scope)), 458 DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements, 459 0, nullptr, nullptr, UniqueIdentifier); 460 AllEnumTypes.push_back(CTy); 461 if (!UniqueIdentifier.empty()) 462 retainType(CTy); 463 trackIfUnresolved(CTy); 464 return CTy; 465 } 466 467 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits, 468 DIType *Ty, 469 DINodeArray Subscripts) { 470 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", 471 nullptr, 0, nullptr, DITypeRef::get(Ty), Size, 472 AlignInBits, 0, 0, Subscripts, 0, nullptr); 473 trackIfUnresolved(R); 474 return R; 475 } 476 477 DICompositeType *DIBuilder::createVectorType(uint64_t Size, 478 uint64_t AlignInBits, DIType *Ty, 479 DINodeArray Subscripts) { 480 auto *R = 481 DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, 482 nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0, 483 DINode::FlagVector, Subscripts, 0, nullptr); 484 trackIfUnresolved(R); 485 return R; 486 } 487 488 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty, 489 unsigned FlagsToSet) { 490 auto NewTy = Ty->clone(); 491 NewTy->setFlags(NewTy->getFlags() | FlagsToSet); 492 return MDNode::replaceWithUniqued(std::move(NewTy)); 493 } 494 495 DIType *DIBuilder::createArtificialType(DIType *Ty) { 496 // FIXME: Restrict this to the nodes where it's valid. 497 if (Ty->isArtificial()) 498 return Ty; 499 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial); 500 } 501 502 DIType *DIBuilder::createObjectPointerType(DIType *Ty) { 503 // FIXME: Restrict this to the nodes where it's valid. 504 if (Ty->isObjectPointer()) 505 return Ty; 506 unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial; 507 return createTypeWithFlags(VMContext, Ty, Flags); 508 } 509 510 void DIBuilder::retainType(DIScope *T) { 511 assert(T && "Expected non-null type"); 512 assert((isa<DIType>(T) || (isa<DISubprogram>(T) && 513 cast<DISubprogram>(T)->isDefinition() == false)) && 514 "Expected type or subprogram declaration"); 515 AllRetainTypes.emplace_back(T); 516 } 517 518 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; } 519 520 DICompositeType * 521 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope, 522 DIFile *F, unsigned Line, unsigned RuntimeLang, 523 uint64_t SizeInBits, uint64_t AlignInBits, 524 StringRef UniqueIdentifier) { 525 // FIXME: Define in terms of createReplaceableForwardDecl() by calling 526 // replaceWithUniqued(). 527 auto *RetTy = DICompositeType::get( 528 VMContext, Tag, Name, F, Line, 529 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits, 530 AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr, 531 nullptr, UniqueIdentifier); 532 if (!UniqueIdentifier.empty()) 533 retainType(RetTy); 534 trackIfUnresolved(RetTy); 535 return RetTy; 536 } 537 538 DICompositeType *DIBuilder::createReplaceableCompositeType( 539 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line, 540 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits, 541 unsigned Flags, StringRef UniqueIdentifier) { 542 auto *RetTy = DICompositeType::getTemporary( 543 VMContext, Tag, Name, F, Line, 544 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, 545 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, 546 nullptr, nullptr, UniqueIdentifier) 547 .release(); 548 if (!UniqueIdentifier.empty()) 549 retainType(RetTy); 550 trackIfUnresolved(RetTy); 551 return RetTy; 552 } 553 554 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) { 555 return MDTuple::get(VMContext, Elements); 556 } 557 558 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) { 559 SmallVector<llvm::Metadata *, 16> Elts; 560 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 561 if (Elements[i] && isa<MDNode>(Elements[i])) 562 Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i]))); 563 else 564 Elts.push_back(Elements[i]); 565 } 566 return DITypeRefArray(MDNode::get(VMContext, Elts)); 567 } 568 569 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) { 570 return DISubrange::get(VMContext, Count, Lo); 571 } 572 573 static void checkGlobalVariableScope(DIScope *Context) { 574 #ifndef NDEBUG 575 if (auto *CT = 576 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context))) 577 assert(CT->getIdentifier().empty() && 578 "Context of a global variable should not be a type with identifier"); 579 #endif 580 } 581 582 DIGlobalVariable *DIBuilder::createGlobalVariable( 583 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 584 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val, 585 MDNode *Decl) { 586 checkGlobalVariableScope(Context); 587 588 auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context), 589 Name, LinkageName, F, LineNumber, 590 DITypeRef::get(Ty), isLocalToUnit, true, Val, 591 cast_or_null<DIDerivedType>(Decl)); 592 AllGVs.push_back(N); 593 return N; 594 } 595 596 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl( 597 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 598 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val, 599 MDNode *Decl) { 600 checkGlobalVariableScope(Context); 601 602 return DIGlobalVariable::getTemporary( 603 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, 604 LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val, 605 cast_or_null<DIDerivedType>(Decl)) 606 .release(); 607 } 608 609 static DILocalVariable *createLocalVariable( 610 LLVMContext &VMContext, 611 DenseMap<MDNode *, std::vector<TrackingMDNodeRef>> &PreservedVariables, 612 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, 613 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) { 614 // FIXME: Why getNonCompileUnitScope()? 615 // FIXME: Why is "!Context" okay here? 616 // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT 617 // the only valid scopes)? 618 DIScope *Context = getNonCompileUnitScope(Scope); 619 620 auto *Node = 621 DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name, 622 File, LineNo, DITypeRef::get(Ty), ArgNo, Flags); 623 if (AlwaysPreserve) { 624 // The optimizer may remove local variables. If there is an interest 625 // to preserve variable info in such situation then stash it in a 626 // named mdnode. 627 DISubprogram *Fn = getDISubprogram(Scope); 628 assert(Fn && "Missing subprogram for local variable"); 629 PreservedVariables[Fn].emplace_back(Node); 630 } 631 return Node; 632 } 633 634 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name, 635 DIFile *File, unsigned LineNo, 636 DIType *Ty, bool AlwaysPreserve, 637 unsigned Flags) { 638 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, 639 /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve, 640 Flags); 641 } 642 643 DILocalVariable *DIBuilder::createParameterVariable( 644 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, 645 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) { 646 assert(ArgNo && "Expected non-zero argument number for parameter"); 647 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo, 648 File, LineNo, Ty, AlwaysPreserve, Flags); 649 } 650 651 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) { 652 return DIExpression::get(VMContext, Addr); 653 } 654 655 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) { 656 // TODO: Remove the callers of this signed version and delete. 657 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end()); 658 return createExpression(Addr); 659 } 660 661 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes, 662 unsigned SizeInBytes) { 663 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes}; 664 return DIExpression::get(VMContext, Addr); 665 } 666 667 DISubprogram *DIBuilder::createFunction( 668 DIScopeRef Context, StringRef Name, StringRef LinkageName, DIFile *File, 669 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 670 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized, 671 DITemplateParameterArray TParams, DISubprogram *Decl) { 672 // dragonegg does not generate identifier for types, so using an empty map 673 // to resolve the context should be fine. 674 DITypeIdentifierMap EmptyMap; 675 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File, 676 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, 677 Flags, isOptimized, TParams, Decl); 678 } 679 680 template <class... Ts> 681 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) { 682 if (IsDistinct) 683 return DISubprogram::getDistinct(std::forward<Ts>(Args)...); 684 return DISubprogram::get(std::forward<Ts>(Args)...); 685 } 686 687 DISubprogram *DIBuilder::createFunction( 688 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 689 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 690 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized, 691 DITemplateParameterArray TParams, DISubprogram *Decl) { 692 auto *Node = getSubprogram( 693 /* IsDistinct = */ isDefinition, VMContext, 694 DIScopeRef::get(getNonCompileUnitScope(Context)), Name, LinkageName, File, 695 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags, 696 isOptimized, isDefinition ? CUNode : nullptr, TParams, Decl, 697 MDTuple::getTemporary(VMContext, None).release()); 698 699 if (isDefinition) 700 AllSubprograms.push_back(Node); 701 trackIfUnresolved(Node); 702 return Node; 703 } 704 705 DISubprogram *DIBuilder::createTempFunctionFwdDecl( 706 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 707 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 708 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized, 709 DITemplateParameterArray TParams, DISubprogram *Decl) { 710 return DISubprogram::getTemporary( 711 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name, 712 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, 713 ScopeLine, nullptr, 0, 0, Flags, isOptimized, 714 isDefinition ? CUNode : nullptr, TParams, Decl, nullptr) 715 .release(); 716 } 717 718 DISubprogram * 719 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName, 720 DIFile *F, unsigned LineNo, DISubroutineType *Ty, 721 bool isLocalToUnit, bool isDefinition, unsigned VK, 722 unsigned VIndex, DIType *VTableHolder, unsigned Flags, 723 bool isOptimized, DITemplateParameterArray TParams) { 724 assert(getNonCompileUnitScope(Context) && 725 "Methods should have both a Context and a context that isn't " 726 "the compile unit."); 727 // FIXME: Do we want to use different scope/lines? 728 auto *SP = getSubprogram( 729 /* IsDistinct = */ isDefinition, VMContext, 730 DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F, LineNo, Ty, 731 isLocalToUnit, isDefinition, LineNo, DITypeRef::get(VTableHolder), VK, 732 VIndex, Flags, isOptimized, isDefinition ? CUNode : nullptr, TParams, 733 nullptr, nullptr); 734 735 if (isDefinition) 736 AllSubprograms.push_back(SP); 737 trackIfUnresolved(SP); 738 return SP; 739 } 740 741 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name, 742 DIFile *File, unsigned LineNo) { 743 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name, 744 LineNo); 745 } 746 747 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name, 748 StringRef ConfigurationMacros, 749 StringRef IncludePath, 750 StringRef ISysRoot) { 751 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name, 752 ConfigurationMacros, IncludePath, ISysRoot); 753 } 754 755 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope, 756 DIFile *File, 757 unsigned Discriminator) { 758 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator); 759 } 760 761 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File, 762 unsigned Line, unsigned Col) { 763 // Make these distinct, to avoid merging two lexical blocks on the same 764 // file/line/column. 765 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope), 766 File, Line, Col); 767 } 768 769 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) { 770 assert(V && "no value passed to dbg intrinsic"); 771 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V)); 772 } 773 774 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) { 775 I->setDebugLoc(const_cast<DILocation *>(DL)); 776 return I; 777 } 778 779 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 780 DIExpression *Expr, const DILocation *DL, 781 Instruction *InsertBefore) { 782 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 783 assert(DL && "Expected debug loc"); 784 assert(DL->getScope()->getSubprogram() == 785 VarInfo->getScope()->getSubprogram() && 786 "Expected matching subprograms"); 787 if (!DeclareFn) 788 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 789 790 trackIfUnresolved(VarInfo); 791 trackIfUnresolved(Expr); 792 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 793 MetadataAsValue::get(VMContext, VarInfo), 794 MetadataAsValue::get(VMContext, Expr)}; 795 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL); 796 } 797 798 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 799 DIExpression *Expr, const DILocation *DL, 800 BasicBlock *InsertAtEnd) { 801 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 802 assert(DL && "Expected debug loc"); 803 assert(DL->getScope()->getSubprogram() == 804 VarInfo->getScope()->getSubprogram() && 805 "Expected matching subprograms"); 806 if (!DeclareFn) 807 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 808 809 trackIfUnresolved(VarInfo); 810 trackIfUnresolved(Expr); 811 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 812 MetadataAsValue::get(VMContext, VarInfo), 813 MetadataAsValue::get(VMContext, Expr)}; 814 815 // If this block already has a terminator then insert this intrinsic 816 // before the terminator. 817 if (TerminatorInst *T = InsertAtEnd->getTerminator()) 818 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL); 819 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL); 820 } 821 822 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, 823 DILocalVariable *VarInfo, 824 DIExpression *Expr, 825 const DILocation *DL, 826 Instruction *InsertBefore) { 827 assert(V && "no value passed to dbg.value"); 828 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 829 assert(DL && "Expected debug loc"); 830 assert(DL->getScope()->getSubprogram() == 831 VarInfo->getScope()->getSubprogram() && 832 "Expected matching subprograms"); 833 if (!ValueFn) 834 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 835 836 trackIfUnresolved(VarInfo); 837 trackIfUnresolved(Expr); 838 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 839 ConstantInt::get(Type::getInt64Ty(VMContext), Offset), 840 MetadataAsValue::get(VMContext, VarInfo), 841 MetadataAsValue::get(VMContext, Expr)}; 842 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL); 843 } 844 845 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, 846 DILocalVariable *VarInfo, 847 DIExpression *Expr, 848 const DILocation *DL, 849 BasicBlock *InsertAtEnd) { 850 assert(V && "no value passed to dbg.value"); 851 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 852 assert(DL && "Expected debug loc"); 853 assert(DL->getScope()->getSubprogram() == 854 VarInfo->getScope()->getSubprogram() && 855 "Expected matching subprograms"); 856 if (!ValueFn) 857 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 858 859 trackIfUnresolved(VarInfo); 860 trackIfUnresolved(Expr); 861 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 862 ConstantInt::get(Type::getInt64Ty(VMContext), Offset), 863 MetadataAsValue::get(VMContext, VarInfo), 864 MetadataAsValue::get(VMContext, Expr)}; 865 866 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL); 867 } 868 869 void DIBuilder::replaceVTableHolder(DICompositeType *&T, 870 DICompositeType *VTableHolder) { 871 { 872 TypedTrackingMDRef<DICompositeType> N(T); 873 N->replaceVTableHolder(DITypeRef::get(VTableHolder)); 874 T = N.get(); 875 } 876 877 // If this didn't create a self-reference, just return. 878 if (T != VTableHolder) 879 return; 880 881 // Look for unresolved operands. T will drop RAUW support, orphaning any 882 // cycles underneath it. 883 if (T->isResolved()) 884 for (const MDOperand &O : T->operands()) 885 if (auto *N = dyn_cast_or_null<MDNode>(O)) 886 trackIfUnresolved(N); 887 } 888 889 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements, 890 DINodeArray TParams) { 891 { 892 TypedTrackingMDRef<DICompositeType> N(T); 893 if (Elements) 894 N->replaceElements(Elements); 895 if (TParams) 896 N->replaceTemplateParams(DITemplateParameterArray(TParams)); 897 T = N.get(); 898 } 899 900 // If T isn't resolved, there's no problem. 901 if (!T->isResolved()) 902 return; 903 904 // If T is resolved, it may be due to a self-reference cycle. Track the 905 // arrays explicitly if they're unresolved, or else the cycles will be 906 // orphaned. 907 if (Elements) 908 trackIfUnresolved(Elements.get()); 909 if (TParams) 910 trackIfUnresolved(TParams.get()); 911 } 912