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 DIFile::ChecksumKind CSKind, StringRef Checksum) { 208 return DIFile::get(VMContext, Filename, Directory, CSKind, Checksum); 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 assert(!Name.empty() && "Unable to create enumerator without name"); 238 return DIEnumerator::get(VMContext, Val, Name); 239 } 240 241 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) { 242 assert(!Name.empty() && "Unable to create type without name"); 243 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name); 244 } 245 246 DIBasicType *DIBuilder::createNullPtrType() { 247 return createUnspecifiedType("decltype(nullptr)"); 248 } 249 250 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits, 251 unsigned Encoding) { 252 assert(!Name.empty() && "Unable to create type without name"); 253 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits, 254 0, Encoding); 255 } 256 257 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) { 258 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0, 259 0, 0, None, DINode::FlagZero); 260 } 261 262 DIDerivedType *DIBuilder::createPointerType( 263 DIType *PointeeTy, 264 uint64_t SizeInBits, 265 uint32_t AlignInBits, 266 Optional<unsigned> DWARFAddressSpace, 267 StringRef Name) { 268 // FIXME: Why is there a name here? 269 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name, 270 nullptr, 0, nullptr, PointeeTy, SizeInBits, 271 AlignInBits, 0, DWARFAddressSpace, 272 DINode::FlagZero); 273 } 274 275 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy, 276 DIType *Base, 277 uint64_t SizeInBits, 278 uint32_t AlignInBits, 279 DINode::DIFlags Flags) { 280 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "", 281 nullptr, 0, nullptr, PointeeTy, SizeInBits, 282 AlignInBits, 0, None, Flags, Base); 283 } 284 285 DIDerivedType *DIBuilder::createReferenceType( 286 unsigned Tag, DIType *RTy, 287 uint64_t SizeInBits, 288 uint32_t AlignInBits, 289 Optional<unsigned> DWARFAddressSpace) { 290 assert(RTy && "Unable to create reference type"); 291 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy, 292 SizeInBits, AlignInBits, 0, DWARFAddressSpace, 293 DINode::FlagZero); 294 } 295 296 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name, 297 DIFile *File, unsigned LineNo, 298 DIScope *Context) { 299 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File, 300 LineNo, getNonCompileUnitScope(Context), Ty, 0, 0, 301 0, None, DINode::FlagZero); 302 } 303 304 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) { 305 assert(Ty && "Invalid type!"); 306 assert(FriendTy && "Invalid friend type!"); 307 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty, 308 FriendTy, 0, 0, 0, None, DINode::FlagZero); 309 } 310 311 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy, 312 uint64_t BaseOffset, 313 DINode::DIFlags Flags) { 314 assert(Ty && "Unable to create inheritance"); 315 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr, 316 0, Ty, BaseTy, 0, 0, BaseOffset, None, Flags); 317 } 318 319 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name, 320 DIFile *File, unsigned LineNumber, 321 uint64_t SizeInBits, 322 uint32_t AlignInBits, 323 uint64_t OffsetInBits, 324 DINode::DIFlags Flags, DIType *Ty) { 325 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 326 LineNumber, getNonCompileUnitScope(Scope), Ty, 327 SizeInBits, AlignInBits, OffsetInBits, None, Flags); 328 } 329 330 static ConstantAsMetadata *getConstantOrNull(Constant *C) { 331 if (C) 332 return ConstantAsMetadata::get(C); 333 return nullptr; 334 } 335 336 DIDerivedType *DIBuilder::createBitFieldMemberType( 337 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 338 uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits, 339 DINode::DIFlags Flags, DIType *Ty) { 340 Flags |= DINode::FlagBitField; 341 return DIDerivedType::get( 342 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 343 getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0, 344 OffsetInBits, None, Flags, 345 ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64), 346 StorageOffsetInBits))); 347 } 348 349 DIDerivedType * 350 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File, 351 unsigned LineNumber, DIType *Ty, 352 DINode::DIFlags Flags, llvm::Constant *Val, 353 uint32_t AlignInBits) { 354 Flags |= DINode::FlagStaticMember; 355 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 356 LineNumber, getNonCompileUnitScope(Scope), Ty, 0, 357 AlignInBits, 0, None, Flags, 358 getConstantOrNull(Val)); 359 } 360 361 DIDerivedType * 362 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber, 363 uint64_t SizeInBits, uint32_t AlignInBits, 364 uint64_t OffsetInBits, DINode::DIFlags Flags, 365 DIType *Ty, MDNode *PropertyNode) { 366 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 367 LineNumber, getNonCompileUnitScope(File), Ty, 368 SizeInBits, AlignInBits, OffsetInBits, None, Flags, 369 PropertyNode); 370 } 371 372 DIObjCProperty * 373 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber, 374 StringRef GetterName, StringRef SetterName, 375 unsigned PropertyAttributes, DIType *Ty) { 376 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName, 377 SetterName, PropertyAttributes, Ty); 378 } 379 380 DITemplateTypeParameter * 381 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name, 382 DIType *Ty) { 383 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 384 return DITemplateTypeParameter::get(VMContext, Name, Ty); 385 } 386 387 static DITemplateValueParameter * 388 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag, 389 DIScope *Context, StringRef Name, DIType *Ty, 390 Metadata *MD) { 391 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 392 return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD); 393 } 394 395 DITemplateValueParameter * 396 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name, 397 DIType *Ty, Constant *Val) { 398 return createTemplateValueParameterHelper( 399 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, 400 getConstantOrNull(Val)); 401 } 402 403 DITemplateValueParameter * 404 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name, 405 DIType *Ty, StringRef Val) { 406 return createTemplateValueParameterHelper( 407 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty, 408 MDString::get(VMContext, Val)); 409 } 410 411 DITemplateValueParameter * 412 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name, 413 DIType *Ty, DINodeArray Val) { 414 return createTemplateValueParameterHelper( 415 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty, 416 Val.get()); 417 } 418 419 DICompositeType *DIBuilder::createClassType( 420 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 421 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 422 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements, 423 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) { 424 assert((!Context || isa<DIScope>(Context)) && 425 "createClassType should be called with a valid Context"); 426 427 auto *R = DICompositeType::get( 428 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 429 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 430 OffsetInBits, Flags, Elements, 0, VTableHolder, 431 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier); 432 trackIfUnresolved(R); 433 return R; 434 } 435 436 DICompositeType *DIBuilder::createStructType( 437 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 438 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, 439 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang, 440 DIType *VTableHolder, StringRef UniqueIdentifier) { 441 auto *R = DICompositeType::get( 442 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 443 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0, 444 Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier); 445 trackIfUnresolved(R); 446 return R; 447 } 448 449 DICompositeType *DIBuilder::createUnionType( 450 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 451 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, 452 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) { 453 auto *R = DICompositeType::get( 454 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber, 455 getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags, 456 Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier); 457 trackIfUnresolved(R); 458 return R; 459 } 460 461 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes, 462 DINode::DIFlags Flags, 463 unsigned CC) { 464 return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes); 465 } 466 467 DICompositeType *DIBuilder::createEnumerationType( 468 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 469 uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements, 470 DIType *UnderlyingType, StringRef UniqueIdentifier) { 471 auto *CTy = DICompositeType::get( 472 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber, 473 getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0, 474 DINode::FlagZero, Elements, 0, nullptr, nullptr, UniqueIdentifier); 475 AllEnumTypes.push_back(CTy); 476 trackIfUnresolved(CTy); 477 return CTy; 478 } 479 480 DICompositeType *DIBuilder::createArrayType(uint64_t Size, 481 uint32_t AlignInBits, DIType *Ty, 482 DINodeArray Subscripts) { 483 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", 484 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0, 485 DINode::FlagZero, Subscripts, 0, nullptr); 486 trackIfUnresolved(R); 487 return R; 488 } 489 490 DICompositeType *DIBuilder::createVectorType(uint64_t Size, 491 uint32_t AlignInBits, DIType *Ty, 492 DINodeArray Subscripts) { 493 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", 494 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0, 495 DINode::FlagVector, Subscripts, 0, nullptr); 496 trackIfUnresolved(R); 497 return R; 498 } 499 500 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty, 501 DINode::DIFlags FlagsToSet) { 502 auto NewTy = Ty->clone(); 503 NewTy->setFlags(NewTy->getFlags() | FlagsToSet); 504 return MDNode::replaceWithUniqued(std::move(NewTy)); 505 } 506 507 DIType *DIBuilder::createArtificialType(DIType *Ty) { 508 // FIXME: Restrict this to the nodes where it's valid. 509 if (Ty->isArtificial()) 510 return Ty; 511 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial); 512 } 513 514 DIType *DIBuilder::createObjectPointerType(DIType *Ty) { 515 // FIXME: Restrict this to the nodes where it's valid. 516 if (Ty->isObjectPointer()) 517 return Ty; 518 DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial; 519 return createTypeWithFlags(VMContext, Ty, Flags); 520 } 521 522 void DIBuilder::retainType(DIScope *T) { 523 assert(T && "Expected non-null type"); 524 assert((isa<DIType>(T) || (isa<DISubprogram>(T) && 525 cast<DISubprogram>(T)->isDefinition() == false)) && 526 "Expected type or subprogram declaration"); 527 AllRetainTypes.emplace_back(T); 528 } 529 530 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; } 531 532 DICompositeType * 533 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope, 534 DIFile *F, unsigned Line, unsigned RuntimeLang, 535 uint64_t SizeInBits, uint32_t AlignInBits, 536 StringRef UniqueIdentifier) { 537 // FIXME: Define in terms of createReplaceableForwardDecl() by calling 538 // replaceWithUniqued(). 539 auto *RetTy = DICompositeType::get( 540 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr, 541 SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, 542 nullptr, nullptr, UniqueIdentifier); 543 trackIfUnresolved(RetTy); 544 return RetTy; 545 } 546 547 DICompositeType *DIBuilder::createReplaceableCompositeType( 548 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line, 549 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, 550 DINode::DIFlags Flags, StringRef UniqueIdentifier) { 551 auto *RetTy = 552 DICompositeType::getTemporary( 553 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr, 554 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr, 555 nullptr, UniqueIdentifier) 556 .release(); 557 trackIfUnresolved(RetTy); 558 return RetTy; 559 } 560 561 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) { 562 return MDTuple::get(VMContext, Elements); 563 } 564 565 DIMacroNodeArray 566 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) { 567 return MDTuple::get(VMContext, Elements); 568 } 569 570 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) { 571 SmallVector<llvm::Metadata *, 16> Elts; 572 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 573 if (Elements[i] && isa<MDNode>(Elements[i])) 574 Elts.push_back(cast<DIType>(Elements[i])); 575 else 576 Elts.push_back(Elements[i]); 577 } 578 return DITypeRefArray(MDNode::get(VMContext, Elts)); 579 } 580 581 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) { 582 return DISubrange::get(VMContext, Count, Lo); 583 } 584 585 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) { 586 return DISubrange::get(VMContext, CountNode, Lo); 587 } 588 589 static void checkGlobalVariableScope(DIScope *Context) { 590 #ifndef NDEBUG 591 if (auto *CT = 592 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context))) 593 assert(CT->getIdentifier().empty() && 594 "Context of a global variable should not be a type with identifier"); 595 #endif 596 } 597 598 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression( 599 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 600 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, DIExpression *Expr, 601 MDNode *Decl, uint32_t AlignInBits) { 602 checkGlobalVariableScope(Context); 603 604 auto *GV = DIGlobalVariable::getDistinct( 605 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, 606 LineNumber, Ty, isLocalToUnit, true, cast_or_null<DIDerivedType>(Decl), 607 AlignInBits); 608 if (!Expr) 609 Expr = createExpression(); 610 auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr); 611 AllGVs.push_back(N); 612 return N; 613 } 614 615 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl( 616 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 617 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, MDNode *Decl, 618 uint32_t AlignInBits) { 619 checkGlobalVariableScope(Context); 620 621 return DIGlobalVariable::getTemporary( 622 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, 623 LineNumber, Ty, isLocalToUnit, false, 624 cast_or_null<DIDerivedType>(Decl), AlignInBits) 625 .release(); 626 } 627 628 static DILocalVariable *createLocalVariable( 629 LLVMContext &VMContext, 630 DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables, 631 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, 632 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags, 633 uint32_t AlignInBits) { 634 // FIXME: Why getNonCompileUnitScope()? 635 // FIXME: Why is "!Context" okay here? 636 // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT 637 // the only valid scopes)? 638 DIScope *Context = getNonCompileUnitScope(Scope); 639 640 auto *Node = 641 DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name, 642 File, LineNo, Ty, ArgNo, Flags, AlignInBits); 643 if (AlwaysPreserve) { 644 // The optimizer may remove local variables. If there is an interest 645 // to preserve variable info in such situation then stash it in a 646 // named mdnode. 647 DISubprogram *Fn = getDISubprogram(Scope); 648 assert(Fn && "Missing subprogram for local variable"); 649 PreservedVariables[Fn].emplace_back(Node); 650 } 651 return Node; 652 } 653 654 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name, 655 DIFile *File, unsigned LineNo, 656 DIType *Ty, bool AlwaysPreserve, 657 DINode::DIFlags Flags, 658 uint32_t AlignInBits) { 659 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, 660 /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve, 661 Flags, AlignInBits); 662 } 663 664 DILocalVariable *DIBuilder::createParameterVariable( 665 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, 666 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) { 667 assert(ArgNo && "Expected non-zero argument number for parameter"); 668 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo, 669 File, LineNo, Ty, AlwaysPreserve, Flags, 670 /* AlignInBits */0); 671 } 672 673 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) { 674 return DIExpression::get(VMContext, Addr); 675 } 676 677 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) { 678 // TODO: Remove the callers of this signed version and delete. 679 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end()); 680 return createExpression(Addr); 681 } 682 683 template <class... Ts> 684 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) { 685 if (IsDistinct) 686 return DISubprogram::getDistinct(std::forward<Ts>(Args)...); 687 return DISubprogram::get(std::forward<Ts>(Args)...); 688 } 689 690 DISubprogram *DIBuilder::createFunction( 691 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 692 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 693 bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags, 694 bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl, 695 DITypeArray ThrownTypes) { 696 auto *Node = getSubprogram( 697 /* IsDistinct = */ isDefinition, VMContext, 698 getNonCompileUnitScope(Context), Name, LinkageName, File, LineNo, Ty, 699 isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, 0, Flags, 700 isOptimized, isDefinition ? CUNode : nullptr, TParams, Decl, 701 MDTuple::getTemporary(VMContext, None).release(), ThrownTypes); 702 703 if (isDefinition) 704 AllSubprograms.push_back(Node); 705 trackIfUnresolved(Node); 706 return Node; 707 } 708 709 DISubprogram *DIBuilder::createTempFunctionFwdDecl( 710 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 711 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 712 bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags, 713 bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl, 714 DITypeArray ThrownTypes) { 715 return DISubprogram::getTemporary( 716 VMContext, getNonCompileUnitScope(Context), Name, LinkageName, 717 File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr, 718 0, 0, 0, Flags, isOptimized, isDefinition ? CUNode : nullptr, 719 TParams, Decl, nullptr, ThrownTypes) 720 .release(); 721 } 722 723 DISubprogram *DIBuilder::createMethod( 724 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 725 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 726 bool isDefinition, unsigned VK, unsigned VIndex, int ThisAdjustment, 727 DIType *VTableHolder, DINode::DIFlags Flags, bool isOptimized, 728 DITemplateParameterArray TParams, DITypeArray ThrownTypes) { 729 assert(getNonCompileUnitScope(Context) && 730 "Methods should have both a Context and a context that isn't " 731 "the compile unit."); 732 // FIXME: Do we want to use different scope/lines? 733 auto *SP = getSubprogram( 734 /* IsDistinct = */ isDefinition, VMContext, cast<DIScope>(Context), Name, 735 LinkageName, F, LineNo, Ty, isLocalToUnit, isDefinition, LineNo, 736 VTableHolder, VK, VIndex, ThisAdjustment, Flags, isOptimized, 737 isDefinition ? CUNode : nullptr, TParams, nullptr, nullptr, ThrownTypes); 738 739 if (isDefinition) 740 AllSubprograms.push_back(SP); 741 trackIfUnresolved(SP); 742 return SP; 743 } 744 745 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name, 746 bool ExportSymbols) { 747 748 // It is okay to *not* make anonymous top-level namespaces distinct, because 749 // all nodes that have an anonymous namespace as their parent scope are 750 // guaranteed to be unique and/or are linked to their containing 751 // DICompileUnit. This decision is an explicit tradeoff of link time versus 752 // memory usage versus code simplicity and may get revisited in the future. 753 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name, 754 ExportSymbols); 755 } 756 757 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name, 758 StringRef ConfigurationMacros, 759 StringRef IncludePath, 760 StringRef ISysRoot) { 761 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name, 762 ConfigurationMacros, IncludePath, ISysRoot); 763 } 764 765 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope, 766 DIFile *File, 767 unsigned Discriminator) { 768 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator); 769 } 770 771 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File, 772 unsigned Line, unsigned Col) { 773 // Make these distinct, to avoid merging two lexical blocks on the same 774 // file/line/column. 775 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope), 776 File, Line, Col); 777 } 778 779 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 780 DIExpression *Expr, const DILocation *DL, 781 Instruction *InsertBefore) { 782 return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(), 783 InsertBefore); 784 } 785 786 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 787 DIExpression *Expr, const DILocation *DL, 788 BasicBlock *InsertAtEnd) { 789 // If this block already has a terminator then insert this intrinsic before 790 // the terminator. Otherwise, put it at the end of the block. 791 Instruction *InsertBefore = InsertAtEnd->getTerminator(); 792 return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore); 793 } 794 795 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, 796 DILocalVariable *VarInfo, 797 DIExpression *Expr, 798 const DILocation *DL, 799 Instruction *InsertBefore) { 800 return insertDbgValueIntrinsic( 801 V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr, 802 InsertBefore); 803 } 804 805 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, 806 DILocalVariable *VarInfo, 807 DIExpression *Expr, 808 const DILocation *DL, 809 BasicBlock *InsertAtEnd) { 810 return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr); 811 } 812 813 /// Return an IRBuilder for inserting dbg.declare and dbg.value intrinsics. This 814 /// abstracts over the various ways to specify an insert position. 815 static IRBuilder<> getIRBForDbgInsertion(const DILocation *DL, 816 BasicBlock *InsertBB, 817 Instruction *InsertBefore) { 818 IRBuilder<> B(DL->getContext()); 819 if (InsertBefore) 820 B.SetInsertPoint(InsertBefore); 821 else if (InsertBB) 822 B.SetInsertPoint(InsertBB); 823 B.SetCurrentDebugLocation(DL); 824 return B; 825 } 826 827 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) { 828 assert(V && "no value passed to dbg intrinsic"); 829 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V)); 830 } 831 832 static Function *getDeclareIntrin(Module &M) { 833 return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr 834 : Intrinsic::dbg_declare); 835 } 836 837 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 838 DIExpression *Expr, const DILocation *DL, 839 BasicBlock *InsertBB, Instruction *InsertBefore) { 840 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 841 assert(DL && "Expected debug loc"); 842 assert(DL->getScope()->getSubprogram() == 843 VarInfo->getScope()->getSubprogram() && 844 "Expected matching subprograms"); 845 if (!DeclareFn) 846 DeclareFn = getDeclareIntrin(M); 847 848 trackIfUnresolved(VarInfo); 849 trackIfUnresolved(Expr); 850 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 851 MetadataAsValue::get(VMContext, VarInfo), 852 MetadataAsValue::get(VMContext, Expr)}; 853 854 IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore); 855 return B.CreateCall(DeclareFn, Args); 856 } 857 858 Instruction *DIBuilder::insertDbgValueIntrinsic( 859 Value *V, DILocalVariable *VarInfo, DIExpression *Expr, 860 const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) { 861 assert(V && "no value passed to dbg.value"); 862 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 863 assert(DL && "Expected debug loc"); 864 assert(DL->getScope()->getSubprogram() == 865 VarInfo->getScope()->getSubprogram() && 866 "Expected matching subprograms"); 867 if (!ValueFn) 868 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 869 870 trackIfUnresolved(VarInfo); 871 trackIfUnresolved(Expr); 872 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 873 MetadataAsValue::get(VMContext, VarInfo), 874 MetadataAsValue::get(VMContext, Expr)}; 875 876 IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore); 877 return B.CreateCall(ValueFn, Args); 878 } 879 880 void DIBuilder::replaceVTableHolder(DICompositeType *&T, 881 DIType *VTableHolder) { 882 { 883 TypedTrackingMDRef<DICompositeType> N(T); 884 N->replaceVTableHolder(VTableHolder); 885 T = N.get(); 886 } 887 888 // If this didn't create a self-reference, just return. 889 if (T != VTableHolder) 890 return; 891 892 // Look for unresolved operands. T will drop RAUW support, orphaning any 893 // cycles underneath it. 894 if (T->isResolved()) 895 for (const MDOperand &O : T->operands()) 896 if (auto *N = dyn_cast_or_null<MDNode>(O)) 897 trackIfUnresolved(N); 898 } 899 900 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements, 901 DINodeArray TParams) { 902 { 903 TypedTrackingMDRef<DICompositeType> N(T); 904 if (Elements) 905 N->replaceElements(Elements); 906 if (TParams) 907 N->replaceTemplateParams(DITemplateParameterArray(TParams)); 908 T = N.get(); 909 } 910 911 // If T isn't resolved, there's no problem. 912 if (!T->isResolved()) 913 return; 914 915 // If T is resolved, it may be due to a self-reference cycle. Track the 916 // arrays explicitly if they're unresolved, or else the cycles will be 917 // orphaned. 918 if (Elements) 919 trackIfUnresolved(Elements.get()); 920 if (TParams) 921 trackIfUnresolved(TParams.get()); 922 } 923