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