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