1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===// 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 contains support for writing dwarf debug info into asm files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "DwarfDebug.h" 15 16 #include "ByteStreamer.h" 17 #include "DwarfCompileUnit.h" 18 #include "DIE.h" 19 #include "DIEHash.h" 20 #include "DwarfUnit.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineModuleInfo.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DIBuilder.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/DebugInfo.h" 31 #include "llvm/IR/Instructions.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/ValueHandle.h" 34 #include "llvm/MC/MCAsmInfo.h" 35 #include "llvm/MC/MCSection.h" 36 #include "llvm/MC/MCStreamer.h" 37 #include "llvm/MC/MCSymbol.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/Dwarf.h" 41 #include "llvm/Support/Endian.h" 42 #include "llvm/Support/ErrorHandling.h" 43 #include "llvm/Support/FormattedStream.h" 44 #include "llvm/Support/LEB128.h" 45 #include "llvm/Support/MD5.h" 46 #include "llvm/Support/Path.h" 47 #include "llvm/Support/Timer.h" 48 #include "llvm/Target/TargetFrameLowering.h" 49 #include "llvm/Target/TargetLoweringObjectFile.h" 50 #include "llvm/Target/TargetMachine.h" 51 #include "llvm/Target/TargetOptions.h" 52 #include "llvm/Target/TargetRegisterInfo.h" 53 #include "llvm/Target/TargetSubtargetInfo.h" 54 using namespace llvm; 55 56 #define DEBUG_TYPE "dwarfdebug" 57 58 static cl::opt<bool> 59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 60 cl::desc("Disable debug info printing")); 61 62 static cl::opt<bool> UnknownLocations( 63 "use-unknown-locations", cl::Hidden, 64 cl::desc("Make an absence of debug location information explicit."), 65 cl::init(false)); 66 67 static cl::opt<bool> 68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden, 69 cl::desc("Generate GNU-style pubnames and pubtypes"), 70 cl::init(false)); 71 72 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 73 cl::Hidden, 74 cl::desc("Generate dwarf aranges"), 75 cl::init(false)); 76 77 namespace { 78 enum DefaultOnOff { Default, Enable, Disable }; 79 } 80 81 static cl::opt<DefaultOnOff> 82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden, 83 cl::desc("Output prototype dwarf accelerator tables."), 84 cl::values(clEnumVal(Default, "Default for platform"), 85 clEnumVal(Enable, "Enabled"), 86 clEnumVal(Disable, "Disabled"), clEnumValEnd), 87 cl::init(Default)); 88 89 static cl::opt<DefaultOnOff> 90 SplitDwarf("split-dwarf", cl::Hidden, 91 cl::desc("Output DWARF5 split debug info."), 92 cl::values(clEnumVal(Default, "Default for platform"), 93 clEnumVal(Enable, "Enabled"), 94 clEnumVal(Disable, "Disabled"), clEnumValEnd), 95 cl::init(Default)); 96 97 static cl::opt<DefaultOnOff> 98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden, 99 cl::desc("Generate DWARF pubnames and pubtypes sections"), 100 cl::values(clEnumVal(Default, "Default for platform"), 101 clEnumVal(Enable, "Enabled"), 102 clEnumVal(Disable, "Disabled"), clEnumValEnd), 103 cl::init(Default)); 104 105 static const char *const DWARFGroupName = "DWARF Emission"; 106 static const char *const DbgTimerName = "DWARF Debug Writer"; 107 108 //===----------------------------------------------------------------------===// 109 110 /// resolve - Look in the DwarfDebug map for the MDNode that 111 /// corresponds to the reference. 112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const { 113 return DD->resolve(Ref); 114 } 115 116 bool DbgVariable::isBlockByrefVariable() const { 117 assert(Var.isVariable() && "Invalid complex DbgVariable!"); 118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap()); 119 } 120 121 DIType DbgVariable::getType() const { 122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap()); 123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 124 // addresses instead. 125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) { 126 /* Byref variables, in Blocks, are declared by the programmer as 127 "SomeType VarName;", but the compiler creates a 128 __Block_byref_x_VarName struct, and gives the variable VarName 129 either the struct, or a pointer to the struct, as its type. This 130 is necessary for various behind-the-scenes things the compiler 131 needs to do with by-reference variables in blocks. 132 133 However, as far as the original *programmer* is concerned, the 134 variable should still have type 'SomeType', as originally declared. 135 136 The following function dives into the __Block_byref_x_VarName 137 struct to find the original type of the variable. This will be 138 passed back to the code generating the type for the Debug 139 Information Entry for the variable 'VarName'. 'VarName' will then 140 have the original type 'SomeType' in its debug information. 141 142 The original type 'SomeType' will be the type of the field named 143 'VarName' inside the __Block_byref_x_VarName struct. 144 145 NOTE: In order for this to not completely fail on the debugger 146 side, the Debug Information Entry for the variable VarName needs to 147 have a DW_AT_location that tells the debugger how to unwind through 148 the pointers and __Block_byref_x_VarName struct to find the actual 149 value of the variable. The function addBlockByrefType does this. */ 150 DIType subType = Ty; 151 uint16_t tag = Ty.getTag(); 152 153 if (tag == dwarf::DW_TAG_pointer_type) 154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom()); 155 156 DIArray Elements = DICompositeType(subType).getElements(); 157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 158 DIDerivedType DT(Elements.getElement(i)); 159 if (getName() == DT.getName()) 160 return (resolve(DT.getTypeDerivedFrom())); 161 } 162 } 163 return Ty; 164 } 165 166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = { 167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4), 168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2), 169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)}; 170 171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 172 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr), 173 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator), 174 UsedNonDefaultText(false), 175 SkeletonHolder(A, "skel_string", DIEValueAllocator), 176 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()), 177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, 178 dwarf::DW_FORM_data4)), 179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, 180 dwarf::DW_FORM_data4)), 181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, 182 dwarf::DW_FORM_data4)), 183 AccelTypes(TypeAtoms) { 184 185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr; 186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr; 187 DwarfLineSectionSym = nullptr; 188 DwarfAddrSectionSym = nullptr; 189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr; 190 FunctionBeginSym = FunctionEndSym = nullptr; 191 CurFn = nullptr; 192 CurMI = nullptr; 193 194 // Turn on accelerator tables for Darwin by default, pubnames by 195 // default for non-Darwin, and handle split dwarf. 196 if (DwarfAccelTables == Default) 197 HasDwarfAccelTables = IsDarwin; 198 else 199 HasDwarfAccelTables = DwarfAccelTables == Enable; 200 201 if (SplitDwarf == Default) 202 HasSplitDwarf = false; 203 else 204 HasSplitDwarf = SplitDwarf == Enable; 205 206 if (DwarfPubSections == Default) 207 HasDwarfPubSections = !IsDarwin; 208 else 209 HasDwarfPubSections = DwarfPubSections == Enable; 210 211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 213 : MMI->getModule()->getDwarfVersion(); 214 215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion); 216 217 { 218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 219 beginModule(); 220 } 221 } 222 223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 224 DwarfDebug::~DwarfDebug() { } 225 226 // Switch to the specified MCSection and emit an assembler 227 // temporary label to it if SymbolStem is specified. 228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section, 229 const char *SymbolStem = nullptr) { 230 Asm->OutStreamer.SwitchSection(Section); 231 if (!SymbolStem) 232 return nullptr; 233 234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem); 235 Asm->OutStreamer.EmitLabel(TmpSym); 236 return TmpSym; 237 } 238 239 static bool isObjCClass(StringRef Name) { 240 return Name.startswith("+") || Name.startswith("-"); 241 } 242 243 static bool hasObjCCategory(StringRef Name) { 244 if (!isObjCClass(Name)) 245 return false; 246 247 return Name.find(") ") != StringRef::npos; 248 } 249 250 static void getObjCClassCategory(StringRef In, StringRef &Class, 251 StringRef &Category) { 252 if (!hasObjCCategory(In)) { 253 Class = In.slice(In.find('[') + 1, In.find(' ')); 254 Category = ""; 255 return; 256 } 257 258 Class = In.slice(In.find('[') + 1, In.find('(')); 259 Category = In.slice(In.find('[') + 1, In.find(' ')); 260 return; 261 } 262 263 static StringRef getObjCMethodName(StringRef In) { 264 return In.slice(In.find(' ') + 1, In.find(']')); 265 } 266 267 // Helper for sorting sections into a stable output order. 268 static bool SectionSort(const MCSection *A, const MCSection *B) { 269 std::string LA = (A ? A->getLabelBeginName() : ""); 270 std::string LB = (B ? B->getLabelBeginName() : ""); 271 return LA < LB; 272 } 273 274 // Add the various names to the Dwarf accelerator table names. 275 // TODO: Determine whether or not we should add names for programs 276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this 277 // is only slightly different than the lookup of non-standard ObjC names. 278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) { 279 if (!SP.isDefinition()) 280 return; 281 addAccelName(SP.getName(), Die); 282 283 // If the linkage name is different than the name, go ahead and output 284 // that as well into the name table. 285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName()) 286 addAccelName(SP.getLinkageName(), Die); 287 288 // If this is an Objective-C selector name add it to the ObjC accelerator 289 // too. 290 if (isObjCClass(SP.getName())) { 291 StringRef Class, Category; 292 getObjCClassCategory(SP.getName(), Class, Category); 293 addAccelObjC(Class, Die); 294 if (Category != "") 295 addAccelObjC(Category, Die); 296 // Also add the base method name to the name table. 297 addAccelName(getObjCMethodName(SP.getName()), Die); 298 } 299 } 300 301 /// isSubprogramContext - Return true if Context is either a subprogram 302 /// or another context nested inside a subprogram. 303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) { 304 if (!Context) 305 return false; 306 DIDescriptor D(Context); 307 if (D.isSubprogram()) 308 return true; 309 if (D.isType()) 310 return isSubprogramContext(resolve(DIType(Context).getContext())); 311 return false; 312 } 313 314 /// Check whether we should create a DIE for the given Scope, return true 315 /// if we don't create a DIE (the corresponding DIE is null). 316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 317 if (Scope->isAbstractScope()) 318 return false; 319 320 // We don't create a DIE if there is no Range. 321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 322 if (Ranges.empty()) 323 return true; 324 325 if (Ranges.size() > 1) 326 return false; 327 328 // We don't create a DIE if we have a single Range and the end label 329 // is null. 330 return !getLabelAfterInsn(Ranges.front().second); 331 } 332 333 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) { 334 assert(Scope && Scope->getScopeNode()); 335 assert(Scope->isAbstractScope()); 336 assert(!Scope->getInlinedAt()); 337 338 const MDNode *SP = Scope->getScopeNode(); 339 340 DIE *&AbsDef = AbstractSPDies[SP]; 341 if (AbsDef) 342 return; 343 344 ProcessedSPNodes.insert(SP); 345 346 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 347 // was inlined from another compile unit. 348 AbsDef = &SPMap[SP]->constructAbstractSubprogramScopeDIE(Scope); 349 } 350 351 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const { 352 if (!GenerateGnuPubSections) 353 return; 354 355 U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 356 } 357 358 // Create new DwarfCompileUnit for the given metadata node with tag 359 // DW_TAG_compile_unit. 360 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) { 361 StringRef FN = DIUnit.getFilename(); 362 CompilationDir = DIUnit.getDirectory(); 363 364 auto OwnedUnit = make_unique<DwarfCompileUnit>( 365 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 366 DwarfCompileUnit &NewCU = *OwnedUnit; 367 DIE &Die = NewCU.getUnitDie(); 368 InfoHolder.addUnit(std::move(OwnedUnit)); 369 370 // LTO with assembly output shares a single line table amongst multiple CUs. 371 // To avoid the compilation directory being ambiguous, let the line table 372 // explicitly describe the directory of all files, never relying on the 373 // compilation directory. 374 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU) 375 Asm->OutStreamer.getContext().setMCLineTableCompilationDir( 376 NewCU.getUniqueID(), CompilationDir); 377 378 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer()); 379 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 380 DIUnit.getLanguage()); 381 NewCU.addString(Die, dwarf::DW_AT_name, FN); 382 383 if (!useSplitDwarf()) { 384 NewCU.initStmtList(DwarfLineSectionSym); 385 386 // If we're using split dwarf the compilation dir is going to be in the 387 // skeleton CU and so we don't need to duplicate it here. 388 if (!CompilationDir.empty()) 389 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 390 391 addGnuPubAttributes(NewCU, Die); 392 } 393 394 if (DIUnit.isOptimized()) 395 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 396 397 StringRef Flags = DIUnit.getFlags(); 398 if (!Flags.empty()) 399 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 400 401 if (unsigned RVer = DIUnit.getRunTimeVersion()) 402 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 403 dwarf::DW_FORM_data1, RVer); 404 405 if (!FirstCU) 406 FirstCU = &NewCU; 407 408 if (useSplitDwarf()) { 409 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(), 410 DwarfInfoDWOSectionSym); 411 NewCU.setSkeleton(constructSkeletonCU(NewCU)); 412 } else 413 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(), 414 DwarfInfoSectionSym); 415 416 CUMap.insert(std::make_pair(DIUnit, &NewCU)); 417 CUDieMap.insert(std::make_pair(&Die, &NewCU)); 418 return NewCU; 419 } 420 421 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 422 const MDNode *N) { 423 DIImportedEntity Module(N); 424 assert(Module.Verify()); 425 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext())) 426 D->addChild(TheCU.constructImportedEntityDIE(Module)); 427 } 428 429 // Emit all Dwarf sections that should come prior to the content. Create 430 // global DIEs and emit initial debug info sections. This is invoked by 431 // the target AsmPrinter. 432 void DwarfDebug::beginModule() { 433 if (DisableDebugInfoPrinting) 434 return; 435 436 const Module *M = MMI->getModule(); 437 438 FunctionDIs = makeSubprogramMap(*M); 439 440 // If module has named metadata anchors then use them, otherwise scan the 441 // module using debug info finder to collect debug info. 442 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu"); 443 if (!CU_Nodes) 444 return; 445 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes); 446 447 // Emit initial sections so we can reference labels later. 448 emitSectionLabels(); 449 450 SingleCU = CU_Nodes->getNumOperands() == 1; 451 452 for (MDNode *N : CU_Nodes->operands()) { 453 DICompileUnit CUNode(N); 454 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode); 455 DIArray ImportedEntities = CUNode.getImportedEntities(); 456 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i) 457 ScopesWithImportedEntities.push_back(std::make_pair( 458 DIImportedEntity(ImportedEntities.getElement(i)).getContext(), 459 ImportedEntities.getElement(i))); 460 std::sort(ScopesWithImportedEntities.begin(), 461 ScopesWithImportedEntities.end(), less_first()); 462 DIArray GVs = CUNode.getGlobalVariables(); 463 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) 464 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i))); 465 DIArray SPs = CUNode.getSubprograms(); 466 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) 467 SPMap.insert(std::make_pair(SPs.getElement(i), &CU)); 468 DIArray EnumTypes = CUNode.getEnumTypes(); 469 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) { 470 DIType Ty(EnumTypes.getElement(i)); 471 // The enum types array by design contains pointers to 472 // MDNodes rather than DIRefs. Unique them here. 473 DIType UniqueTy(resolve(Ty.getRef())); 474 CU.getOrCreateTypeDIE(UniqueTy); 475 } 476 DIArray RetainedTypes = CUNode.getRetainedTypes(); 477 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) { 478 DIType Ty(RetainedTypes.getElement(i)); 479 // The retained types array by design contains pointers to 480 // MDNodes rather than DIRefs. Unique them here. 481 DIType UniqueTy(resolve(Ty.getRef())); 482 CU.getOrCreateTypeDIE(UniqueTy); 483 } 484 // Emit imported_modules last so that the relevant context is already 485 // available. 486 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i) 487 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i)); 488 } 489 490 // Tell MMI that we have debug info. 491 MMI->setDebugInfoAvailability(true); 492 493 // Prime section data. 494 SectionMap[Asm->getObjFileLowering().getTextSection()]; 495 } 496 497 void DwarfDebug::finishVariableDefinitions() { 498 for (const auto &Var : ConcreteVariables) { 499 DIE *VariableDie = Var->getDIE(); 500 assert(VariableDie); 501 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 502 // in the ConcreteVariables list, rather than looking it up again here. 503 // DIE::getUnit isn't simple - it walks parent pointers, etc. 504 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit()); 505 assert(Unit); 506 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable()); 507 if (AbsVar && AbsVar->getDIE()) { 508 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin, 509 *AbsVar->getDIE()); 510 } else 511 Unit->applyVariableAttributes(*Var, *VariableDie); 512 } 513 } 514 515 void DwarfDebug::finishSubprogramDefinitions() { 516 for (const auto &P : SPMap) 517 P.second->finishSubprogramDefinition(DISubprogram(P.first)); 518 } 519 520 521 // Collect info for variables that were optimized out. 522 void DwarfDebug::collectDeadVariables() { 523 const Module *M = MMI->getModule(); 524 525 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) { 526 for (MDNode *N : CU_Nodes->operands()) { 527 DICompileUnit TheCU(N); 528 // Construct subprogram DIE and add variables DIEs. 529 DwarfCompileUnit *SPCU = 530 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU)); 531 assert(SPCU && "Unable to find Compile Unit!"); 532 DIArray Subprograms = TheCU.getSubprograms(); 533 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) { 534 DISubprogram SP(Subprograms.getElement(i)); 535 if (ProcessedSPNodes.count(SP) != 0) 536 continue; 537 assert(SP.isSubprogram() && 538 "CU's subprogram list contains a non-subprogram"); 539 assert(SP.isDefinition() && 540 "CU's subprogram list contains a subprogram declaration"); 541 DIArray Variables = SP.getVariables(); 542 if (Variables.getNumElements() == 0) 543 continue; 544 545 DIE *SPDIE = AbstractSPDies.lookup(SP); 546 if (!SPDIE) 547 SPDIE = SPCU->getDIE(SP); 548 assert(SPDIE); 549 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) { 550 DIVariable DV(Variables.getElement(vi)); 551 assert(DV.isVariable()); 552 DbgVariable NewVar(DV, DIExpression(nullptr), this); 553 auto VariableDie = SPCU->constructVariableDIE(NewVar); 554 SPCU->applyVariableAttributes(NewVar, *VariableDie); 555 SPDIE->addChild(std::move(VariableDie)); 556 } 557 } 558 } 559 } 560 } 561 562 void DwarfDebug::finalizeModuleInfo() { 563 finishSubprogramDefinitions(); 564 565 finishVariableDefinitions(); 566 567 // Collect info for variables that were optimized out. 568 collectDeadVariables(); 569 570 // Handle anything that needs to be done on a per-unit basis after 571 // all other generation. 572 for (const auto &TheU : getUnits()) { 573 // Emit DW_AT_containing_type attribute to connect types with their 574 // vtable holding type. 575 TheU->constructContainingTypeDIEs(); 576 577 // Add CU specific attributes if we need to add any. 578 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) { 579 // If we're splitting the dwarf out now that we've got the entire 580 // CU then add the dwo id to it. 581 DwarfCompileUnit *SkCU = 582 static_cast<DwarfCompileUnit *>(TheU->getSkeleton()); 583 if (useSplitDwarf()) { 584 // Emit a unique identifier for this CU. 585 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie()); 586 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 587 dwarf::DW_FORM_data8, ID); 588 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 589 dwarf::DW_FORM_data8, ID); 590 591 // We don't keep track of which addresses are used in which CU so this 592 // is a bit pessimistic under LTO. 593 if (!AddrPool.isEmpty()) 594 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base, 595 DwarfAddrSectionSym, DwarfAddrSectionSym); 596 if (!TheU->getRangeLists().empty()) 597 SkCU->addSectionLabel( 598 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 599 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym); 600 } 601 602 // If we have code split among multiple sections or non-contiguous 603 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 604 // remain in the .o file, otherwise add a DW_AT_low_pc. 605 // FIXME: We should use ranges allow reordering of code ala 606 // .subsections_via_symbols in mach-o. This would mean turning on 607 // ranges for all subprogram DIEs for mach-o. 608 DwarfCompileUnit &U = 609 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU); 610 unsigned NumRanges = TheU->getRanges().size(); 611 if (NumRanges) { 612 if (NumRanges > 1) { 613 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges, 614 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()), 615 DwarfDebugRangeSectionSym); 616 617 // A DW_AT_low_pc attribute may also be specified in combination with 618 // DW_AT_ranges to specify the default base address for use in 619 // location lists (see Section 2.6.2) and range lists (see Section 620 // 2.17.3). 621 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 622 0); 623 } else { 624 RangeSpan &Range = TheU->getRanges().back(); 625 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd()); 626 } 627 } 628 } 629 } 630 631 // Compute DIE offsets and sizes. 632 InfoHolder.computeSizeAndOffsets(); 633 if (useSplitDwarf()) 634 SkeletonHolder.computeSizeAndOffsets(); 635 } 636 637 void DwarfDebug::endSections() { 638 // Filter labels by section. 639 for (const SymbolCU &SCU : ArangeLabels) { 640 if (SCU.Sym->isInSection()) { 641 // Make a note of this symbol and it's section. 642 const MCSection *Section = &SCU.Sym->getSection(); 643 if (!Section->getKind().isMetadata()) 644 SectionMap[Section].push_back(SCU); 645 } else { 646 // Some symbols (e.g. common/bss on mach-o) can have no section but still 647 // appear in the output. This sucks as we rely on sections to build 648 // arange spans. We can do it without, but it's icky. 649 SectionMap[nullptr].push_back(SCU); 650 } 651 } 652 653 // Build a list of sections used. 654 std::vector<const MCSection *> Sections; 655 for (const auto &it : SectionMap) { 656 const MCSection *Section = it.first; 657 Sections.push_back(Section); 658 } 659 660 // Sort the sections into order. 661 // This is only done to ensure consistent output order across different runs. 662 std::sort(Sections.begin(), Sections.end(), SectionSort); 663 664 // Add terminating symbols for each section. 665 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) { 666 const MCSection *Section = Sections[ID]; 667 MCSymbol *Sym = nullptr; 668 669 if (Section) { 670 // We can't call MCSection::getLabelEndName, as it's only safe to do so 671 // if we know the section name up-front. For user-created sections, the 672 // resulting label may not be valid to use as a label. (section names can 673 // use a greater set of characters on some systems) 674 Sym = Asm->GetTempSymbol("debug_end", ID); 675 Asm->OutStreamer.SwitchSection(Section); 676 Asm->OutStreamer.EmitLabel(Sym); 677 } 678 679 // Insert a final terminator. 680 SectionMap[Section].push_back(SymbolCU(nullptr, Sym)); 681 } 682 } 683 684 // Emit all Dwarf sections that should come after the content. 685 void DwarfDebug::endModule() { 686 assert(CurFn == nullptr); 687 assert(CurMI == nullptr); 688 689 if (!FirstCU) 690 return; 691 692 // End any existing sections. 693 // TODO: Does this need to happen? 694 endSections(); 695 696 // Finalize the debug info for the module. 697 finalizeModuleInfo(); 698 699 emitDebugStr(); 700 701 // Emit all the DIEs into a debug info section. 702 emitDebugInfo(); 703 704 // Corresponding abbreviations into a abbrev section. 705 emitAbbreviations(); 706 707 // Emit info into a debug aranges section. 708 if (GenerateARangeSection) 709 emitDebugARanges(); 710 711 // Emit info into a debug ranges section. 712 emitDebugRanges(); 713 714 if (useSplitDwarf()) { 715 emitDebugStrDWO(); 716 emitDebugInfoDWO(); 717 emitDebugAbbrevDWO(); 718 emitDebugLineDWO(); 719 emitDebugLocDWO(); 720 // Emit DWO addresses. 721 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 722 } else 723 // Emit info into a debug loc section. 724 emitDebugLoc(); 725 726 // Emit info into the dwarf accelerator table sections. 727 if (useDwarfAccelTables()) { 728 emitAccelNames(); 729 emitAccelObjC(); 730 emitAccelNamespaces(); 731 emitAccelTypes(); 732 } 733 734 // Emit the pubnames and pubtypes sections if requested. 735 if (HasDwarfPubSections) { 736 emitDebugPubNames(GenerateGnuPubSections); 737 emitDebugPubTypes(GenerateGnuPubSections); 738 } 739 740 // clean up. 741 SPMap.clear(); 742 AbstractVariables.clear(); 743 744 // Reset these for the next Module if we have one. 745 FirstCU = nullptr; 746 } 747 748 // Find abstract variable, if any, associated with Var. 749 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV, 750 DIVariable &Cleansed) { 751 LLVMContext &Ctx = DV->getContext(); 752 // More then one inlined variable corresponds to one abstract variable. 753 // FIXME: This duplication of variables when inlining should probably be 754 // removed. It's done to allow each DIVariable to describe its location 755 // because the DebugLoc on the dbg.value/declare isn't accurate. We should 756 // make it accurate then remove this duplication/cleansing stuff. 757 Cleansed = cleanseInlinedVariable(DV, Ctx); 758 auto I = AbstractVariables.find(Cleansed); 759 if (I != AbstractVariables.end()) 760 return I->second.get(); 761 return nullptr; 762 } 763 764 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) { 765 DIVariable Cleansed; 766 return getExistingAbstractVariable(DV, Cleansed); 767 } 768 769 void DwarfDebug::createAbstractVariable(const DIVariable &Var, 770 LexicalScope *Scope) { 771 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this); 772 addScopeVariable(Scope, AbsDbgVariable.get()); 773 AbstractVariables[Var] = std::move(AbsDbgVariable); 774 } 775 776 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV, 777 const MDNode *ScopeNode) { 778 DIVariable Cleansed = DV; 779 if (getExistingAbstractVariable(DV, Cleansed)) 780 return; 781 782 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode)); 783 } 784 785 void 786 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV, 787 const MDNode *ScopeNode) { 788 DIVariable Cleansed = DV; 789 if (getExistingAbstractVariable(DV, Cleansed)) 790 return; 791 792 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode)) 793 createAbstractVariable(Cleansed, Scope); 794 } 795 796 // If Var is a current function argument then add it to CurrentFnArguments list. 797 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) { 798 if (!LScopes.isCurrentFunctionScope(Scope)) 799 return false; 800 DIVariable DV = Var->getVariable(); 801 if (DV.getTag() != dwarf::DW_TAG_arg_variable) 802 return false; 803 unsigned ArgNo = DV.getArgNumber(); 804 if (ArgNo == 0) 805 return false; 806 807 size_t Size = CurrentFnArguments.size(); 808 if (Size == 0) 809 CurrentFnArguments.resize(CurFn->getFunction()->arg_size()); 810 // llvm::Function argument size is not good indicator of how many 811 // arguments does the function have at source level. 812 if (ArgNo > Size) 813 CurrentFnArguments.resize(ArgNo * 2); 814 assert(!CurrentFnArguments[ArgNo - 1]); 815 CurrentFnArguments[ArgNo - 1] = Var; 816 return true; 817 } 818 819 // Collect variable information from side table maintained by MMI. 820 void DwarfDebug::collectVariableInfoFromMMITable( 821 SmallPtrSetImpl<const MDNode *> &Processed) { 822 for (const auto &VI : MMI->getVariableDbgInfo()) { 823 if (!VI.Var) 824 continue; 825 Processed.insert(VI.Var); 826 DIVariable DV(VI.Var); 827 DIExpression Expr(VI.Expr); 828 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 829 830 // If variable scope is not found then skip this variable. 831 if (!Scope) 832 continue; 833 834 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode()); 835 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this)); 836 DbgVariable *RegVar = ConcreteVariables.back().get(); 837 RegVar->setFrameIndex(VI.Slot); 838 addScopeVariable(Scope, RegVar); 839 } 840 } 841 842 // Get .debug_loc entry for the instruction range starting at MI. 843 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) { 844 const MDNode *Expr = MI->getDebugExpression(); 845 const MDNode *Var = MI->getDebugVariable(); 846 847 assert(MI->getNumOperands() == 4); 848 if (MI->getOperand(0).isReg()) { 849 MachineLocation MLoc; 850 // If the second operand is an immediate, this is a 851 // register-indirect address. 852 if (!MI->getOperand(1).isImm()) 853 MLoc.set(MI->getOperand(0).getReg()); 854 else 855 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm()); 856 return DebugLocEntry::Value(Var, Expr, MLoc); 857 } 858 if (MI->getOperand(0).isImm()) 859 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm()); 860 if (MI->getOperand(0).isFPImm()) 861 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm()); 862 if (MI->getOperand(0).isCImm()) 863 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm()); 864 865 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 866 } 867 868 /// Determine whether two variable pieces overlap. 869 static bool piecesOverlap(DIExpression P1, DIExpression P2) { 870 if (!P1.isVariablePiece() || !P2.isVariablePiece()) 871 return true; 872 unsigned l1 = P1.getPieceOffset(); 873 unsigned l2 = P2.getPieceOffset(); 874 unsigned r1 = l1 + P1.getPieceSize(); 875 unsigned r2 = l2 + P2.getPieceSize(); 876 // True where [l1,r1[ and [r1,r2[ overlap. 877 return (l1 < r2) && (l2 < r1); 878 } 879 880 /// Build the location list for all DBG_VALUEs in the function that 881 /// describe the same variable. If the ranges of several independent 882 /// pieces of the same variable overlap partially, split them up and 883 /// combine the ranges. The resulting DebugLocEntries are will have 884 /// strict monotonically increasing begin addresses and will never 885 /// overlap. 886 // 887 // Input: 888 // 889 // Ranges History [var, loc, piece ofs size] 890 // 0 | [x, (reg0, piece 0, 32)] 891 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry 892 // 2 | | ... 893 // 3 | [clobber reg0] 894 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x. 895 // 896 // Output: 897 // 898 // [0-1] [x, (reg0, piece 0, 32)] 899 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)] 900 // [3-4] [x, (reg1, piece 32, 32)] 901 // [4- ] [x, (mem, piece 0, 64)] 902 void 903 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 904 const DbgValueHistoryMap::InstrRanges &Ranges) { 905 SmallVector<DebugLocEntry::Value, 4> OpenRanges; 906 907 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 908 const MachineInstr *Begin = I->first; 909 const MachineInstr *End = I->second; 910 assert(Begin->isDebugValue() && "Invalid History entry"); 911 912 // Check if a variable is inaccessible in this range. 913 if (Begin->getNumOperands() > 1 && 914 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) { 915 OpenRanges.clear(); 916 continue; 917 } 918 919 // If this piece overlaps with any open ranges, truncate them. 920 DIExpression DIExpr = Begin->getDebugExpression(); 921 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(), 922 [&](DebugLocEntry::Value R) { 923 return piecesOverlap(DIExpr, R.getExpression()); 924 }); 925 OpenRanges.erase(Last, OpenRanges.end()); 926 927 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin); 928 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!"); 929 930 const MCSymbol *EndLabel; 931 if (End != nullptr) 932 EndLabel = getLabelAfterInsn(End); 933 else if (std::next(I) == Ranges.end()) 934 EndLabel = FunctionEndSym; 935 else 936 EndLabel = getLabelBeforeInsn(std::next(I)->first); 937 assert(EndLabel && "Forgot label after instruction ending a range!"); 938 939 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n"); 940 941 auto Value = getDebugLocValue(Begin); 942 DebugLocEntry Loc(StartLabel, EndLabel, Value); 943 bool couldMerge = false; 944 945 // If this is a piece, it may belong to the current DebugLocEntry. 946 if (DIExpr.isVariablePiece()) { 947 // Add this value to the list of open ranges. 948 OpenRanges.push_back(Value); 949 950 // Attempt to add the piece to the last entry. 951 if (!DebugLoc.empty()) 952 if (DebugLoc.back().MergeValues(Loc)) 953 couldMerge = true; 954 } 955 956 if (!couldMerge) { 957 // Need to add a new DebugLocEntry. Add all values from still 958 // valid non-overlapping pieces. 959 if (OpenRanges.size()) 960 Loc.addValues(OpenRanges); 961 962 DebugLoc.push_back(std::move(Loc)); 963 } 964 965 // Attempt to coalesce the ranges of two otherwise identical 966 // DebugLocEntries. 967 auto CurEntry = DebugLoc.rbegin(); 968 auto PrevEntry = std::next(CurEntry); 969 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 970 DebugLoc.pop_back(); 971 972 DEBUG({ 973 dbgs() << CurEntry->getValues().size() << " Values:\n"; 974 for (auto Value : CurEntry->getValues()) { 975 Value.getVariable()->dump(); 976 Value.getExpression()->dump(); 977 } 978 dbgs() << "-----\n"; 979 }); 980 } 981 } 982 983 984 // Find variables for each lexical scope. 985 void 986 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) { 987 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 988 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode()); 989 990 // Grab the variable info that was squirreled away in the MMI side-table. 991 collectVariableInfoFromMMITable(Processed); 992 993 for (const auto &I : DbgValues) { 994 DIVariable DV(I.first); 995 if (Processed.count(DV)) 996 continue; 997 998 // Instruction ranges, specifying where DV is accessible. 999 const auto &Ranges = I.second; 1000 if (Ranges.empty()) 1001 continue; 1002 1003 LexicalScope *Scope = nullptr; 1004 if (MDNode *IA = DV.getInlinedAt()) { 1005 DebugLoc DL = DebugLoc::getFromDILocation(IA); 1006 Scope = LScopes.findInlinedScope(DebugLoc::get( 1007 DL.getLine(), DL.getCol(), DV.getContext(), IA)); 1008 } else 1009 Scope = LScopes.findLexicalScope(DV.getContext()); 1010 // If variable scope is not found then skip this variable. 1011 if (!Scope) 1012 continue; 1013 1014 Processed.insert(DV); 1015 const MachineInstr *MInsn = Ranges.front().first; 1016 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1017 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode()); 1018 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this)); 1019 DbgVariable *RegVar = ConcreteVariables.back().get(); 1020 addScopeVariable(Scope, RegVar); 1021 1022 // Check if the first DBG_VALUE is valid for the rest of the function. 1023 if (Ranges.size() == 1 && Ranges.front().second == nullptr) 1024 continue; 1025 1026 // Handle multiple DBG_VALUE instructions describing one variable. 1027 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size()); 1028 1029 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1); 1030 DebugLocList &LocList = DotDebugLocEntries.back(); 1031 LocList.CU = TheCU; 1032 LocList.Label = 1033 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1); 1034 1035 // Build the location list for this variable. 1036 buildLocationList(LocList.List, Ranges); 1037 } 1038 1039 // Collect info for variables that were optimized out. 1040 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables(); 1041 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) { 1042 DIVariable DV(Variables.getElement(i)); 1043 assert(DV.isVariable()); 1044 if (!Processed.insert(DV)) 1045 continue; 1046 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) { 1047 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode()); 1048 DIExpression NoExpr; 1049 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this)); 1050 addScopeVariable(Scope, ConcreteVariables.back().get()); 1051 } 1052 } 1053 } 1054 1055 // Return Label preceding the instruction. 1056 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) { 1057 MCSymbol *Label = LabelsBeforeInsn.lookup(MI); 1058 assert(Label && "Didn't insert label before instruction"); 1059 return Label; 1060 } 1061 1062 // Return Label immediately following the instruction. 1063 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) { 1064 return LabelsAfterInsn.lookup(MI); 1065 } 1066 1067 // Process beginning of an instruction. 1068 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1069 assert(CurMI == nullptr); 1070 CurMI = MI; 1071 // Check if source location changes, but ignore DBG_VALUE locations. 1072 if (!MI->isDebugValue()) { 1073 DebugLoc DL = MI->getDebugLoc(); 1074 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) { 1075 unsigned Flags = 0; 1076 PrevInstLoc = DL; 1077 if (DL == PrologEndLoc) { 1078 Flags |= DWARF2_FLAG_PROLOGUE_END; 1079 PrologEndLoc = DebugLoc(); 1080 } 1081 if (PrologEndLoc.isUnknown()) 1082 Flags |= DWARF2_FLAG_IS_STMT; 1083 1084 if (!DL.isUnknown()) { 1085 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext()); 1086 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1087 } else 1088 recordSourceLine(0, 0, nullptr, 0); 1089 } 1090 } 1091 1092 // Insert labels where requested. 1093 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 1094 LabelsBeforeInsn.find(MI); 1095 1096 // No label needed. 1097 if (I == LabelsBeforeInsn.end()) 1098 return; 1099 1100 // Label already assigned. 1101 if (I->second) 1102 return; 1103 1104 if (!PrevLabel) { 1105 PrevLabel = MMI->getContext().CreateTempSymbol(); 1106 Asm->OutStreamer.EmitLabel(PrevLabel); 1107 } 1108 I->second = PrevLabel; 1109 } 1110 1111 // Process end of an instruction. 1112 void DwarfDebug::endInstruction() { 1113 assert(CurMI != nullptr); 1114 // Don't create a new label after DBG_VALUE instructions. 1115 // They don't generate code. 1116 if (!CurMI->isDebugValue()) 1117 PrevLabel = nullptr; 1118 1119 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 1120 LabelsAfterInsn.find(CurMI); 1121 CurMI = nullptr; 1122 1123 // No label needed. 1124 if (I == LabelsAfterInsn.end()) 1125 return; 1126 1127 // Label already assigned. 1128 if (I->second) 1129 return; 1130 1131 // We need a label after this instruction. 1132 if (!PrevLabel) { 1133 PrevLabel = MMI->getContext().CreateTempSymbol(); 1134 Asm->OutStreamer.EmitLabel(PrevLabel); 1135 } 1136 I->second = PrevLabel; 1137 } 1138 1139 // Each LexicalScope has first instruction and last instruction to mark 1140 // beginning and end of a scope respectively. Create an inverse map that list 1141 // scopes starts (and ends) with an instruction. One instruction may start (or 1142 // end) multiple scopes. Ignore scopes that are not reachable. 1143 void DwarfDebug::identifyScopeMarkers() { 1144 SmallVector<LexicalScope *, 4> WorkList; 1145 WorkList.push_back(LScopes.getCurrentFunctionScope()); 1146 while (!WorkList.empty()) { 1147 LexicalScope *S = WorkList.pop_back_val(); 1148 1149 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren(); 1150 if (!Children.empty()) 1151 WorkList.append(Children.begin(), Children.end()); 1152 1153 if (S->isAbstractScope()) 1154 continue; 1155 1156 for (const InsnRange &R : S->getRanges()) { 1157 assert(R.first && "InsnRange does not have first instruction!"); 1158 assert(R.second && "InsnRange does not have second instruction!"); 1159 requestLabelBeforeInsn(R.first); 1160 requestLabelAfterInsn(R.second); 1161 } 1162 } 1163 } 1164 1165 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1166 // First known non-DBG_VALUE and non-frame setup location marks 1167 // the beginning of the function body. 1168 for (const auto &MBB : *MF) 1169 for (const auto &MI : MBB) 1170 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 1171 !MI.getDebugLoc().isUnknown()) 1172 return MI.getDebugLoc(); 1173 return DebugLoc(); 1174 } 1175 1176 // Gather pre-function debug information. Assumes being called immediately 1177 // after the function entry point has been emitted. 1178 void DwarfDebug::beginFunction(const MachineFunction *MF) { 1179 CurFn = MF; 1180 1181 // If there's no debug info for the function we're not going to do anything. 1182 if (!MMI->hasDebugInfo()) 1183 return; 1184 1185 auto DI = FunctionDIs.find(MF->getFunction()); 1186 if (DI == FunctionDIs.end()) 1187 return; 1188 1189 // Grab the lexical scopes for the function, if we don't have any of those 1190 // then we're not going to be able to do anything. 1191 LScopes.initialize(*MF); 1192 if (LScopes.empty()) 1193 return; 1194 1195 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!"); 1196 1197 // Make sure that each lexical scope will have a begin/end label. 1198 identifyScopeMarkers(); 1199 1200 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1201 // belongs to so that we add to the correct per-cu line table in the 1202 // non-asm case. 1203 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1204 // FnScope->getScopeNode() and DI->second should represent the same function, 1205 // though they may not be the same MDNode due to inline functions merged in 1206 // LTO where the debug info metadata still differs (either due to distinct 1207 // written differences - two versions of a linkonce_odr function 1208 // written/copied into two separate files, or some sub-optimal metadata that 1209 // isn't structurally identical (see: file path/name info from clang, which 1210 // includes the directory of the cpp file being built, even when the file name 1211 // is absolute (such as an <> lookup header))) 1212 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode()); 1213 assert(TheCU && "Unable to find compile unit!"); 1214 if (Asm->OutStreamer.hasRawTextSupport()) 1215 // Use a single line table if we are generating assembly. 1216 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0); 1217 else 1218 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID()); 1219 1220 // Emit a label for the function so that we have a beginning address. 1221 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()); 1222 // Assumes in correct section after the entry point. 1223 Asm->OutStreamer.EmitLabel(FunctionBeginSym); 1224 1225 // Calculate history for local variables. 1226 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(), 1227 DbgValues); 1228 1229 // Request labels for the full history. 1230 for (const auto &I : DbgValues) { 1231 const auto &Ranges = I.second; 1232 if (Ranges.empty()) 1233 continue; 1234 1235 // The first mention of a function argument gets the FunctionBeginSym 1236 // label, so arguments are visible when breaking at function entry. 1237 DIVariable DIVar(Ranges.front().first->getDebugVariable()); 1238 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable && 1239 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) { 1240 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym; 1241 if (Ranges.front().first->getDebugExpression().isVariablePiece()) { 1242 // Mark all non-overlapping initial pieces. 1243 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) { 1244 DIExpression Piece = I->first->getDebugExpression(); 1245 if (std::all_of(Ranges.begin(), I, 1246 [&](DbgValueHistoryMap::InstrRange Pred) { 1247 return !piecesOverlap(Piece, Pred.first->getDebugExpression()); 1248 })) 1249 LabelsBeforeInsn[I->first] = FunctionBeginSym; 1250 else 1251 break; 1252 } 1253 } 1254 } 1255 1256 for (const auto &Range : Ranges) { 1257 requestLabelBeforeInsn(Range.first); 1258 if (Range.second) 1259 requestLabelAfterInsn(Range.second); 1260 } 1261 } 1262 1263 PrevInstLoc = DebugLoc(); 1264 PrevLabel = FunctionBeginSym; 1265 1266 // Record beginning of function. 1267 PrologEndLoc = findPrologueEndLoc(MF); 1268 if (!PrologEndLoc.isUnknown()) { 1269 DebugLoc FnStartDL = 1270 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext()); 1271 recordSourceLine( 1272 FnStartDL.getLine(), FnStartDL.getCol(), 1273 FnStartDL.getScope(MF->getFunction()->getContext()), 1274 // We'd like to list the prologue as "not statements" but GDB behaves 1275 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1276 DWARF2_FLAG_IS_STMT); 1277 } 1278 } 1279 1280 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) { 1281 if (addCurrentFnArgument(Var, LS)) 1282 return; 1283 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS]; 1284 DIVariable DV = Var->getVariable(); 1285 // Variables with positive arg numbers are parameters. 1286 if (unsigned ArgNum = DV.getArgNumber()) { 1287 // Keep all parameters in order at the start of the variable list to ensure 1288 // function types are correct (no out-of-order parameters) 1289 // 1290 // This could be improved by only doing it for optimized builds (unoptimized 1291 // builds have the right order to begin with), searching from the back (this 1292 // would catch the unoptimized case quickly), or doing a binary search 1293 // rather than linear search. 1294 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin(); 1295 while (I != Vars.end()) { 1296 unsigned CurNum = (*I)->getVariable().getArgNumber(); 1297 // A local (non-parameter) variable has been found, insert immediately 1298 // before it. 1299 if (CurNum == 0) 1300 break; 1301 // A later indexed parameter has been found, insert immediately before it. 1302 if (CurNum > ArgNum) 1303 break; 1304 ++I; 1305 } 1306 Vars.insert(I, Var); 1307 return; 1308 } 1309 1310 Vars.push_back(Var); 1311 } 1312 1313 // Gather and emit post-function debug information. 1314 void DwarfDebug::endFunction(const MachineFunction *MF) { 1315 assert(CurFn == MF && 1316 "endFunction should be called with the same function as beginFunction"); 1317 1318 if (!MMI->hasDebugInfo() || LScopes.empty() || 1319 !FunctionDIs.count(MF->getFunction())) { 1320 // If we don't have a lexical scope for this function then there will 1321 // be a hole in the range information. Keep note of this by setting the 1322 // previously used section to nullptr. 1323 PrevCU = nullptr; 1324 CurFn = nullptr; 1325 return; 1326 } 1327 1328 // Define end label for subprogram. 1329 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()); 1330 // Assumes in correct section after the entry point. 1331 Asm->OutStreamer.EmitLabel(FunctionEndSym); 1332 1333 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1334 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0); 1335 1336 SmallPtrSet<const MDNode *, 16> ProcessedVars; 1337 collectVariableInfo(ProcessedVars); 1338 1339 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1340 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode()); 1341 1342 // Add the range of this function to the list of ranges for the CU. 1343 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym)); 1344 1345 // Under -gmlt, skip building the subprogram if there are no inlined 1346 // subroutines inside it. 1347 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly && 1348 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1349 assert(ScopeVariables.empty()); 1350 assert(CurrentFnArguments.empty()); 1351 assert(DbgValues.empty()); 1352 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed 1353 // by a -gmlt CU. Add a test and remove this assertion. 1354 assert(AbstractVariables.empty()); 1355 LabelsBeforeInsn.clear(); 1356 LabelsAfterInsn.clear(); 1357 PrevLabel = nullptr; 1358 CurFn = nullptr; 1359 return; 1360 } 1361 1362 #ifndef NDEBUG 1363 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1364 #endif 1365 // Construct abstract scopes. 1366 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1367 DISubprogram SP(AScope->getScopeNode()); 1368 assert(SP.isSubprogram()); 1369 // Collect info for variables that were optimized out. 1370 DIArray Variables = SP.getVariables(); 1371 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) { 1372 DIVariable DV(Variables.getElement(i)); 1373 assert(DV && DV.isVariable()); 1374 if (!ProcessedVars.insert(DV)) 1375 continue; 1376 ensureAbstractVariableIsCreated(DV, DV.getContext()); 1377 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1378 && "ensureAbstractVariableIsCreated inserted abstract scopes"); 1379 } 1380 constructAbstractSubprogramScopeDIE(AScope); 1381 } 1382 1383 TheCU.constructSubprogramScopeDIE(FnScope); 1384 1385 // Clear debug info 1386 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1387 // DbgVariables except those that are also in AbstractVariables (since they 1388 // can be used cross-function) 1389 ScopeVariables.clear(); 1390 CurrentFnArguments.clear(); 1391 DbgValues.clear(); 1392 LabelsBeforeInsn.clear(); 1393 LabelsAfterInsn.clear(); 1394 PrevLabel = nullptr; 1395 CurFn = nullptr; 1396 } 1397 1398 // Register a source line with debug info. Returns the unique label that was 1399 // emitted and which provides correspondence to the source line list. 1400 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1401 unsigned Flags) { 1402 StringRef Fn; 1403 StringRef Dir; 1404 unsigned Src = 1; 1405 unsigned Discriminator = 0; 1406 if (DIScope Scope = DIScope(S)) { 1407 assert(Scope.isScope()); 1408 Fn = Scope.getFilename(); 1409 Dir = Scope.getDirectory(); 1410 if (Scope.isLexicalBlockFile()) 1411 Discriminator = DILexicalBlockFile(S).getDiscriminator(); 1412 1413 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID(); 1414 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID]) 1415 .getOrCreateSourceID(Fn, Dir); 1416 } 1417 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 1418 Discriminator, Fn); 1419 } 1420 1421 //===----------------------------------------------------------------------===// 1422 // Emit Methods 1423 //===----------------------------------------------------------------------===// 1424 1425 // Emit initial Dwarf sections with a label at the start of each one. 1426 void DwarfDebug::emitSectionLabels() { 1427 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1428 1429 // Dwarf sections base addresses. 1430 DwarfInfoSectionSym = 1431 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info"); 1432 if (useSplitDwarf()) { 1433 DwarfInfoDWOSectionSym = 1434 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo"); 1435 DwarfTypesDWOSectionSym = 1436 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo"); 1437 } 1438 DwarfAbbrevSectionSym = 1439 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev"); 1440 if (useSplitDwarf()) 1441 DwarfAbbrevDWOSectionSym = emitSectionSym( 1442 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo"); 1443 if (GenerateARangeSection) 1444 emitSectionSym(Asm, TLOF.getDwarfARangesSection()); 1445 1446 DwarfLineSectionSym = 1447 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line"); 1448 if (GenerateGnuPubSections) { 1449 DwarfGnuPubNamesSectionSym = 1450 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection()); 1451 DwarfGnuPubTypesSectionSym = 1452 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection()); 1453 } else if (HasDwarfPubSections) { 1454 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection()); 1455 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection()); 1456 } 1457 1458 DwarfStrSectionSym = 1459 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string"); 1460 if (useSplitDwarf()) { 1461 DwarfStrDWOSectionSym = 1462 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string"); 1463 DwarfAddrSectionSym = 1464 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec"); 1465 DwarfDebugLocSectionSym = 1466 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc"); 1467 } else 1468 DwarfDebugLocSectionSym = 1469 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc"); 1470 DwarfDebugRangeSectionSym = 1471 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range"); 1472 } 1473 1474 // Recursively emits a debug information entry. 1475 void DwarfDebug::emitDIE(DIE &Die) { 1476 // Get the abbreviation for this DIE. 1477 const DIEAbbrev &Abbrev = Die.getAbbrev(); 1478 1479 // Emit the code (index) for the abbreviation. 1480 if (Asm->isVerbose()) 1481 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) + 1482 "] 0x" + Twine::utohexstr(Die.getOffset()) + 1483 ":0x" + Twine::utohexstr(Die.getSize()) + " " + 1484 dwarf::TagString(Abbrev.getTag())); 1485 Asm->EmitULEB128(Abbrev.getNumber()); 1486 1487 const SmallVectorImpl<DIEValue *> &Values = Die.getValues(); 1488 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData(); 1489 1490 // Emit the DIE attribute values. 1491 for (unsigned i = 0, N = Values.size(); i < N; ++i) { 1492 dwarf::Attribute Attr = AbbrevData[i].getAttribute(); 1493 dwarf::Form Form = AbbrevData[i].getForm(); 1494 assert(Form && "Too many attributes for DIE (check abbreviation)"); 1495 1496 if (Asm->isVerbose()) { 1497 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr)); 1498 if (Attr == dwarf::DW_AT_accessibility) 1499 Asm->OutStreamer.AddComment(dwarf::AccessibilityString( 1500 cast<DIEInteger>(Values[i])->getValue())); 1501 } 1502 1503 // Emit an attribute using the defined form. 1504 Values[i]->EmitValue(Asm, Form); 1505 } 1506 1507 // Emit the DIE children if any. 1508 if (Abbrev.hasChildren()) { 1509 for (auto &Child : Die.getChildren()) 1510 emitDIE(*Child); 1511 1512 Asm->OutStreamer.AddComment("End Of Children Mark"); 1513 Asm->EmitInt8(0); 1514 } 1515 } 1516 1517 // Emit the debug info section. 1518 void DwarfDebug::emitDebugInfo() { 1519 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1520 1521 Holder.emitUnits(this, DwarfAbbrevSectionSym); 1522 } 1523 1524 // Emit the abbreviation section. 1525 void DwarfDebug::emitAbbreviations() { 1526 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1527 1528 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1529 } 1530 1531 // Emit the last address of the section and the end of the line matrix. 1532 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) { 1533 // Define last address of section. 1534 Asm->OutStreamer.AddComment("Extended Op"); 1535 Asm->EmitInt8(0); 1536 1537 Asm->OutStreamer.AddComment("Op size"); 1538 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1); 1539 Asm->OutStreamer.AddComment("DW_LNE_set_address"); 1540 Asm->EmitInt8(dwarf::DW_LNE_set_address); 1541 1542 Asm->OutStreamer.AddComment("Section end label"); 1543 1544 Asm->OutStreamer.EmitSymbolValue( 1545 Asm->GetTempSymbol("section_end", SectionEnd), 1546 Asm->getDataLayout().getPointerSize()); 1547 1548 // Mark end of matrix. 1549 Asm->OutStreamer.AddComment("DW_LNE_end_sequence"); 1550 Asm->EmitInt8(0); 1551 Asm->EmitInt8(1); 1552 Asm->EmitInt8(1); 1553 } 1554 1555 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section, 1556 StringRef TableName, StringRef SymName) { 1557 Accel.FinalizeTable(Asm, TableName); 1558 Asm->OutStreamer.SwitchSection(Section); 1559 auto *SectionBegin = Asm->GetTempSymbol(SymName); 1560 Asm->OutStreamer.EmitLabel(SectionBegin); 1561 1562 // Emit the full data. 1563 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym); 1564 } 1565 1566 // Emit visible names into a hashed accelerator table section. 1567 void DwarfDebug::emitAccelNames() { 1568 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1569 "Names", "names_begin"); 1570 } 1571 1572 // Emit objective C classes and categories into a hashed accelerator table 1573 // section. 1574 void DwarfDebug::emitAccelObjC() { 1575 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1576 "ObjC", "objc_begin"); 1577 } 1578 1579 // Emit namespace dies into a hashed accelerator table. 1580 void DwarfDebug::emitAccelNamespaces() { 1581 emitAccel(AccelNamespace, 1582 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1583 "namespac", "namespac_begin"); 1584 } 1585 1586 // Emit type dies into a hashed accelerator table. 1587 void DwarfDebug::emitAccelTypes() { 1588 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1589 "types", "types_begin"); 1590 } 1591 1592 // Public name handling. 1593 // The format for the various pubnames: 1594 // 1595 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1596 // for the DIE that is named. 1597 // 1598 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1599 // into the CU and the index value is computed according to the type of value 1600 // for the DIE that is named. 1601 // 1602 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1603 // it's the offset within the debug_info/debug_types dwo section, however, the 1604 // reference in the pubname header doesn't change. 1605 1606 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1607 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1608 const DIE *Die) { 1609 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1610 1611 // We could have a specification DIE that has our most of our knowledge, 1612 // look for that now. 1613 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification); 1614 if (SpecVal) { 1615 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry(); 1616 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1617 Linkage = dwarf::GIEL_EXTERNAL; 1618 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1619 Linkage = dwarf::GIEL_EXTERNAL; 1620 1621 switch (Die->getTag()) { 1622 case dwarf::DW_TAG_class_type: 1623 case dwarf::DW_TAG_structure_type: 1624 case dwarf::DW_TAG_union_type: 1625 case dwarf::DW_TAG_enumeration_type: 1626 return dwarf::PubIndexEntryDescriptor( 1627 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1628 ? dwarf::GIEL_STATIC 1629 : dwarf::GIEL_EXTERNAL); 1630 case dwarf::DW_TAG_typedef: 1631 case dwarf::DW_TAG_base_type: 1632 case dwarf::DW_TAG_subrange_type: 1633 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1634 case dwarf::DW_TAG_namespace: 1635 return dwarf::GIEK_TYPE; 1636 case dwarf::DW_TAG_subprogram: 1637 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1638 case dwarf::DW_TAG_constant: 1639 case dwarf::DW_TAG_variable: 1640 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1641 case dwarf::DW_TAG_enumerator: 1642 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1643 dwarf::GIEL_STATIC); 1644 default: 1645 return dwarf::GIEK_NONE; 1646 } 1647 } 1648 1649 /// emitDebugPubNames - Emit visible names into a debug pubnames section. 1650 /// 1651 void DwarfDebug::emitDebugPubNames(bool GnuStyle) { 1652 const MCSection *PSec = 1653 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1654 : Asm->getObjFileLowering().getDwarfPubNamesSection(); 1655 1656 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames); 1657 } 1658 1659 void DwarfDebug::emitDebugPubSection( 1660 bool GnuStyle, const MCSection *PSec, StringRef Name, 1661 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) { 1662 for (const auto &NU : CUMap) { 1663 DwarfCompileUnit *TheU = NU.second; 1664 1665 const auto &Globals = (TheU->*Accessor)(); 1666 1667 if (Globals.empty()) 1668 continue; 1669 1670 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton())) 1671 TheU = Skeleton; 1672 unsigned ID = TheU->getUniqueID(); 1673 1674 // Start the dwarf pubnames section. 1675 Asm->OutStreamer.SwitchSection(PSec); 1676 1677 // Emit the header. 1678 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info"); 1679 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID); 1680 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID); 1681 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1682 1683 Asm->OutStreamer.EmitLabel(BeginLabel); 1684 1685 Asm->OutStreamer.AddComment("DWARF Version"); 1686 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); 1687 1688 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info"); 1689 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym()); 1690 1691 Asm->OutStreamer.AddComment("Compilation Unit Length"); 1692 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4); 1693 1694 // Emit the pubnames for this compilation unit. 1695 for (const auto &GI : Globals) { 1696 const char *Name = GI.getKeyData(); 1697 const DIE *Entity = GI.second; 1698 1699 Asm->OutStreamer.AddComment("DIE offset"); 1700 Asm->EmitInt32(Entity->getOffset()); 1701 1702 if (GnuStyle) { 1703 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1704 Asm->OutStreamer.AddComment( 1705 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " + 1706 dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1707 Asm->EmitInt8(Desc.toBits()); 1708 } 1709 1710 Asm->OutStreamer.AddComment("External Name"); 1711 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1712 } 1713 1714 Asm->OutStreamer.AddComment("End Mark"); 1715 Asm->EmitInt32(0); 1716 Asm->OutStreamer.EmitLabel(EndLabel); 1717 } 1718 } 1719 1720 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) { 1721 const MCSection *PSec = 1722 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1723 : Asm->getObjFileLowering().getDwarfPubTypesSection(); 1724 1725 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes); 1726 } 1727 1728 // Emit visible names into a debug str section. 1729 void DwarfDebug::emitDebugStr() { 1730 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1731 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection()); 1732 } 1733 1734 /// Emits an optimal (=sorted) sequence of DW_OP_pieces. 1735 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer, 1736 const DITypeIdentifierMap &Map, 1737 ArrayRef<DebugLocEntry::Value> Values) { 1738 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) { 1739 return P.isVariablePiece(); 1740 }) && "all values are expected to be pieces"); 1741 assert(std::is_sorted(Values.begin(), Values.end()) && 1742 "pieces are expected to be sorted"); 1743 1744 unsigned Offset = 0; 1745 for (auto Piece : Values) { 1746 DIExpression Expr = Piece.getExpression(); 1747 unsigned PieceOffset = Expr.getPieceOffset(); 1748 unsigned PieceSize = Expr.getPieceSize(); 1749 assert(Offset <= PieceOffset && "overlapping or duplicate pieces"); 1750 if (Offset < PieceOffset) { 1751 // The DWARF spec seriously mandates pieces with no locations for gaps. 1752 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8); 1753 Offset += PieceOffset-Offset; 1754 } 1755 1756 Offset += PieceSize; 1757 1758 const unsigned SizeOfByte = 8; 1759 #ifndef NDEBUG 1760 DIVariable Var = Piece.getVariable(); 1761 assert(!Var.isIndirect() && "indirect address for piece"); 1762 unsigned VarSize = Var.getSizeInBits(Map); 1763 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte 1764 && "piece is larger than or outside of variable"); 1765 assert(PieceSize*SizeOfByte != VarSize 1766 && "piece covers entire variable"); 1767 #endif 1768 if (Piece.isLocation() && Piece.getLoc().isReg()) 1769 Asm->EmitDwarfRegOpPiece(Streamer, 1770 Piece.getLoc(), 1771 PieceSize*SizeOfByte); 1772 else { 1773 emitDebugLocValue(Streamer, Piece); 1774 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte); 1775 } 1776 } 1777 } 1778 1779 1780 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1781 const DebugLocEntry &Entry) { 1782 const DebugLocEntry::Value Value = Entry.getValues()[0]; 1783 if (Value.isVariablePiece()) 1784 // Emit all pieces that belong to the same variable and range. 1785 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues()); 1786 1787 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value"); 1788 emitDebugLocValue(Streamer, Value); 1789 } 1790 1791 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer, 1792 const DebugLocEntry::Value &Value) { 1793 DIVariable DV = Value.getVariable(); 1794 // Regular entry. 1795 if (Value.isInt()) { 1796 DIBasicType BTy(resolve(DV.getType())); 1797 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed || 1798 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) { 1799 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts"); 1800 Streamer.EmitSLEB128(Value.getInt()); 1801 } else { 1802 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu"); 1803 Streamer.EmitULEB128(Value.getInt()); 1804 } 1805 } else if (Value.isLocation()) { 1806 MachineLocation Loc = Value.getLoc(); 1807 DIExpression Expr = Value.getExpression(); 1808 if (!Expr) 1809 // Regular entry. 1810 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect()); 1811 else { 1812 // Complex address entry. 1813 unsigned N = Expr.getNumElements(); 1814 unsigned i = 0; 1815 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) { 1816 if (Loc.getOffset()) { 1817 i = 2; 1818 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect()); 1819 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref"); 1820 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst"); 1821 Streamer.EmitSLEB128(Expr.getElement(1)); 1822 } else { 1823 // If first address element is OpPlus then emit 1824 // DW_OP_breg + Offset instead of DW_OP_reg + Offset. 1825 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1)); 1826 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect()); 1827 i = 2; 1828 } 1829 } else { 1830 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect()); 1831 } 1832 1833 // Emit remaining complex address elements. 1834 for (; i < N; ++i) { 1835 uint64_t Element = Expr.getElement(i); 1836 if (Element == dwarf::DW_OP_plus) { 1837 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst"); 1838 Streamer.EmitULEB128(Expr.getElement(++i)); 1839 } else if (Element == dwarf::DW_OP_deref) { 1840 if (!Loc.isReg()) 1841 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref"); 1842 } else if (Element == dwarf::DW_OP_piece) { 1843 i += 3; 1844 // handled in emitDebugLocEntry. 1845 } else 1846 llvm_unreachable("unknown Opcode found in complex address"); 1847 } 1848 } 1849 } 1850 // else ... ignore constant fp. There is not any good way to 1851 // to represent them here in dwarf. 1852 // FIXME: ^ 1853 } 1854 1855 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) { 1856 Asm->OutStreamer.AddComment("Loc expr size"); 1857 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol(); 1858 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol(); 1859 Asm->EmitLabelDifference(end, begin, 2); 1860 Asm->OutStreamer.EmitLabel(begin); 1861 // Emit the entry. 1862 APByteStreamer Streamer(*Asm); 1863 emitDebugLocEntry(Streamer, Entry); 1864 // Close the range. 1865 Asm->OutStreamer.EmitLabel(end); 1866 } 1867 1868 // Emit locations into the debug loc section. 1869 void DwarfDebug::emitDebugLoc() { 1870 // Start the dwarf loc section. 1871 Asm->OutStreamer.SwitchSection( 1872 Asm->getObjFileLowering().getDwarfLocSection()); 1873 unsigned char Size = Asm->getDataLayout().getPointerSize(); 1874 for (const auto &DebugLoc : DotDebugLocEntries) { 1875 Asm->OutStreamer.EmitLabel(DebugLoc.Label); 1876 const DwarfCompileUnit *CU = DebugLoc.CU; 1877 assert(!CU->getRanges().empty()); 1878 for (const auto &Entry : DebugLoc.List) { 1879 // Set up the range. This range is relative to the entry point of the 1880 // compile unit. This is a hard coded 0 for low_pc when we're emitting 1881 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 1882 if (CU->getRanges().size() == 1) { 1883 // Grab the begin symbol from the first range as our base. 1884 const MCSymbol *Base = CU->getRanges()[0].getStart(); 1885 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size); 1886 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size); 1887 } else { 1888 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size); 1889 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size); 1890 } 1891 1892 emitDebugLocEntryLocation(Entry); 1893 } 1894 Asm->OutStreamer.EmitIntValue(0, Size); 1895 Asm->OutStreamer.EmitIntValue(0, Size); 1896 } 1897 } 1898 1899 void DwarfDebug::emitDebugLocDWO() { 1900 Asm->OutStreamer.SwitchSection( 1901 Asm->getObjFileLowering().getDwarfLocDWOSection()); 1902 for (const auto &DebugLoc : DotDebugLocEntries) { 1903 Asm->OutStreamer.EmitLabel(DebugLoc.Label); 1904 for (const auto &Entry : DebugLoc.List) { 1905 // Just always use start_length for now - at least that's one address 1906 // rather than two. We could get fancier and try to, say, reuse an 1907 // address we know we've emitted elsewhere (the start of the function? 1908 // The start of the CU or CU subrange that encloses this range?) 1909 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry); 1910 unsigned idx = AddrPool.getIndex(Entry.getBeginSym()); 1911 Asm->EmitULEB128(idx); 1912 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4); 1913 1914 emitDebugLocEntryLocation(Entry); 1915 } 1916 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry); 1917 } 1918 } 1919 1920 struct ArangeSpan { 1921 const MCSymbol *Start, *End; 1922 }; 1923 1924 // Emit a debug aranges section, containing a CU lookup for any 1925 // address we can tie back to a CU. 1926 void DwarfDebug::emitDebugARanges() { 1927 // Start the dwarf aranges section. 1928 Asm->OutStreamer.SwitchSection( 1929 Asm->getObjFileLowering().getDwarfARangesSection()); 1930 1931 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType; 1932 1933 SpansType Spans; 1934 1935 // Build a list of sections used. 1936 std::vector<const MCSection *> Sections; 1937 for (const auto &it : SectionMap) { 1938 const MCSection *Section = it.first; 1939 Sections.push_back(Section); 1940 } 1941 1942 // Sort the sections into order. 1943 // This is only done to ensure consistent output order across different runs. 1944 std::sort(Sections.begin(), Sections.end(), SectionSort); 1945 1946 // Build a set of address spans, sorted by CU. 1947 for (const MCSection *Section : Sections) { 1948 SmallVector<SymbolCU, 8> &List = SectionMap[Section]; 1949 if (List.size() < 2) 1950 continue; 1951 1952 // Sort the symbols by offset within the section. 1953 std::sort(List.begin(), List.end(), 1954 [&](const SymbolCU &A, const SymbolCU &B) { 1955 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0; 1956 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0; 1957 1958 // Symbols with no order assigned should be placed at the end. 1959 // (e.g. section end labels) 1960 if (IA == 0) 1961 return false; 1962 if (IB == 0) 1963 return true; 1964 return IA < IB; 1965 }); 1966 1967 // If we have no section (e.g. common), just write out 1968 // individual spans for each symbol. 1969 if (!Section) { 1970 for (const SymbolCU &Cur : List) { 1971 ArangeSpan Span; 1972 Span.Start = Cur.Sym; 1973 Span.End = nullptr; 1974 if (Cur.CU) 1975 Spans[Cur.CU].push_back(Span); 1976 } 1977 } else { 1978 // Build spans between each label. 1979 const MCSymbol *StartSym = List[0].Sym; 1980 for (size_t n = 1, e = List.size(); n < e; n++) { 1981 const SymbolCU &Prev = List[n - 1]; 1982 const SymbolCU &Cur = List[n]; 1983 1984 // Try and build the longest span we can within the same CU. 1985 if (Cur.CU != Prev.CU) { 1986 ArangeSpan Span; 1987 Span.Start = StartSym; 1988 Span.End = Cur.Sym; 1989 Spans[Prev.CU].push_back(Span); 1990 StartSym = Cur.Sym; 1991 } 1992 } 1993 } 1994 } 1995 1996 unsigned PtrSize = Asm->getDataLayout().getPointerSize(); 1997 1998 // Build a list of CUs used. 1999 std::vector<DwarfCompileUnit *> CUs; 2000 for (const auto &it : Spans) { 2001 DwarfCompileUnit *CU = it.first; 2002 CUs.push_back(CU); 2003 } 2004 2005 // Sort the CU list (again, to ensure consistent output order). 2006 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) { 2007 return A->getUniqueID() < B->getUniqueID(); 2008 }); 2009 2010 // Emit an arange table for each CU we used. 2011 for (DwarfCompileUnit *CU : CUs) { 2012 std::vector<ArangeSpan> &List = Spans[CU]; 2013 2014 // Emit size of content not including length itself. 2015 unsigned ContentSize = 2016 sizeof(int16_t) + // DWARF ARange version number 2017 sizeof(int32_t) + // Offset of CU in the .debug_info section 2018 sizeof(int8_t) + // Pointer Size (in bytes) 2019 sizeof(int8_t); // Segment Size (in bytes) 2020 2021 unsigned TupleSize = PtrSize * 2; 2022 2023 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2024 unsigned Padding = 2025 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2026 2027 ContentSize += Padding; 2028 ContentSize += (List.size() + 1) * TupleSize; 2029 2030 // For each compile unit, write the list of spans it covers. 2031 Asm->OutStreamer.AddComment("Length of ARange Set"); 2032 Asm->EmitInt32(ContentSize); 2033 Asm->OutStreamer.AddComment("DWARF Arange version number"); 2034 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); 2035 Asm->OutStreamer.AddComment("Offset Into Debug Info Section"); 2036 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym()); 2037 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 2038 Asm->EmitInt8(PtrSize); 2039 Asm->OutStreamer.AddComment("Segment Size (in bytes)"); 2040 Asm->EmitInt8(0); 2041 2042 Asm->OutStreamer.EmitFill(Padding, 0xff); 2043 2044 for (const ArangeSpan &Span : List) { 2045 Asm->EmitLabelReference(Span.Start, PtrSize); 2046 2047 // Calculate the size as being from the span start to it's end. 2048 if (Span.End) { 2049 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2050 } else { 2051 // For symbols without an end marker (e.g. common), we 2052 // write a single arange entry containing just that one symbol. 2053 uint64_t Size = SymSize[Span.Start]; 2054 if (Size == 0) 2055 Size = 1; 2056 2057 Asm->OutStreamer.EmitIntValue(Size, PtrSize); 2058 } 2059 } 2060 2061 Asm->OutStreamer.AddComment("ARange terminator"); 2062 Asm->OutStreamer.EmitIntValue(0, PtrSize); 2063 Asm->OutStreamer.EmitIntValue(0, PtrSize); 2064 } 2065 } 2066 2067 // Emit visible names into a debug ranges section. 2068 void DwarfDebug::emitDebugRanges() { 2069 // Start the dwarf ranges section. 2070 Asm->OutStreamer.SwitchSection( 2071 Asm->getObjFileLowering().getDwarfRangesSection()); 2072 2073 // Size for our labels. 2074 unsigned char Size = Asm->getDataLayout().getPointerSize(); 2075 2076 // Grab the specific ranges for the compile units in the module. 2077 for (const auto &I : CUMap) { 2078 DwarfCompileUnit *TheCU = I.second; 2079 2080 // Iterate over the misc ranges for the compile units in the module. 2081 for (const RangeSpanList &List : TheCU->getRangeLists()) { 2082 // Emit our symbol so we can find the beginning of the range. 2083 Asm->OutStreamer.EmitLabel(List.getSym()); 2084 2085 for (const RangeSpan &Range : List.getRanges()) { 2086 const MCSymbol *Begin = Range.getStart(); 2087 const MCSymbol *End = Range.getEnd(); 2088 assert(Begin && "Range without a begin symbol?"); 2089 assert(End && "Range without an end symbol?"); 2090 if (TheCU->getRanges().size() == 1) { 2091 // Grab the begin symbol from the first range as our base. 2092 const MCSymbol *Base = TheCU->getRanges()[0].getStart(); 2093 Asm->EmitLabelDifference(Begin, Base, Size); 2094 Asm->EmitLabelDifference(End, Base, Size); 2095 } else { 2096 Asm->OutStreamer.EmitSymbolValue(Begin, Size); 2097 Asm->OutStreamer.EmitSymbolValue(End, Size); 2098 } 2099 } 2100 2101 // And terminate the list with two 0 values. 2102 Asm->OutStreamer.EmitIntValue(0, Size); 2103 Asm->OutStreamer.EmitIntValue(0, Size); 2104 } 2105 2106 // Now emit a range for the CU itself. 2107 if (TheCU->getRanges().size() > 1) { 2108 Asm->OutStreamer.EmitLabel( 2109 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID())); 2110 for (const RangeSpan &Range : TheCU->getRanges()) { 2111 const MCSymbol *Begin = Range.getStart(); 2112 const MCSymbol *End = Range.getEnd(); 2113 assert(Begin && "Range without a begin symbol?"); 2114 assert(End && "Range without an end symbol?"); 2115 Asm->OutStreamer.EmitSymbolValue(Begin, Size); 2116 Asm->OutStreamer.EmitSymbolValue(End, Size); 2117 } 2118 // And terminate the list with two 0 values. 2119 Asm->OutStreamer.EmitIntValue(0, Size); 2120 Asm->OutStreamer.EmitIntValue(0, Size); 2121 } 2122 } 2123 } 2124 2125 // DWARF5 Experimental Separate Dwarf emitters. 2126 2127 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2128 std::unique_ptr<DwarfUnit> NewU) { 2129 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, 2130 U.getCUNode().getSplitDebugFilename()); 2131 2132 if (!CompilationDir.empty()) 2133 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2134 2135 addGnuPubAttributes(*NewU, Die); 2136 2137 SkeletonHolder.addUnit(std::move(NewU)); 2138 } 2139 2140 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list, 2141 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id, 2142 // DW_AT_addr_base, DW_AT_ranges_base. 2143 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2144 2145 auto OwnedUnit = make_unique<DwarfCompileUnit>( 2146 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2147 DwarfCompileUnit &NewCU = *OwnedUnit; 2148 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(), 2149 DwarfInfoSectionSym); 2150 2151 NewCU.initStmtList(DwarfLineSectionSym); 2152 2153 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2154 2155 return NewCU; 2156 } 2157 2158 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2159 // compile units that would normally be in debug_info. 2160 void DwarfDebug::emitDebugInfoDWO() { 2161 assert(useSplitDwarf() && "No split dwarf debug info?"); 2162 // Don't pass an abbrev symbol, using a constant zero instead so as not to 2163 // emit relocations into the dwo file. 2164 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr); 2165 } 2166 2167 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2168 // abbreviations for the .debug_info.dwo section. 2169 void DwarfDebug::emitDebugAbbrevDWO() { 2170 assert(useSplitDwarf() && "No split dwarf?"); 2171 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2172 } 2173 2174 void DwarfDebug::emitDebugLineDWO() { 2175 assert(useSplitDwarf() && "No split dwarf?"); 2176 Asm->OutStreamer.SwitchSection( 2177 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2178 SplitTypeUnitFileTable.Emit(Asm->OutStreamer); 2179 } 2180 2181 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2182 // string section and is identical in format to traditional .debug_str 2183 // sections. 2184 void DwarfDebug::emitDebugStrDWO() { 2185 assert(useSplitDwarf() && "No split dwarf?"); 2186 const MCSection *OffSec = 2187 Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2188 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2189 OffSec); 2190 } 2191 2192 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2193 if (!useSplitDwarf()) 2194 return nullptr; 2195 if (SingleCU) 2196 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory()); 2197 return &SplitTypeUnitFileTable; 2198 } 2199 2200 static uint64_t makeTypeSignature(StringRef Identifier) { 2201 MD5 Hash; 2202 Hash.update(Identifier); 2203 // ... take the least significant 8 bytes and return those. Our MD5 2204 // implementation always returns its results in little endian, swap bytes 2205 // appropriately. 2206 MD5::MD5Result Result; 2207 Hash.final(Result); 2208 return *reinterpret_cast<support::ulittle64_t *>(Result + 8); 2209 } 2210 2211 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2212 StringRef Identifier, DIE &RefDie, 2213 DICompositeType CTy) { 2214 // Fast path if we're building some type units and one has already used the 2215 // address pool we know we're going to throw away all this work anyway, so 2216 // don't bother building dependent types. 2217 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2218 return; 2219 2220 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy]; 2221 if (TU) { 2222 CU.addDIETypeSignature(RefDie, *TU); 2223 return; 2224 } 2225 2226 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2227 AddrPool.resetUsedFlag(); 2228 2229 auto OwnedUnit = make_unique<DwarfTypeUnit>( 2230 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm, 2231 this, &InfoHolder, getDwoLineTable(CU)); 2232 DwarfTypeUnit &NewTU = *OwnedUnit; 2233 DIE &UnitDie = NewTU.getUnitDie(); 2234 TU = &NewTU; 2235 TypeUnitsUnderConstruction.push_back( 2236 std::make_pair(std::move(OwnedUnit), CTy)); 2237 2238 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2239 CU.getLanguage()); 2240 2241 uint64_t Signature = makeTypeSignature(Identifier); 2242 NewTU.setTypeSignature(Signature); 2243 2244 if (useSplitDwarf()) 2245 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(), 2246 DwarfTypesDWOSectionSym); 2247 else { 2248 CU.applyStmtList(UnitDie); 2249 NewTU.initSection( 2250 Asm->getObjFileLowering().getDwarfTypesSection(Signature)); 2251 } 2252 2253 NewTU.setType(NewTU.createTypeDIE(CTy)); 2254 2255 if (TopLevelType) { 2256 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2257 TypeUnitsUnderConstruction.clear(); 2258 2259 // Types referencing entries in the address table cannot be placed in type 2260 // units. 2261 if (AddrPool.hasBeenUsed()) { 2262 2263 // Remove all the types built while building this type. 2264 // This is pessimistic as some of these types might not be dependent on 2265 // the type that used an address. 2266 for (const auto &TU : TypeUnitsToAdd) 2267 DwarfTypeUnits.erase(TU.second); 2268 2269 // Construct this type in the CU directly. 2270 // This is inefficient because all the dependent types will be rebuilt 2271 // from scratch, including building them in type units, discovering that 2272 // they depend on addresses, throwing them out and rebuilding them. 2273 CU.constructTypeDIE(RefDie, CTy); 2274 return; 2275 } 2276 2277 // If the type wasn't dependent on fission addresses, finish adding the type 2278 // and all its dependent types. 2279 for (auto &TU : TypeUnitsToAdd) 2280 InfoHolder.addUnit(std::move(TU.first)); 2281 } 2282 CU.addDIETypeSignature(RefDie, NewTU); 2283 } 2284 2285 // Accelerator table mutators - add each name along with its companion 2286 // DIE to the proper table while ensuring that the name that we're going 2287 // to reference is in the string table. We do this since the names we 2288 // add may not only be identical to the names in the DIE. 2289 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) { 2290 if (!useDwarfAccelTables()) 2291 return; 2292 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name), 2293 &Die); 2294 } 2295 2296 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) { 2297 if (!useDwarfAccelTables()) 2298 return; 2299 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name), 2300 &Die); 2301 } 2302 2303 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) { 2304 if (!useDwarfAccelTables()) 2305 return; 2306 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name), 2307 &Die); 2308 } 2309 2310 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) { 2311 if (!useDwarfAccelTables()) 2312 return; 2313 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name), 2314 &Die); 2315 } 2316