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 "LLVMContextImpl.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/BinaryFormat/Dwarf.h" 18 #include "llvm/IR/Constants.h" 19 #include "llvm/IR/DebugInfo.h" 20 #include "llvm/IR/IntrinsicInst.h" 21 #include "llvm/IR/Module.h" 22 #include "llvm/Support/Debug.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::finalizeSubprogram(DISubprogram *SP) { 43 MDTuple *Temp = SP->getVariables().get(); 44 if (!Temp || !Temp->isTemporary()) 45 return; 46 47 SmallVector<Metadata *, 4> Variables; 48 49 auto PV = PreservedVariables.find(SP); 50 if (PV != PreservedVariables.end()) 51 Variables.append(PV->second.begin(), PV->second.end()); 52 53 DINodeArray AV = getOrCreateArray(Variables); 54 TempMDTuple(Temp)->replaceAllUsesWith(AV.get()); 55 } 56 57 void DIBuilder::finalize() { 58 if (!CUNode) { 59 assert(!AllowUnresolvedNodes && 60 "creating type nodes without a CU is not supported"); 61 return; 62 } 63 64 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes)); 65 66 SmallVector<Metadata *, 16> RetainValues; 67 // Declarations and definitions of the same type may be retained. Some 68 // clients RAUW these pairs, leaving duplicates in the retained types 69 // list. Use a set to remove the duplicates while we transform the 70 // TrackingVHs back into Values. 71 SmallPtrSet<Metadata *, 16> RetainSet; 72 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++) 73 if (RetainSet.insert(AllRetainTypes[I]).second) 74 RetainValues.push_back(AllRetainTypes[I]); 75 76 if (!RetainValues.empty()) 77 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues)); 78 79 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms); 80 for (auto *SP : SPs) 81 finalizeSubprogram(SP); 82 for (auto *N : RetainValues) 83 if (auto *SP = dyn_cast<DISubprogram>(N)) 84 finalizeSubprogram(SP); 85 86 if (!AllGVs.empty()) 87 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs)); 88 89 if (!AllImportedModules.empty()) 90 CUNode->replaceImportedEntities(MDTuple::get( 91 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(), 92 AllImportedModules.end()))); 93 94 for (const auto &I : AllMacrosPerParent) { 95 // DIMacroNode's with nullptr parent are DICompileUnit direct children. 96 if (!I.first) { 97 CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef())); 98 continue; 99 } 100 // Otherwise, it must be a temporary DIMacroFile that need to be resolved. 101 auto *TMF = cast<DIMacroFile>(I.first); 102 auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file, 103 TMF->getLine(), TMF->getFile(), 104 getOrCreateMacroArray(I.second.getArrayRef())); 105 replaceTemporary(llvm::TempDIMacroNode(TMF), MF); 106 } 107 108 // Now that all temp nodes have been replaced or deleted, resolve remaining 109 // cycles. 110 for (const auto &N : UnresolvedNodes) 111 if (N && !N->isResolved()) 112 N->resolveCycles(); 113 UnresolvedNodes.clear(); 114 115 // Can't handle unresolved nodes anymore. 116 AllowUnresolvedNodes = false; 117 } 118 119 /// If N is compile unit return NULL otherwise return N. 120 static DIScope *getNonCompileUnitScope(DIScope *N) { 121 if (!N || isa<DICompileUnit>(N)) 122 return nullptr; 123 return cast<DIScope>(N); 124 } 125 126 DICompileUnit *DIBuilder::createCompileUnit( 127 unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized, 128 StringRef Flags, unsigned RunTimeVer, StringRef SplitName, 129 DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId, 130 bool SplitDebugInlining, bool DebugInfoForProfiling) { 131 132 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) || 133 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && 134 "Invalid Language tag"); 135 136 assert(!CUNode && "Can only make one compile unit per DIBuilder instance"); 137 CUNode = DICompileUnit::getDistinct( 138 VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer, 139 SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId, 140 SplitDebugInlining, DebugInfoForProfiling); 141 142 // Create a named metadata so that it is easier to find cu in a module. 143 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); 144 NMD->addOperand(CUNode); 145 trackIfUnresolved(CUNode); 146 return CUNode; 147 } 148 149 static DIImportedEntity * 150 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context, 151 Metadata *NS, unsigned Line, StringRef Name, 152 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) { 153 unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size(); 154 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name); 155 if (EntitiesCount < C.pImpl->DIImportedEntitys.size()) 156 // A new Imported Entity was just added to the context. 157 // Add it to the Imported Modules list. 158 AllImportedModules.emplace_back(M); 159 return M; 160 } 161 162 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 163 DINamespace *NS, 164 unsigned Line) { 165 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 166 Context, NS, Line, StringRef(), AllImportedModules); 167 } 168 169 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 170 DIImportedEntity *NS, 171 unsigned Line) { 172 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 173 Context, NS, Line, StringRef(), AllImportedModules); 174 } 175 176 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M, 177 unsigned Line) { 178 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 179 Context, M, Line, StringRef(), AllImportedModules); 180 } 181 182 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context, 183 DINode *Decl, 184 unsigned Line, 185 StringRef Name) { 186 // Make sure to use the unique identifier based metadata reference for 187 // types that have one. 188 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration, 189 Context, Decl, Line, Name, AllImportedModules); 190 } 191 192 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory, 193 DIFile::ChecksumKind CSKind, StringRef Checksum) { 194 return DIFile::get(VMContext, Filename, Directory, CSKind, Checksum); 195 } 196 197 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber, 198 unsigned MacroType, StringRef Name, 199 StringRef Value) { 200 assert(!Name.empty() && "Unable to create macro without name"); 201 assert((MacroType == dwarf::DW_MACINFO_undef || 202 MacroType == dwarf::DW_MACINFO_define) && 203 "Unexpected macro type"); 204 auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value); 205 AllMacrosPerParent[Parent].insert(M); 206 return M; 207 } 208 209 DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent, 210 unsigned LineNumber, DIFile *File) { 211 auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file, 212 LineNumber, File, DIMacroNodeArray()) 213 .release(); 214 AllMacrosPerParent[Parent].insert(MF); 215 // Add the new temporary DIMacroFile to the macro per parent map as a parent. 216 // This is needed to assure DIMacroFile with no children to have an entry in 217 // the map. Otherwise, it will not be resolved in DIBuilder::finalize(). 218 AllMacrosPerParent.insert({MF, {}}); 219 return MF; 220 } 221 222 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) { 223 assert(!Name.empty() && "Unable to create enumerator without name"); 224 return DIEnumerator::get(VMContext, Val, Name); 225 } 226 227 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) { 228 assert(!Name.empty() && "Unable to create type without name"); 229 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name); 230 } 231 232 DIBasicType *DIBuilder::createNullPtrType() { 233 return createUnspecifiedType("decltype(nullptr)"); 234 } 235 236 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits, 237 unsigned Encoding) { 238 assert(!Name.empty() && "Unable to create type without name"); 239 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits, 240 0, Encoding); 241 } 242 243 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) { 244 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0, 245 0, 0, None, DINode::FlagZero); 246 } 247 248 DIDerivedType *DIBuilder::createPointerType( 249 DIType *PointeeTy, 250 uint64_t SizeInBits, 251 uint32_t AlignInBits, 252 Optional<unsigned> DWARFAddressSpace, 253 StringRef Name) { 254 // FIXME: Why is there a name here? 255 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name, 256 nullptr, 0, nullptr, PointeeTy, SizeInBits, 257 AlignInBits, 0, DWARFAddressSpace, 258 DINode::FlagZero); 259 } 260 261 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy, 262 DIType *Base, 263 uint64_t SizeInBits, 264 uint32_t AlignInBits, 265 DINode::DIFlags Flags) { 266 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "", 267 nullptr, 0, nullptr, PointeeTy, SizeInBits, 268 AlignInBits, 0, None, Flags, Base); 269 } 270 271 DIDerivedType *DIBuilder::createReferenceType( 272 unsigned Tag, DIType *RTy, 273 uint64_t SizeInBits, 274 uint32_t AlignInBits, 275 Optional<unsigned> DWARFAddressSpace) { 276 assert(RTy && "Unable to create reference type"); 277 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy, 278 SizeInBits, AlignInBits, 0, DWARFAddressSpace, 279 DINode::FlagZero); 280 } 281 282 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name, 283 DIFile *File, unsigned LineNo, 284 DIScope *Context) { 285 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File, 286 LineNo, getNonCompileUnitScope(Context), Ty, 0, 0, 287 0, None, DINode::FlagZero); 288 } 289 290 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) { 291 assert(Ty && "Invalid type!"); 292 assert(FriendTy && "Invalid friend type!"); 293 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty, 294 FriendTy, 0, 0, 0, None, DINode::FlagZero); 295 } 296 297 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy, 298 uint64_t BaseOffset, 299 DINode::DIFlags Flags) { 300 assert(Ty && "Unable to create inheritance"); 301 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr, 302 0, Ty, BaseTy, 0, 0, BaseOffset, None, Flags); 303 } 304 305 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name, 306 DIFile *File, unsigned LineNumber, 307 uint64_t SizeInBits, 308 uint32_t AlignInBits, 309 uint64_t OffsetInBits, 310 DINode::DIFlags Flags, DIType *Ty) { 311 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 312 LineNumber, getNonCompileUnitScope(Scope), Ty, 313 SizeInBits, AlignInBits, OffsetInBits, None, Flags); 314 } 315 316 static ConstantAsMetadata *getConstantOrNull(Constant *C) { 317 if (C) 318 return ConstantAsMetadata::get(C); 319 return nullptr; 320 } 321 322 DIDerivedType *DIBuilder::createBitFieldMemberType( 323 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 324 uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits, 325 DINode::DIFlags Flags, DIType *Ty) { 326 Flags |= DINode::FlagBitField; 327 return DIDerivedType::get( 328 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 329 getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0, 330 OffsetInBits, None, Flags, 331 ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64), 332 StorageOffsetInBits))); 333 } 334 335 DIDerivedType * 336 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File, 337 unsigned LineNumber, DIType *Ty, 338 DINode::DIFlags Flags, llvm::Constant *Val, 339 uint32_t AlignInBits) { 340 Flags |= DINode::FlagStaticMember; 341 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 342 LineNumber, getNonCompileUnitScope(Scope), Ty, 0, 343 AlignInBits, 0, None, Flags, 344 getConstantOrNull(Val)); 345 } 346 347 DIDerivedType * 348 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber, 349 uint64_t SizeInBits, uint32_t AlignInBits, 350 uint64_t OffsetInBits, DINode::DIFlags Flags, 351 DIType *Ty, MDNode *PropertyNode) { 352 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 353 LineNumber, getNonCompileUnitScope(File), Ty, 354 SizeInBits, AlignInBits, OffsetInBits, None, Flags, 355 PropertyNode); 356 } 357 358 DIObjCProperty * 359 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber, 360 StringRef GetterName, StringRef SetterName, 361 unsigned PropertyAttributes, DIType *Ty) { 362 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName, 363 SetterName, PropertyAttributes, Ty); 364 } 365 366 DITemplateTypeParameter * 367 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name, 368 DIType *Ty) { 369 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 370 return DITemplateTypeParameter::get(VMContext, Name, Ty); 371 } 372 373 static DITemplateValueParameter * 374 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag, 375 DIScope *Context, StringRef Name, DIType *Ty, 376 Metadata *MD) { 377 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 378 return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD); 379 } 380 381 DITemplateValueParameter * 382 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name, 383 DIType *Ty, Constant *Val) { 384 return createTemplateValueParameterHelper( 385 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, 386 getConstantOrNull(Val)); 387 } 388 389 DITemplateValueParameter * 390 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name, 391 DIType *Ty, StringRef Val) { 392 return createTemplateValueParameterHelper( 393 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty, 394 MDString::get(VMContext, Val)); 395 } 396 397 DITemplateValueParameter * 398 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name, 399 DIType *Ty, DINodeArray Val) { 400 return createTemplateValueParameterHelper( 401 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty, 402 Val.get()); 403 } 404 405 DICompositeType *DIBuilder::createClassType( 406 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 407 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 408 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements, 409 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) { 410 assert((!Context || isa<DIScope>(Context)) && 411 "createClassType should be called with a valid Context"); 412 413 auto *R = DICompositeType::get( 414 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 415 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 416 OffsetInBits, Flags, Elements, 0, VTableHolder, 417 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier); 418 trackIfUnresolved(R); 419 return R; 420 } 421 422 DICompositeType *DIBuilder::createStructType( 423 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 424 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, 425 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang, 426 DIType *VTableHolder, StringRef UniqueIdentifier) { 427 auto *R = DICompositeType::get( 428 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 429 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0, 430 Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier); 431 trackIfUnresolved(R); 432 return R; 433 } 434 435 DICompositeType *DIBuilder::createUnionType( 436 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 437 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, 438 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) { 439 auto *R = DICompositeType::get( 440 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber, 441 getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags, 442 Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier); 443 trackIfUnresolved(R); 444 return R; 445 } 446 447 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes, 448 DINode::DIFlags Flags, 449 unsigned CC) { 450 return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes); 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 DITypeArray ThrownTypes) { 682 auto *Node = getSubprogram( 683 /* IsDistinct = */ isDefinition, VMContext, 684 getNonCompileUnitScope(Context), Name, LinkageName, File, LineNo, Ty, 685 isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, 0, Flags, 686 isOptimized, isDefinition ? CUNode : nullptr, TParams, Decl, 687 MDTuple::getTemporary(VMContext, None).release(), ThrownTypes); 688 689 if (isDefinition) 690 AllSubprograms.push_back(Node); 691 trackIfUnresolved(Node); 692 return Node; 693 } 694 695 DISubprogram *DIBuilder::createTempFunctionFwdDecl( 696 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 697 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 698 bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags, 699 bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl, 700 DITypeArray ThrownTypes) { 701 return DISubprogram::getTemporary( 702 VMContext, getNonCompileUnitScope(Context), Name, LinkageName, 703 File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr, 704 0, 0, 0, Flags, isOptimized, isDefinition ? CUNode : nullptr, 705 TParams, Decl, nullptr, ThrownTypes) 706 .release(); 707 } 708 709 DISubprogram *DIBuilder::createMethod( 710 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 711 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 712 bool isDefinition, unsigned VK, unsigned VIndex, int ThisAdjustment, 713 DIType *VTableHolder, DINode::DIFlags Flags, bool isOptimized, 714 DITemplateParameterArray TParams, DITypeArray ThrownTypes) { 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, ThrownTypes); 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 bool ExportSymbols) { 733 734 // It is okay to *not* make anonymous top-level namespaces distinct, because 735 // all nodes that have an anonymous namespace as their parent scope are 736 // guaranteed to be unique and/or are linked to their containing 737 // DICompileUnit. This decision is an explicit tradeoff of link time versus 738 // memory usage versus code simplicity and may get revisited in the future. 739 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name, 740 ExportSymbols); 741 } 742 743 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name, 744 StringRef ConfigurationMacros, 745 StringRef IncludePath, 746 StringRef ISysRoot) { 747 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name, 748 ConfigurationMacros, IncludePath, ISysRoot); 749 } 750 751 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope, 752 DIFile *File, 753 unsigned Discriminator) { 754 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator); 755 } 756 757 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File, 758 unsigned Line, unsigned Col) { 759 // Make these distinct, to avoid merging two lexical blocks on the same 760 // file/line/column. 761 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope), 762 File, Line, Col); 763 } 764 765 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) { 766 assert(V && "no value passed to dbg intrinsic"); 767 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V)); 768 } 769 770 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) { 771 I->setDebugLoc(const_cast<DILocation *>(DL)); 772 return I; 773 } 774 775 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 776 DIExpression *Expr, const DILocation *DL, 777 Instruction *InsertBefore) { 778 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 779 assert(DL && "Expected debug loc"); 780 assert(DL->getScope()->getSubprogram() == 781 VarInfo->getScope()->getSubprogram() && 782 "Expected matching subprograms"); 783 if (!DeclareFn) 784 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 785 786 trackIfUnresolved(VarInfo); 787 trackIfUnresolved(Expr); 788 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 789 MetadataAsValue::get(VMContext, VarInfo), 790 MetadataAsValue::get(VMContext, Expr)}; 791 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL); 792 } 793 794 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 795 DIExpression *Expr, const DILocation *DL, 796 BasicBlock *InsertAtEnd) { 797 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 798 assert(DL && "Expected debug loc"); 799 assert(DL->getScope()->getSubprogram() == 800 VarInfo->getScope()->getSubprogram() && 801 "Expected matching subprograms"); 802 if (!DeclareFn) 803 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 804 805 trackIfUnresolved(VarInfo); 806 trackIfUnresolved(Expr); 807 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 808 MetadataAsValue::get(VMContext, VarInfo), 809 MetadataAsValue::get(VMContext, Expr)}; 810 811 // If this block already has a terminator then insert this intrinsic 812 // before the terminator. 813 if (TerminatorInst *T = InsertAtEnd->getTerminator()) 814 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL); 815 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL); 816 } 817 818 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, 819 DILocalVariable *VarInfo, 820 DIExpression *Expr, 821 const DILocation *DL, 822 Instruction *InsertBefore) { 823 assert(V && "no value passed to dbg.value"); 824 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 825 assert(DL && "Expected debug loc"); 826 assert(DL->getScope()->getSubprogram() == 827 VarInfo->getScope()->getSubprogram() && 828 "Expected matching subprograms"); 829 if (!ValueFn) 830 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 831 832 trackIfUnresolved(VarInfo); 833 trackIfUnresolved(Expr); 834 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 835 ConstantInt::get(Type::getInt64Ty(VMContext), Offset), 836 MetadataAsValue::get(VMContext, VarInfo), 837 MetadataAsValue::get(VMContext, Expr)}; 838 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL); 839 } 840 841 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, 842 DILocalVariable *VarInfo, 843 DIExpression *Expr, 844 const DILocation *DL, 845 BasicBlock *InsertAtEnd) { 846 assert(V && "no value passed to dbg.value"); 847 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 848 assert(DL && "Expected debug loc"); 849 assert(DL->getScope()->getSubprogram() == 850 VarInfo->getScope()->getSubprogram() && 851 "Expected matching subprograms"); 852 if (!ValueFn) 853 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 854 855 trackIfUnresolved(VarInfo); 856 trackIfUnresolved(Expr); 857 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 858 ConstantInt::get(Type::getInt64Ty(VMContext), Offset), 859 MetadataAsValue::get(VMContext, VarInfo), 860 MetadataAsValue::get(VMContext, Expr)}; 861 862 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL); 863 } 864 865 void DIBuilder::replaceVTableHolder(DICompositeType *&T, 866 DICompositeType *VTableHolder) { 867 { 868 TypedTrackingMDRef<DICompositeType> N(T); 869 N->replaceVTableHolder(VTableHolder); 870 T = N.get(); 871 } 872 873 // If this didn't create a self-reference, just return. 874 if (T != VTableHolder) 875 return; 876 877 // Look for unresolved operands. T will drop RAUW support, orphaning any 878 // cycles underneath it. 879 if (T->isResolved()) 880 for (const MDOperand &O : T->operands()) 881 if (auto *N = dyn_cast_or_null<MDNode>(O)) 882 trackIfUnresolved(N); 883 } 884 885 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements, 886 DINodeArray TParams) { 887 { 888 TypedTrackingMDRef<DICompositeType> N(T); 889 if (Elements) 890 N->replaceElements(Elements); 891 if (TParams) 892 N->replaceTemplateParams(DITemplateParameterArray(TParams)); 893 T = N.get(); 894 } 895 896 // If T isn't resolved, there's no problem. 897 if (!T->isResolved()) 898 return; 899 900 // If T is resolved, it may be due to a self-reference cycle. Track the 901 // arrays explicitly if they're unresolved, or else the cycles will be 902 // orphaned. 903 if (Elements) 904 trackIfUnresolved(Elements.get()); 905 if (TParams) 906 trackIfUnresolved(TParams.get()); 907 } 908