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