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