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