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