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