1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for writing dwarf debug info into asm files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "DwarfDebug.h" 14 #include "ByteStreamer.h" 15 #include "DIEHash.h" 16 #include "DebugLocEntry.h" 17 #include "DebugLocStream.h" 18 #include "DwarfCompileUnit.h" 19 #include "DwarfExpression.h" 20 #include "DwarfFile.h" 21 #include "DwarfUnit.h" 22 #include "llvm/ADT/APInt.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/DenseSet.h" 25 #include "llvm/ADT/MapVector.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/BinaryFormat/Dwarf.h" 32 #include "llvm/CodeGen/AccelTable.h" 33 #include "llvm/CodeGen/AsmPrinter.h" 34 #include "llvm/CodeGen/DIE.h" 35 #include "llvm/CodeGen/LexicalScopes.h" 36 #include "llvm/CodeGen/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineInstr.h" 39 #include "llvm/CodeGen/MachineModuleInfo.h" 40 #include "llvm/CodeGen/MachineOperand.h" 41 #include "llvm/CodeGen/TargetInstrInfo.h" 42 #include "llvm/CodeGen/TargetRegisterInfo.h" 43 #include "llvm/CodeGen/TargetSubtargetInfo.h" 44 #include "llvm/DebugInfo/DWARF/DWARFExpression.h" 45 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h" 46 #include "llvm/IR/Constants.h" 47 #include "llvm/IR/DebugInfoMetadata.h" 48 #include "llvm/IR/DebugLoc.h" 49 #include "llvm/IR/Function.h" 50 #include "llvm/IR/GlobalVariable.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/MC/MCAsmInfo.h" 53 #include "llvm/MC/MCContext.h" 54 #include "llvm/MC/MCDwarf.h" 55 #include "llvm/MC/MCSection.h" 56 #include "llvm/MC/MCStreamer.h" 57 #include "llvm/MC/MCSymbol.h" 58 #include "llvm/MC/MCTargetOptions.h" 59 #include "llvm/MC/MachineLocation.h" 60 #include "llvm/MC/SectionKind.h" 61 #include "llvm/Pass.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/MD5.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/Timer.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Target/TargetLoweringObjectFile.h" 71 #include "llvm/Target/TargetMachine.h" 72 #include "llvm/Target/TargetOptions.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstddef> 76 #include <cstdint> 77 #include <iterator> 78 #include <string> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 #define DEBUG_TYPE "dwarfdebug" 85 86 static cl::opt<bool> 87 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 88 cl::desc("Disable debug info printing")); 89 90 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier( 91 "use-dwarf-ranges-base-address-specifier", cl::Hidden, 92 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false)); 93 94 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 95 cl::Hidden, 96 cl::desc("Generate dwarf aranges"), 97 cl::init(false)); 98 99 static cl::opt<bool> 100 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 101 cl::desc("Generate DWARF4 type units."), 102 cl::init(false)); 103 104 static cl::opt<bool> SplitDwarfCrossCuReferences( 105 "split-dwarf-cross-cu-references", cl::Hidden, 106 cl::desc("Enable cross-cu references in DWO files"), cl::init(false)); 107 108 enum DefaultOnOff { Default, Enable, Disable }; 109 110 static cl::opt<DefaultOnOff> UnknownLocations( 111 "use-unknown-locations", cl::Hidden, 112 cl::desc("Make an absence of debug location information explicit."), 113 cl::values(clEnumVal(Default, "At top of block or after label"), 114 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), 115 cl::init(Default)); 116 117 static cl::opt<AccelTableKind> AccelTables( 118 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), 119 cl::values(clEnumValN(AccelTableKind::Default, "Default", 120 "Default for platform"), 121 clEnumValN(AccelTableKind::None, "Disable", "Disabled."), 122 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), 123 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), 124 cl::init(AccelTableKind::Default)); 125 126 static cl::opt<DefaultOnOff> 127 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, 128 cl::desc("Use inlined strings rather than string section."), 129 cl::values(clEnumVal(Default, "Default for platform"), 130 clEnumVal(Enable, "Enabled"), 131 clEnumVal(Disable, "Disabled")), 132 cl::init(Default)); 133 134 static cl::opt<bool> 135 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, 136 cl::desc("Disable emission .debug_ranges section."), 137 cl::init(false)); 138 139 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences( 140 "dwarf-sections-as-references", cl::Hidden, 141 cl::desc("Use sections+offset as references rather than labels."), 142 cl::values(clEnumVal(Default, "Default for platform"), 143 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), 144 cl::init(Default)); 145 146 enum LinkageNameOption { 147 DefaultLinkageNames, 148 AllLinkageNames, 149 AbstractLinkageNames 150 }; 151 152 static cl::opt<LinkageNameOption> 153 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, 154 cl::desc("Which DWARF linkage-name attributes to emit."), 155 cl::values(clEnumValN(DefaultLinkageNames, "Default", 156 "Default for platform"), 157 clEnumValN(AllLinkageNames, "All", "All"), 158 clEnumValN(AbstractLinkageNames, "Abstract", 159 "Abstract subprograms")), 160 cl::init(DefaultLinkageNames)); 161 162 static const char *const DWARFGroupName = "dwarf"; 163 static const char *const DWARFGroupDescription = "DWARF Emission"; 164 static const char *const DbgTimerName = "writer"; 165 static const char *const DbgTimerDescription = "DWARF Debug Writer"; 166 static constexpr unsigned ULEB128PadSize = 4; 167 168 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) { 169 BS.EmitInt8( 170 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op) 171 : dwarf::OperationEncodingString(Op)); 172 } 173 174 void DebugLocDwarfExpression::emitSigned(int64_t Value) { 175 BS.EmitSLEB128(Value, Twine(Value)); 176 } 177 178 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) { 179 BS.EmitULEB128(Value, Twine(Value)); 180 } 181 182 void DebugLocDwarfExpression::emitData1(uint8_t Value) { 183 BS.EmitInt8(Value, Twine(Value)); 184 } 185 186 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) { 187 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit"); 188 BS.EmitULEB128(Idx, Twine(Idx), ULEB128PadSize); 189 } 190 191 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 192 unsigned MachineReg) { 193 // This information is not available while emitting .debug_loc entries. 194 return false; 195 } 196 197 bool DbgVariable::isBlockByrefVariable() const { 198 assert(getVariable() && "Invalid complex DbgVariable!"); 199 return getVariable()->getType()->isBlockByrefStruct(); 200 } 201 202 const DIType *DbgVariable::getType() const { 203 DIType *Ty = getVariable()->getType(); 204 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 205 // addresses instead. 206 if (Ty->isBlockByrefStruct()) { 207 /* Byref variables, in Blocks, are declared by the programmer as 208 "SomeType VarName;", but the compiler creates a 209 __Block_byref_x_VarName struct, and gives the variable VarName 210 either the struct, or a pointer to the struct, as its type. This 211 is necessary for various behind-the-scenes things the compiler 212 needs to do with by-reference variables in blocks. 213 214 However, as far as the original *programmer* is concerned, the 215 variable should still have type 'SomeType', as originally declared. 216 217 The following function dives into the __Block_byref_x_VarName 218 struct to find the original type of the variable. This will be 219 passed back to the code generating the type for the Debug 220 Information Entry for the variable 'VarName'. 'VarName' will then 221 have the original type 'SomeType' in its debug information. 222 223 The original type 'SomeType' will be the type of the field named 224 'VarName' inside the __Block_byref_x_VarName struct. 225 226 NOTE: In order for this to not completely fail on the debugger 227 side, the Debug Information Entry for the variable VarName needs to 228 have a DW_AT_location that tells the debugger how to unwind through 229 the pointers and __Block_byref_x_VarName struct to find the actual 230 value of the variable. The function addBlockByrefType does this. */ 231 DIType *subType = Ty; 232 uint16_t tag = Ty->getTag(); 233 234 if (tag == dwarf::DW_TAG_pointer_type) 235 subType = cast<DIDerivedType>(Ty)->getBaseType(); 236 237 auto Elements = cast<DICompositeType>(subType)->getElements(); 238 for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 239 auto *DT = cast<DIDerivedType>(Elements[i]); 240 if (getName() == DT->getName()) 241 return DT->getBaseType(); 242 } 243 } 244 return Ty; 245 } 246 247 /// Get .debug_loc entry for the instruction range starting at MI. 248 static DbgValueLoc getDebugLocValue(const MachineInstr *MI) { 249 const DIExpression *Expr = MI->getDebugExpression(); 250 assert(MI->getNumOperands() == 4); 251 if (MI->getOperand(0).isReg()) { 252 auto RegOp = MI->getOperand(0); 253 auto Op1 = MI->getOperand(1); 254 // If the second operand is an immediate, this is a 255 // register-indirect address. 256 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 257 MachineLocation MLoc(RegOp.getReg(), Op1.isImm()); 258 return DbgValueLoc(Expr, MLoc); 259 } 260 if (MI->getOperand(0).isImm()) 261 return DbgValueLoc(Expr, MI->getOperand(0).getImm()); 262 if (MI->getOperand(0).isFPImm()) 263 return DbgValueLoc(Expr, MI->getOperand(0).getFPImm()); 264 if (MI->getOperand(0).isCImm()) 265 return DbgValueLoc(Expr, MI->getOperand(0).getCImm()); 266 267 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 268 } 269 270 void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) { 271 assert(FrameIndexExprs.empty() && "Already initialized?"); 272 assert(!ValueLoc.get() && "Already initialized?"); 273 274 assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable"); 275 assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() && 276 "Wrong inlined-at"); 277 278 ValueLoc = llvm::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue)); 279 if (auto *E = DbgValue->getDebugExpression()) 280 if (E->getNumElements()) 281 FrameIndexExprs.push_back({0, E}); 282 } 283 284 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const { 285 if (FrameIndexExprs.size() == 1) 286 return FrameIndexExprs; 287 288 assert(llvm::all_of(FrameIndexExprs, 289 [](const FrameIndexExpr &A) { 290 return A.Expr->isFragment(); 291 }) && 292 "multiple FI expressions without DW_OP_LLVM_fragment"); 293 llvm::sort(FrameIndexExprs, 294 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool { 295 return A.Expr->getFragmentInfo()->OffsetInBits < 296 B.Expr->getFragmentInfo()->OffsetInBits; 297 }); 298 299 return FrameIndexExprs; 300 } 301 302 void DbgVariable::addMMIEntry(const DbgVariable &V) { 303 assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry"); 304 assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry"); 305 assert(V.getVariable() == getVariable() && "conflicting variable"); 306 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location"); 307 308 assert(!FrameIndexExprs.empty() && "Expected an MMI entry"); 309 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry"); 310 311 // FIXME: This logic should not be necessary anymore, as we now have proper 312 // deduplication. However, without it, we currently run into the assertion 313 // below, which means that we are likely dealing with broken input, i.e. two 314 // non-fragment entries for the same variable at different frame indices. 315 if (FrameIndexExprs.size()) { 316 auto *Expr = FrameIndexExprs.back().Expr; 317 if (!Expr || !Expr->isFragment()) 318 return; 319 } 320 321 for (const auto &FIE : V.FrameIndexExprs) 322 // Ignore duplicate entries. 323 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) { 324 return FIE.FI == Other.FI && FIE.Expr == Other.Expr; 325 })) 326 FrameIndexExprs.push_back(FIE); 327 328 assert((FrameIndexExprs.size() == 1 || 329 llvm::all_of(FrameIndexExprs, 330 [](FrameIndexExpr &FIE) { 331 return FIE.Expr && FIE.Expr->isFragment(); 332 })) && 333 "conflicting locations for variable"); 334 } 335 336 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, 337 bool GenerateTypeUnits, 338 DebuggerKind Tuning, 339 const Triple &TT) { 340 // Honor an explicit request. 341 if (AccelTables != AccelTableKind::Default) 342 return AccelTables; 343 344 // Accelerator tables with type units are currently not supported. 345 if (GenerateTypeUnits) 346 return AccelTableKind::None; 347 348 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5 349 // always implies debug_names. For lower standard versions we use apple 350 // accelerator tables on apple platforms and debug_names elsewhere. 351 if (DwarfVersion >= 5) 352 return AccelTableKind::Dwarf; 353 if (Tuning == DebuggerKind::LLDB) 354 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple 355 : AccelTableKind::Dwarf; 356 return AccelTableKind::None; 357 } 358 359 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 360 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()), 361 InfoHolder(A, "info_string", DIEValueAllocator), 362 SkeletonHolder(A, "skel_string", DIEValueAllocator), 363 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) { 364 const Triple &TT = Asm->TM.getTargetTriple(); 365 366 // Make sure we know our "debugger tuning". The target option takes 367 // precedence; fall back to triple-based defaults. 368 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default) 369 DebuggerTuning = Asm->TM.Options.DebuggerTuning; 370 else if (IsDarwin) 371 DebuggerTuning = DebuggerKind::LLDB; 372 else if (TT.isPS4CPU()) 373 DebuggerTuning = DebuggerKind::SCE; 374 else 375 DebuggerTuning = DebuggerKind::GDB; 376 377 if (DwarfInlinedStrings == Default) 378 UseInlineStrings = TT.isNVPTX(); 379 else 380 UseInlineStrings = DwarfInlinedStrings == Enable; 381 382 UseLocSection = !TT.isNVPTX(); 383 384 HasAppleExtensionAttributes = tuneForLLDB(); 385 386 // Handle split DWARF. 387 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty(); 388 389 // SCE defaults to linkage names only for abstract subprograms. 390 if (DwarfLinkageNames == DefaultLinkageNames) 391 UseAllLinkageNames = !tuneForSCE(); 392 else 393 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames; 394 395 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 396 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 397 : MMI->getModule()->getDwarfVersion(); 398 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2. 399 DwarfVersion = 400 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION); 401 402 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX(); 403 404 // Use sections as references. Force for NVPTX. 405 if (DwarfSectionsAsReferences == Default) 406 UseSectionsAsReferences = TT.isNVPTX(); 407 else 408 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable; 409 410 // Don't generate type units for unsupported object file formats. 411 GenerateTypeUnits = 412 A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits; 413 414 TheAccelTableKind = computeAccelTableKind( 415 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple()); 416 417 // Work around a GDB bug. GDB doesn't support the standard opcode; 418 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which 419 // is defined as of DWARF 3. 420 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 421 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616 422 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3; 423 424 // GDB does not fully support the DWARF 4 representation for bitfields. 425 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB(); 426 427 // The DWARF v5 string offsets table has - possibly shared - contributions 428 // from each compile and type unit each preceded by a header. The string 429 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses 430 // a monolithic string offsets table without any header. 431 UseSegmentedStringOffsetsTable = DwarfVersion >= 5; 432 433 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion); 434 } 435 436 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 437 DwarfDebug::~DwarfDebug() = default; 438 439 static bool isObjCClass(StringRef Name) { 440 return Name.startswith("+") || Name.startswith("-"); 441 } 442 443 static bool hasObjCCategory(StringRef Name) { 444 if (!isObjCClass(Name)) 445 return false; 446 447 return Name.find(") ") != StringRef::npos; 448 } 449 450 static void getObjCClassCategory(StringRef In, StringRef &Class, 451 StringRef &Category) { 452 if (!hasObjCCategory(In)) { 453 Class = In.slice(In.find('[') + 1, In.find(' ')); 454 Category = ""; 455 return; 456 } 457 458 Class = In.slice(In.find('[') + 1, In.find('(')); 459 Category = In.slice(In.find('[') + 1, In.find(' ')); 460 } 461 462 static StringRef getObjCMethodName(StringRef In) { 463 return In.slice(In.find(' ') + 1, In.find(']')); 464 } 465 466 // Add the various names to the Dwarf accelerator table names. 467 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU, 468 const DISubprogram *SP, DIE &Die) { 469 if (getAccelTableKind() != AccelTableKind::Apple && 470 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 471 return; 472 473 if (!SP->isDefinition()) 474 return; 475 476 if (SP->getName() != "") 477 addAccelName(CU, SP->getName(), Die); 478 479 // If the linkage name is different than the name, go ahead and output that as 480 // well into the name table. Only do that if we are going to actually emit 481 // that name. 482 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() && 483 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP))) 484 addAccelName(CU, SP->getLinkageName(), Die); 485 486 // If this is an Objective-C selector name add it to the ObjC accelerator 487 // too. 488 if (isObjCClass(SP->getName())) { 489 StringRef Class, Category; 490 getObjCClassCategory(SP->getName(), Class, Category); 491 addAccelObjC(CU, Class, Die); 492 if (Category != "") 493 addAccelObjC(CU, Category, Die); 494 // Also add the base method name to the name table. 495 addAccelName(CU, getObjCMethodName(SP->getName()), Die); 496 } 497 } 498 499 /// Check whether we should create a DIE for the given Scope, return true 500 /// if we don't create a DIE (the corresponding DIE is null). 501 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 502 if (Scope->isAbstractScope()) 503 return false; 504 505 // We don't create a DIE if there is no Range. 506 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 507 if (Ranges.empty()) 508 return true; 509 510 if (Ranges.size() > 1) 511 return false; 512 513 // We don't create a DIE if we have a single Range and the end label 514 // is null. 515 return !getLabelAfterInsn(Ranges.front().second); 516 } 517 518 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) { 519 F(CU); 520 if (auto *SkelCU = CU.getSkeleton()) 521 if (CU.getCUNode()->getSplitDebugInlining()) 522 F(*SkelCU); 523 } 524 525 bool DwarfDebug::shareAcrossDWOCUs() const { 526 return SplitDwarfCrossCuReferences; 527 } 528 529 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, 530 LexicalScope *Scope) { 531 assert(Scope && Scope->getScopeNode()); 532 assert(Scope->isAbstractScope()); 533 assert(!Scope->getInlinedAt()); 534 535 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 536 537 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 538 // was inlined from another compile unit. 539 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining()) 540 // Avoid building the original CU if it won't be used 541 SrcCU.constructAbstractSubprogramScopeDIE(Scope); 542 else { 543 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 544 if (auto *SkelCU = CU.getSkeleton()) { 545 (shareAcrossDWOCUs() ? CU : SrcCU) 546 .constructAbstractSubprogramScopeDIE(Scope); 547 if (CU.getCUNode()->getSplitDebugInlining()) 548 SkelCU->constructAbstractSubprogramScopeDIE(Scope); 549 } else 550 CU.constructAbstractSubprogramScopeDIE(Scope); 551 } 552 } 553 554 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP, 555 DwarfCompileUnit &CU, DIE &ScopeDIE, 556 const MachineFunction &MF) { 557 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if 558 // the subprogram is required to have one. 559 if (!SP.areAllCallsDescribed() || !SP.isDefinition()) 560 return; 561 562 // Use DW_AT_call_all_calls to express that call site entries are present 563 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls 564 // because one of its requirements is not met: call site entries for 565 // optimized-out calls are elided. 566 CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls); 567 568 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 569 assert(TII && "TargetInstrInfo not found: cannot label tail calls"); 570 571 // Emit call site entries for each call or tail call in the function. 572 for (const MachineBasicBlock &MBB : MF) { 573 for (const MachineInstr &MI : MBB.instrs()) { 574 // Skip instructions which aren't calls. Both calls and tail-calling jump 575 // instructions (e.g TAILJMPd64) are classified correctly here. 576 if (!MI.isCall()) 577 continue; 578 579 // TODO: Add support for targets with delay slots (see: beginInstruction). 580 if (MI.hasDelaySlot()) 581 return; 582 583 // If this is a direct call, find the callee's subprogram. 584 const MachineOperand &CalleeOp = MI.getOperand(0); 585 if (!CalleeOp.isGlobal()) 586 continue; 587 const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal()); 588 if (!CalleeDecl || !CalleeDecl->getSubprogram()) 589 continue; 590 591 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc). 592 // TODO: Add support for indirect calls. 593 594 bool IsTail = TII->isTailCall(MI); 595 596 // For tail calls, no return PC information is needed. For regular calls, 597 // the return PC is needed to disambiguate paths in the call graph which 598 // could lead to some target function. 599 const MCExpr *PCOffset = 600 IsTail ? nullptr : getFunctionLocalOffsetAfterInsn(&MI); 601 602 assert((IsTail || PCOffset) && "Call without return PC information"); 603 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> " 604 << CalleeDecl->getName() << (IsTail ? " [tail]" : "") 605 << "\n"); 606 CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(), 607 IsTail, PCOffset); 608 } 609 } 610 } 611 612 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const { 613 if (!U.hasDwarfPubSections()) 614 return; 615 616 U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 617 } 618 619 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit, 620 DwarfCompileUnit &NewCU) { 621 DIE &Die = NewCU.getUnitDie(); 622 StringRef FN = DIUnit->getFilename(); 623 624 StringRef Producer = DIUnit->getProducer(); 625 StringRef Flags = DIUnit->getFlags(); 626 if (!Flags.empty() && !useAppleExtensionAttributes()) { 627 std::string ProducerWithFlags = Producer.str() + " " + Flags.str(); 628 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags); 629 } else 630 NewCU.addString(Die, dwarf::DW_AT_producer, Producer); 631 632 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 633 DIUnit->getSourceLanguage()); 634 NewCU.addString(Die, dwarf::DW_AT_name, FN); 635 636 // Add DW_str_offsets_base to the unit DIE, except for split units. 637 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 638 NewCU.addStringOffsetsStart(); 639 640 if (!useSplitDwarf()) { 641 NewCU.initStmtList(); 642 643 // If we're using split dwarf the compilation dir is going to be in the 644 // skeleton CU and so we don't need to duplicate it here. 645 if (!CompilationDir.empty()) 646 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 647 648 addGnuPubAttributes(NewCU, Die); 649 } 650 651 if (useAppleExtensionAttributes()) { 652 if (DIUnit->isOptimized()) 653 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 654 655 StringRef Flags = DIUnit->getFlags(); 656 if (!Flags.empty()) 657 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 658 659 if (unsigned RVer = DIUnit->getRuntimeVersion()) 660 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 661 dwarf::DW_FORM_data1, RVer); 662 } 663 664 if (DIUnit->getDWOId()) { 665 // This CU is either a clang module DWO or a skeleton CU. 666 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 667 DIUnit->getDWOId()); 668 if (!DIUnit->getSplitDebugFilename().empty()) 669 // This is a prefabricated skeleton CU. 670 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name, 671 DIUnit->getSplitDebugFilename()); 672 } 673 } 674 // Create new DwarfCompileUnit for the given metadata node with tag 675 // DW_TAG_compile_unit. 676 DwarfCompileUnit & 677 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) { 678 if (auto *CU = CUMap.lookup(DIUnit)) 679 return *CU; 680 681 CompilationDir = DIUnit->getDirectory(); 682 683 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 684 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 685 DwarfCompileUnit &NewCU = *OwnedUnit; 686 InfoHolder.addUnit(std::move(OwnedUnit)); 687 688 for (auto *IE : DIUnit->getImportedEntities()) 689 NewCU.addImportedEntity(IE); 690 691 // LTO with assembly output shares a single line table amongst multiple CUs. 692 // To avoid the compilation directory being ambiguous, let the line table 693 // explicitly describe the directory of all files, never relying on the 694 // compilation directory. 695 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU) 696 Asm->OutStreamer->emitDwarfFile0Directive( 697 CompilationDir, DIUnit->getFilename(), 698 NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(), 699 NewCU.getUniqueID()); 700 701 if (useSplitDwarf()) { 702 NewCU.setSkeleton(constructSkeletonCU(NewCU)); 703 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection()); 704 } else { 705 finishUnitAttributes(DIUnit, NewCU); 706 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 707 } 708 709 CUMap.insert({DIUnit, &NewCU}); 710 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU}); 711 return NewCU; 712 } 713 714 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 715 const DIImportedEntity *N) { 716 if (isa<DILocalScope>(N->getScope())) 717 return; 718 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope())) 719 D->addChild(TheCU.constructImportedEntityDIE(N)); 720 } 721 722 /// Sort and unique GVEs by comparing their fragment offset. 723 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & 724 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) { 725 llvm::sort( 726 GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) { 727 // Sort order: first null exprs, then exprs without fragment 728 // info, then sort by fragment offset in bits. 729 // FIXME: Come up with a more comprehensive comparator so 730 // the sorting isn't non-deterministic, and so the following 731 // std::unique call works correctly. 732 if (!A.Expr || !B.Expr) 733 return !!B.Expr; 734 auto FragmentA = A.Expr->getFragmentInfo(); 735 auto FragmentB = B.Expr->getFragmentInfo(); 736 if (!FragmentA || !FragmentB) 737 return !!FragmentB; 738 return FragmentA->OffsetInBits < FragmentB->OffsetInBits; 739 }); 740 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(), 741 [](DwarfCompileUnit::GlobalExpr A, 742 DwarfCompileUnit::GlobalExpr B) { 743 return A.Expr == B.Expr; 744 }), 745 GVEs.end()); 746 return GVEs; 747 } 748 749 // Emit all Dwarf sections that should come prior to the content. Create 750 // global DIEs and emit initial debug info sections. This is invoked by 751 // the target AsmPrinter. 752 void DwarfDebug::beginModule() { 753 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName, 754 DWARFGroupDescription, TimePassesIsEnabled); 755 if (DisableDebugInfoPrinting) { 756 MMI->setDebugInfoAvailability(false); 757 return; 758 } 759 760 const Module *M = MMI->getModule(); 761 762 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(), 763 M->debug_compile_units_end()); 764 // Tell MMI whether we have debug info. 765 assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) && 766 "DebugInfoAvailabilty initialized unexpectedly"); 767 SingleCU = NumDebugCUs == 1; 768 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>> 769 GVMap; 770 for (const GlobalVariable &Global : M->globals()) { 771 SmallVector<DIGlobalVariableExpression *, 1> GVs; 772 Global.getDebugInfo(GVs); 773 for (auto *GVE : GVs) 774 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()}); 775 } 776 777 // Create the symbol that designates the start of the unit's contribution 778 // to the string offsets table. In a split DWARF scenario, only the skeleton 779 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol). 780 if (useSegmentedStringOffsetsTable()) 781 (useSplitDwarf() ? SkeletonHolder : InfoHolder) 782 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base")); 783 784 785 // Create the symbols that designates the start of the DWARF v5 range list 786 // and locations list tables. They are located past the table headers. 787 if (getDwarfVersion() >= 5) { 788 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 789 Holder.setRnglistsTableBaseSym( 790 Asm->createTempSymbol("rnglists_table_base")); 791 Holder.setLoclistsTableBaseSym( 792 Asm->createTempSymbol("loclists_table_base")); 793 794 if (useSplitDwarf()) 795 InfoHolder.setRnglistsTableBaseSym( 796 Asm->createTempSymbol("rnglists_dwo_table_base")); 797 } 798 799 // Create the symbol that points to the first entry following the debug 800 // address table (.debug_addr) header. 801 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base")); 802 803 for (DICompileUnit *CUNode : M->debug_compile_units()) { 804 // FIXME: Move local imported entities into a list attached to the 805 // subprogram, then this search won't be needed and a 806 // getImportedEntities().empty() test should go below with the rest. 807 bool HasNonLocalImportedEntities = llvm::any_of( 808 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) { 809 return !isa<DILocalScope>(IE->getScope()); 810 }); 811 812 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() && 813 CUNode->getRetainedTypes().empty() && 814 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty()) 815 continue; 816 817 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode); 818 819 // Global Variables. 820 for (auto *GVE : CUNode->getGlobalVariables()) { 821 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we 822 // already know about the variable and it isn't adding a constant 823 // expression. 824 auto &GVMapEntry = GVMap[GVE->getVariable()]; 825 auto *Expr = GVE->getExpression(); 826 if (!GVMapEntry.size() || (Expr && Expr->isConstant())) 827 GVMapEntry.push_back({nullptr, Expr}); 828 } 829 DenseSet<DIGlobalVariable *> Processed; 830 for (auto *GVE : CUNode->getGlobalVariables()) { 831 DIGlobalVariable *GV = GVE->getVariable(); 832 if (Processed.insert(GV).second) 833 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV])); 834 } 835 836 for (auto *Ty : CUNode->getEnumTypes()) { 837 // The enum types array by design contains pointers to 838 // MDNodes rather than DIRefs. Unique them here. 839 CU.getOrCreateTypeDIE(cast<DIType>(Ty)); 840 } 841 for (auto *Ty : CUNode->getRetainedTypes()) { 842 // The retained types array by design contains pointers to 843 // MDNodes rather than DIRefs. Unique them here. 844 if (DIType *RT = dyn_cast<DIType>(Ty)) 845 // There is no point in force-emitting a forward declaration. 846 CU.getOrCreateTypeDIE(RT); 847 } 848 // Emit imported_modules last so that the relevant context is already 849 // available. 850 for (auto *IE : CUNode->getImportedEntities()) 851 constructAndAddImportedEntityDIE(CU, IE); 852 } 853 } 854 855 void DwarfDebug::finishEntityDefinitions() { 856 for (const auto &Entity : ConcreteEntities) { 857 DIE *Die = Entity->getDIE(); 858 assert(Die); 859 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 860 // in the ConcreteEntities list, rather than looking it up again here. 861 // DIE::getUnit isn't simple - it walks parent pointers, etc. 862 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie()); 863 assert(Unit); 864 Unit->finishEntityDefinition(Entity.get()); 865 } 866 } 867 868 void DwarfDebug::finishSubprogramDefinitions() { 869 for (const DISubprogram *SP : ProcessedSPNodes) { 870 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug); 871 forBothCUs( 872 getOrCreateDwarfCompileUnit(SP->getUnit()), 873 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); }); 874 } 875 } 876 877 void DwarfDebug::finalizeModuleInfo() { 878 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 879 880 finishSubprogramDefinitions(); 881 882 finishEntityDefinitions(); 883 884 // Include the DWO file name in the hash if there's more than one CU. 885 // This handles ThinLTO's situation where imported CUs may very easily be 886 // duplicate with the same CU partially imported into another ThinLTO unit. 887 StringRef DWOName; 888 if (CUMap.size() > 1) 889 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile; 890 891 // Handle anything that needs to be done on a per-unit basis after 892 // all other generation. 893 for (const auto &P : CUMap) { 894 auto &TheCU = *P.second; 895 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 896 continue; 897 // Emit DW_AT_containing_type attribute to connect types with their 898 // vtable holding type. 899 TheCU.constructContainingTypeDIEs(); 900 901 // Add CU specific attributes if we need to add any. 902 // If we're splitting the dwarf out now that we've got the entire 903 // CU then add the dwo id to it. 904 auto *SkCU = TheCU.getSkeleton(); 905 if (useSplitDwarf() && !empty(TheCU.getUnitDie().children())) { 906 finishUnitAttributes(TheCU.getCUNode(), TheCU); 907 TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name, 908 Asm->TM.Options.MCOptions.SplitDwarfFile); 909 SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name, 910 Asm->TM.Options.MCOptions.SplitDwarfFile); 911 // Emit a unique identifier for this CU. 912 uint64_t ID = 913 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie()); 914 if (getDwarfVersion() >= 5) { 915 TheCU.setDWOId(ID); 916 SkCU->setDWOId(ID); 917 } else { 918 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 919 dwarf::DW_FORM_data8, ID); 920 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 921 dwarf::DW_FORM_data8, ID); 922 } 923 924 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) { 925 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 926 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 927 Sym, Sym); 928 } 929 } else if (SkCU) { 930 finishUnitAttributes(SkCU->getCUNode(), *SkCU); 931 } 932 933 // If we have code split among multiple sections or non-contiguous 934 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 935 // remain in the .o file, otherwise add a DW_AT_low_pc. 936 // FIXME: We should use ranges allow reordering of code ala 937 // .subsections_via_symbols in mach-o. This would mean turning on 938 // ranges for all subprogram DIEs for mach-o. 939 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 940 941 if (unsigned NumRanges = TheCU.getRanges().size()) { 942 if (NumRanges > 1 && useRangesSection()) 943 // A DW_AT_low_pc attribute may also be specified in combination with 944 // DW_AT_ranges to specify the default base address for use in 945 // location lists (see Section 2.6.2) and range lists (see Section 946 // 2.17.3). 947 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 948 else 949 U.setBaseAddress(TheCU.getRanges().front().getStart()); 950 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 951 } 952 953 // We don't keep track of which addresses are used in which CU so this 954 // is a bit pessimistic under LTO. 955 if (!AddrPool.isEmpty() && 956 (getDwarfVersion() >= 5 || 957 (SkCU && !empty(TheCU.getUnitDie().children())))) 958 U.addAddrTableBase(); 959 960 if (getDwarfVersion() >= 5) { 961 if (U.hasRangeLists()) 962 U.addRnglistsBase(); 963 964 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) 965 U.addLoclistsBase(); 966 } 967 968 auto *CUNode = cast<DICompileUnit>(P.first); 969 // If compile Unit has macros, emit "DW_AT_macro_info" attribute. 970 if (CUNode->getMacros()) 971 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info, 972 U.getMacroLabelBegin(), 973 TLOF.getDwarfMacinfoSection()->getBeginSymbol()); 974 } 975 976 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 977 for (auto *CUNode : MMI->getModule()->debug_compile_units()) 978 if (CUNode->getDWOId()) 979 getOrCreateDwarfCompileUnit(CUNode); 980 981 // Compute DIE offsets and sizes. 982 InfoHolder.computeSizeAndOffsets(); 983 if (useSplitDwarf()) 984 SkeletonHolder.computeSizeAndOffsets(); 985 } 986 987 // Emit all Dwarf sections that should come after the content. 988 void DwarfDebug::endModule() { 989 assert(CurFn == nullptr); 990 assert(CurMI == nullptr); 991 992 for (const auto &P : CUMap) { 993 auto &CU = *P.second; 994 CU.createBaseTypeDIEs(); 995 } 996 997 // If we aren't actually generating debug info (check beginModule - 998 // conditionalized on !DisableDebugInfoPrinting and the presence of the 999 // llvm.dbg.cu metadata node) 1000 if (!MMI->hasDebugInfo()) 1001 return; 1002 1003 // Finalize the debug info for the module. 1004 finalizeModuleInfo(); 1005 1006 emitDebugStr(); 1007 1008 if (useSplitDwarf()) 1009 emitDebugLocDWO(); 1010 else 1011 // Emit info into a debug loc section. 1012 emitDebugLoc(); 1013 1014 // Corresponding abbreviations into a abbrev section. 1015 emitAbbreviations(); 1016 1017 // Emit all the DIEs into a debug info section. 1018 emitDebugInfo(); 1019 1020 // Emit info into a debug aranges section. 1021 if (GenerateARangeSection) 1022 emitDebugARanges(); 1023 1024 // Emit info into a debug ranges section. 1025 emitDebugRanges(); 1026 1027 // Emit info into a debug macinfo section. 1028 emitDebugMacinfo(); 1029 1030 if (useSplitDwarf()) { 1031 emitDebugStrDWO(); 1032 emitDebugInfoDWO(); 1033 emitDebugAbbrevDWO(); 1034 emitDebugLineDWO(); 1035 emitDebugRangesDWO(); 1036 } 1037 1038 emitDebugAddr(); 1039 1040 // Emit info into the dwarf accelerator table sections. 1041 switch (getAccelTableKind()) { 1042 case AccelTableKind::Apple: 1043 emitAccelNames(); 1044 emitAccelObjC(); 1045 emitAccelNamespaces(); 1046 emitAccelTypes(); 1047 break; 1048 case AccelTableKind::Dwarf: 1049 emitAccelDebugNames(); 1050 break; 1051 case AccelTableKind::None: 1052 break; 1053 case AccelTableKind::Default: 1054 llvm_unreachable("Default should have already been resolved."); 1055 } 1056 1057 // Emit the pubnames and pubtypes sections if requested. 1058 emitDebugPubSections(); 1059 1060 // clean up. 1061 // FIXME: AbstractVariables.clear(); 1062 } 1063 1064 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU, 1065 const DINode *Node, 1066 const MDNode *ScopeNode) { 1067 if (CU.getExistingAbstractEntity(Node)) 1068 return; 1069 1070 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope( 1071 cast<DILocalScope>(ScopeNode))); 1072 } 1073 1074 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU, 1075 const DINode *Node, const MDNode *ScopeNode) { 1076 if (CU.getExistingAbstractEntity(Node)) 1077 return; 1078 1079 if (LexicalScope *Scope = 1080 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 1081 CU.createAbstractEntity(Node, Scope); 1082 } 1083 1084 // Collect variable information from side table maintained by MF. 1085 void DwarfDebug::collectVariableInfoFromMFTable( 1086 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) { 1087 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars; 1088 for (const auto &VI : Asm->MF->getVariableDbgInfo()) { 1089 if (!VI.Var) 1090 continue; 1091 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1092 "Expected inlined-at fields to agree"); 1093 1094 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt()); 1095 Processed.insert(Var); 1096 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1097 1098 // If variable scope is not found then skip this variable. 1099 if (!Scope) 1100 continue; 1101 1102 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode()); 1103 auto RegVar = llvm::make_unique<DbgVariable>( 1104 cast<DILocalVariable>(Var.first), Var.second); 1105 RegVar->initializeMMI(VI.Expr, VI.Slot); 1106 if (DbgVariable *DbgVar = MFVars.lookup(Var)) 1107 DbgVar->addMMIEntry(*RegVar); 1108 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) { 1109 MFVars.insert({Var, RegVar.get()}); 1110 ConcreteEntities.push_back(std::move(RegVar)); 1111 } 1112 } 1113 } 1114 1115 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1116 /// enclosing lexical scope. The check ensures there are no other instructions 1117 /// in the same lexical scope preceding the DBG_VALUE and that its range is 1118 /// either open or otherwise rolls off the end of the scope. 1119 static bool validThroughout(LexicalScopes &LScopes, 1120 const MachineInstr *DbgValue, 1121 const MachineInstr *RangeEnd) { 1122 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1123 auto MBB = DbgValue->getParent(); 1124 auto DL = DbgValue->getDebugLoc(); 1125 auto *LScope = LScopes.findLexicalScope(DL); 1126 // Scope doesn't exist; this is a dead DBG_VALUE. 1127 if (!LScope) 1128 return false; 1129 auto &LSRange = LScope->getRanges(); 1130 if (LSRange.size() == 0) 1131 return false; 1132 1133 // Determine if the DBG_VALUE is valid at the beginning of its lexical block. 1134 const MachineInstr *LScopeBegin = LSRange.front().first; 1135 // Early exit if the lexical scope begins outside of the current block. 1136 if (LScopeBegin->getParent() != MBB) 1137 return false; 1138 MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1139 for (++Pred; Pred != MBB->rend(); ++Pred) { 1140 if (Pred->getFlag(MachineInstr::FrameSetup)) 1141 break; 1142 auto PredDL = Pred->getDebugLoc(); 1143 if (!PredDL || Pred->isMetaInstruction()) 1144 continue; 1145 // Check whether the instruction preceding the DBG_VALUE is in the same 1146 // (sub)scope as the DBG_VALUE. 1147 if (DL->getScope() == PredDL->getScope()) 1148 return false; 1149 auto *PredScope = LScopes.findLexicalScope(PredDL); 1150 if (!PredScope || LScope->dominates(PredScope)) 1151 return false; 1152 } 1153 1154 // If the range of the DBG_VALUE is open-ended, report success. 1155 if (!RangeEnd) 1156 return true; 1157 1158 // Fail if there are instructions belonging to our scope in another block. 1159 const MachineInstr *LScopeEnd = LSRange.back().second; 1160 if (LScopeEnd->getParent() != MBB) 1161 return false; 1162 1163 // Single, constant DBG_VALUEs in the prologue are promoted to be live 1164 // throughout the function. This is a hack, presumably for DWARF v2 and not 1165 // necessarily correct. It would be much better to use a dbg.declare instead 1166 // if we know the constant is live throughout the scope. 1167 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty()) 1168 return true; 1169 1170 return false; 1171 } 1172 1173 /// Build the location list for all DBG_VALUEs in the function that 1174 /// describe the same variable. The resulting DebugLocEntries will have 1175 /// strict monotonically increasing begin addresses and will never 1176 /// overlap. If the resulting list has only one entry that is valid 1177 /// throughout variable's scope return true. 1178 // 1179 // See the definition of DbgValueHistoryMap::Entry for an explanation of the 1180 // different kinds of history map entries. One thing to be aware of is that if 1181 // a debug value is ended by another entry (rather than being valid until the 1182 // end of the function), that entry's instruction may or may not be included in 1183 // the range, depending on if the entry is a clobbering entry (it has an 1184 // instruction that clobbers one or more preceding locations), or if it is an 1185 // (overlapping) debug value entry. This distinction can be seen in the example 1186 // below. The first debug value is ended by the clobbering entry 2, and the 1187 // second and third debug values are ended by the overlapping debug value entry 1188 // 4. 1189 // 1190 // Input: 1191 // 1192 // History map entries [type, end index, mi] 1193 // 1194 // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)] 1195 // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)] 1196 // 2 | | [Clobber, $reg0 = [...], -, -] 1197 // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)] 1198 // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)] 1199 // 1200 // Output [start, end) [Value...]: 1201 // 1202 // [0-1) [(reg0, fragment 0, 32)] 1203 // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1204 // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)] 1205 // [4-) [(@g, fragment 0, 96)] 1206 bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 1207 const DbgValueHistoryMap::Entries &Entries) { 1208 using OpenRange = 1209 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>; 1210 SmallVector<OpenRange, 4> OpenRanges; 1211 bool isSafeForSingleLocation = true; 1212 const MachineInstr *StartDebugMI = nullptr; 1213 const MachineInstr *EndMI = nullptr; 1214 1215 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) { 1216 const MachineInstr *Instr = EI->getInstr(); 1217 1218 // Remove all values that are no longer live. 1219 size_t Index = std::distance(EB, EI); 1220 auto Last = 1221 remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; }); 1222 OpenRanges.erase(Last, OpenRanges.end()); 1223 1224 // If we are dealing with a clobbering entry, this iteration will result in 1225 // a location list entry starting after the clobbering instruction. 1226 const MCSymbol *StartLabel = 1227 EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr); 1228 assert(StartLabel && 1229 "Forgot label before/after instruction starting a range!"); 1230 1231 const MCSymbol *EndLabel; 1232 if (std::next(EI) == Entries.end()) { 1233 EndLabel = Asm->getFunctionEnd(); 1234 if (EI->isClobber()) 1235 EndMI = EI->getInstr(); 1236 } 1237 else if (std::next(EI)->isClobber()) 1238 EndLabel = getLabelAfterInsn(std::next(EI)->getInstr()); 1239 else 1240 EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr()); 1241 assert(EndLabel && "Forgot label after instruction ending a range!"); 1242 1243 if (EI->isDbgValue()) 1244 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n"); 1245 1246 // If this history map entry has a debug value, add that to the list of 1247 // open ranges and check if its location is valid for a single value 1248 // location. 1249 if (EI->isDbgValue()) { 1250 // Do not add undef debug values, as they are redundant information in 1251 // the location list entries. An undef debug results in an empty location 1252 // description. If there are any non-undef fragments then padding pieces 1253 // with empty location descriptions will automatically be inserted, and if 1254 // all fragments are undef then the whole location list entry is 1255 // redundant. 1256 if (!Instr->isUndefDebugValue()) { 1257 auto Value = getDebugLocValue(Instr); 1258 OpenRanges.emplace_back(EI->getEndIndex(), Value); 1259 1260 // TODO: Add support for single value fragment locations. 1261 if (Instr->getDebugExpression()->isFragment()) 1262 isSafeForSingleLocation = false; 1263 1264 if (!StartDebugMI) 1265 StartDebugMI = Instr; 1266 } else { 1267 isSafeForSingleLocation = false; 1268 } 1269 } 1270 1271 // Location list entries with empty location descriptions are redundant 1272 // information in DWARF, so do not emit those. 1273 if (OpenRanges.empty()) 1274 continue; 1275 1276 // Omit entries with empty ranges as they do not have any effect in DWARF. 1277 if (StartLabel == EndLabel) { 1278 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n"); 1279 continue; 1280 } 1281 1282 SmallVector<DbgValueLoc, 4> Values; 1283 for (auto &R : OpenRanges) 1284 Values.push_back(R.second); 1285 DebugLoc.emplace_back(StartLabel, EndLabel, Values); 1286 1287 // Attempt to coalesce the ranges of two otherwise identical 1288 // DebugLocEntries. 1289 auto CurEntry = DebugLoc.rbegin(); 1290 LLVM_DEBUG({ 1291 dbgs() << CurEntry->getValues().size() << " Values:\n"; 1292 for (auto &Value : CurEntry->getValues()) 1293 Value.dump(); 1294 dbgs() << "-----\n"; 1295 }); 1296 1297 auto PrevEntry = std::next(CurEntry); 1298 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1299 DebugLoc.pop_back(); 1300 } 1301 1302 return DebugLoc.size() == 1 && isSafeForSingleLocation && 1303 validThroughout(LScopes, StartDebugMI, EndMI); 1304 } 1305 1306 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU, 1307 LexicalScope &Scope, 1308 const DINode *Node, 1309 const DILocation *Location, 1310 const MCSymbol *Sym) { 1311 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode()); 1312 if (isa<const DILocalVariable>(Node)) { 1313 ConcreteEntities.push_back( 1314 llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node), 1315 Location)); 1316 InfoHolder.addScopeVariable(&Scope, 1317 cast<DbgVariable>(ConcreteEntities.back().get())); 1318 } else if (isa<const DILabel>(Node)) { 1319 ConcreteEntities.push_back( 1320 llvm::make_unique<DbgLabel>(cast<const DILabel>(Node), 1321 Location, Sym)); 1322 InfoHolder.addScopeLabel(&Scope, 1323 cast<DbgLabel>(ConcreteEntities.back().get())); 1324 } 1325 return ConcreteEntities.back().get(); 1326 } 1327 1328 // Find variables for each lexical scope. 1329 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU, 1330 const DISubprogram *SP, 1331 DenseSet<InlinedEntity> &Processed) { 1332 // Grab the variable info that was squirreled away in the MMI side-table. 1333 collectVariableInfoFromMFTable(TheCU, Processed); 1334 1335 for (const auto &I : DbgValues) { 1336 InlinedEntity IV = I.first; 1337 if (Processed.count(IV)) 1338 continue; 1339 1340 // Instruction ranges, specifying where IV is accessible. 1341 const auto &HistoryMapEntries = I.second; 1342 if (HistoryMapEntries.empty()) 1343 continue; 1344 1345 LexicalScope *Scope = nullptr; 1346 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first); 1347 if (const DILocation *IA = IV.second) 1348 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA); 1349 else 1350 Scope = LScopes.findLexicalScope(LocalVar->getScope()); 1351 // If variable scope is not found then skip this variable. 1352 if (!Scope) 1353 continue; 1354 1355 Processed.insert(IV); 1356 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU, 1357 *Scope, LocalVar, IV.second)); 1358 1359 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr(); 1360 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1361 1362 // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1363 // If the history map contains a single debug value, there may be an 1364 // additional entry which clobbers the debug value. 1365 size_t HistSize = HistoryMapEntries.size(); 1366 bool SingleValueWithClobber = 1367 HistSize == 2 && HistoryMapEntries[1].isClobber(); 1368 if (HistSize == 1 || SingleValueWithClobber) { 1369 const auto *End = 1370 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr; 1371 if (validThroughout(LScopes, MInsn, End)) { 1372 RegVar->initializeDbgValue(MInsn); 1373 continue; 1374 } 1375 } 1376 1377 // Do not emit location lists if .debug_loc secton is disabled. 1378 if (!useLocSection()) 1379 continue; 1380 1381 // Handle multiple DBG_VALUE instructions describing one variable. 1382 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1383 1384 // Build the location list for this variable. 1385 SmallVector<DebugLocEntry, 8> Entries; 1386 bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries); 1387 1388 // Check whether buildLocationList managed to merge all locations to one 1389 // that is valid throughout the variable's scope. If so, produce single 1390 // value location. 1391 if (isValidSingleLocation) { 1392 RegVar->initializeDbgValue(Entries[0].getValues()[0]); 1393 continue; 1394 } 1395 1396 // If the variable has a DIBasicType, extract it. Basic types cannot have 1397 // unique identifiers, so don't bother resolving the type with the 1398 // identifier map. 1399 const DIBasicType *BT = dyn_cast<DIBasicType>( 1400 static_cast<const Metadata *>(LocalVar->getType())); 1401 1402 // Finalize the entry by lowering it into a DWARF bytestream. 1403 for (auto &Entry : Entries) 1404 Entry.finalize(*Asm, List, BT, TheCU); 1405 } 1406 1407 // For each InlinedEntity collected from DBG_LABEL instructions, convert to 1408 // DWARF-related DbgLabel. 1409 for (const auto &I : DbgLabels) { 1410 InlinedEntity IL = I.first; 1411 const MachineInstr *MI = I.second; 1412 if (MI == nullptr) 1413 continue; 1414 1415 LexicalScope *Scope = nullptr; 1416 const DILabel *Label = cast<DILabel>(IL.first); 1417 // Get inlined DILocation if it is inlined label. 1418 if (const DILocation *IA = IL.second) 1419 Scope = LScopes.findInlinedScope(Label->getScope(), IA); 1420 else 1421 Scope = LScopes.findLexicalScope(Label->getScope()); 1422 // If label scope is not found then skip this label. 1423 if (!Scope) 1424 continue; 1425 1426 Processed.insert(IL); 1427 /// At this point, the temporary label is created. 1428 /// Save the temporary label to DbgLabel entity to get the 1429 /// actually address when generating Dwarf DIE. 1430 MCSymbol *Sym = getLabelBeforeInsn(MI); 1431 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym); 1432 } 1433 1434 // Collect info for variables/labels that were optimized out. 1435 for (const DINode *DN : SP->getRetainedNodes()) { 1436 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1437 continue; 1438 LexicalScope *Scope = nullptr; 1439 if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1440 Scope = LScopes.findLexicalScope(DV->getScope()); 1441 } else if (auto *DL = dyn_cast<DILabel>(DN)) { 1442 Scope = LScopes.findLexicalScope(DL->getScope()); 1443 } 1444 1445 if (Scope) 1446 createConcreteEntity(TheCU, *Scope, DN, nullptr); 1447 } 1448 } 1449 1450 // Process beginning of an instruction. 1451 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1452 DebugHandlerBase::beginInstruction(MI); 1453 assert(CurMI); 1454 1455 const auto *SP = MI->getMF()->getFunction().getSubprogram(); 1456 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1457 return; 1458 1459 // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1460 // If the instruction is part of the function frame setup code, do not emit 1461 // any line record, as there is no correspondence with any user code. 1462 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1463 return; 1464 const DebugLoc &DL = MI->getDebugLoc(); 1465 // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1466 // the last line number actually emitted, to see if it was line 0. 1467 unsigned LastAsmLine = 1468 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1469 1470 // Request a label after the call in order to emit AT_return_pc information 1471 // in call site entries. TODO: Add support for targets with delay slots. 1472 if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot()) 1473 requestLabelAfterInsn(MI); 1474 1475 if (DL == PrevInstLoc) { 1476 // If we have an ongoing unspecified location, nothing to do here. 1477 if (!DL) 1478 return; 1479 // We have an explicit location, same as the previous location. 1480 // But we might be coming back to it after a line 0 record. 1481 if (LastAsmLine == 0 && DL.getLine() != 0) { 1482 // Reinstate the source location but not marked as a statement. 1483 const MDNode *Scope = DL.getScope(); 1484 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1485 } 1486 return; 1487 } 1488 1489 if (!DL) { 1490 // We have an unspecified location, which might want to be line 0. 1491 // If we have already emitted a line-0 record, don't repeat it. 1492 if (LastAsmLine == 0) 1493 return; 1494 // If user said Don't Do That, don't do that. 1495 if (UnknownLocations == Disable) 1496 return; 1497 // See if we have a reason to emit a line-0 record now. 1498 // Reasons to emit a line-0 record include: 1499 // - User asked for it (UnknownLocations). 1500 // - Instruction has a label, so it's referenced from somewhere else, 1501 // possibly debug information; we want it to have a source location. 1502 // - Instruction is at the top of a block; we don't want to inherit the 1503 // location from the physically previous (maybe unrelated) block. 1504 if (UnknownLocations == Enable || PrevLabel || 1505 (PrevInstBB && PrevInstBB != MI->getParent())) { 1506 // Preserve the file and column numbers, if we can, to save space in 1507 // the encoded line table. 1508 // Do not update PrevInstLoc, it remembers the last non-0 line. 1509 const MDNode *Scope = nullptr; 1510 unsigned Column = 0; 1511 if (PrevInstLoc) { 1512 Scope = PrevInstLoc.getScope(); 1513 Column = PrevInstLoc.getCol(); 1514 } 1515 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1516 } 1517 return; 1518 } 1519 1520 // We have an explicit location, different from the previous location. 1521 // Don't repeat a line-0 record, but otherwise emit the new location. 1522 // (The new location might be an explicit line 0, which we do emit.) 1523 if (DL.getLine() == 0 && LastAsmLine == 0) 1524 return; 1525 unsigned Flags = 0; 1526 if (DL == PrologEndLoc) { 1527 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 1528 PrologEndLoc = DebugLoc(); 1529 } 1530 // If the line changed, we call that a new statement; unless we went to 1531 // line 0 and came back, in which case it is not a new statement. 1532 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 1533 if (DL.getLine() && DL.getLine() != OldLine) 1534 Flags |= DWARF2_FLAG_IS_STMT; 1535 1536 const MDNode *Scope = DL.getScope(); 1537 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1538 1539 // If we're not at line 0, remember this location. 1540 if (DL.getLine()) 1541 PrevInstLoc = DL; 1542 } 1543 1544 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1545 // First known non-DBG_VALUE and non-frame setup location marks 1546 // the beginning of the function body. 1547 for (const auto &MBB : *MF) 1548 for (const auto &MI : MBB) 1549 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1550 MI.getDebugLoc()) 1551 return MI.getDebugLoc(); 1552 return DebugLoc(); 1553 } 1554 1555 /// Register a source line with debug info. Returns the unique label that was 1556 /// emitted and which provides correspondence to the source line list. 1557 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col, 1558 const MDNode *S, unsigned Flags, unsigned CUID, 1559 uint16_t DwarfVersion, 1560 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) { 1561 StringRef Fn; 1562 unsigned FileNo = 1; 1563 unsigned Discriminator = 0; 1564 if (auto *Scope = cast_or_null<DIScope>(S)) { 1565 Fn = Scope->getFilename(); 1566 if (Line != 0 && DwarfVersion >= 4) 1567 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1568 Discriminator = LBF->getDiscriminator(); 1569 1570 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID]) 1571 .getOrCreateSourceID(Scope->getFile()); 1572 } 1573 Asm.OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 1574 Discriminator, Fn); 1575 } 1576 1577 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF, 1578 unsigned CUID) { 1579 // Get beginning of function. 1580 if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) { 1581 // Ensure the compile unit is created if the function is called before 1582 // beginFunction(). 1583 (void)getOrCreateDwarfCompileUnit( 1584 MF.getFunction().getSubprogram()->getUnit()); 1585 // We'd like to list the prologue as "not statements" but GDB behaves 1586 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1587 const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 1588 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT, 1589 CUID, getDwarfVersion(), getUnits()); 1590 return PrologEndLoc; 1591 } 1592 return DebugLoc(); 1593 } 1594 1595 // Gather pre-function debug information. Assumes being called immediately 1596 // after the function entry point has been emitted. 1597 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 1598 CurFn = MF; 1599 1600 auto *SP = MF->getFunction().getSubprogram(); 1601 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 1602 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1603 return; 1604 1605 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 1606 1607 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1608 // belongs to so that we add to the correct per-cu line table in the 1609 // non-asm case. 1610 if (Asm->OutStreamer->hasRawTextSupport()) 1611 // Use a single line table if we are generating assembly. 1612 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1613 else 1614 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 1615 1616 // Record beginning of function. 1617 PrologEndLoc = emitInitialLocDirective( 1618 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID()); 1619 } 1620 1621 void DwarfDebug::skippedNonDebugFunction() { 1622 // If we don't have a subprogram for this function then there will be a hole 1623 // in the range information. Keep note of this by setting the previously used 1624 // section to nullptr. 1625 PrevCU = nullptr; 1626 CurFn = nullptr; 1627 } 1628 1629 // Gather and emit post-function debug information. 1630 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 1631 const DISubprogram *SP = MF->getFunction().getSubprogram(); 1632 1633 assert(CurFn == MF && 1634 "endFunction should be called with the same function as beginFunction"); 1635 1636 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1637 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1638 1639 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1640 assert(!FnScope || SP == FnScope->getScopeNode()); 1641 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 1642 if (TheCU.getCUNode()->isDebugDirectivesOnly()) { 1643 PrevLabel = nullptr; 1644 CurFn = nullptr; 1645 return; 1646 } 1647 1648 DenseSet<InlinedEntity> Processed; 1649 collectEntityInfo(TheCU, SP, Processed); 1650 1651 // Add the range of this function to the list of ranges for the CU. 1652 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1653 1654 // Under -gmlt, skip building the subprogram if there are no inlined 1655 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 1656 // is still needed as we need its source location. 1657 if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 1658 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 1659 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1660 assert(InfoHolder.getScopeVariables().empty()); 1661 PrevLabel = nullptr; 1662 CurFn = nullptr; 1663 return; 1664 } 1665 1666 #ifndef NDEBUG 1667 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1668 #endif 1669 // Construct abstract scopes. 1670 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1671 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1672 for (const DINode *DN : SP->getRetainedNodes()) { 1673 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1674 continue; 1675 1676 const MDNode *Scope = nullptr; 1677 if (auto *DV = dyn_cast<DILocalVariable>(DN)) 1678 Scope = DV->getScope(); 1679 else if (auto *DL = dyn_cast<DILabel>(DN)) 1680 Scope = DL->getScope(); 1681 else 1682 llvm_unreachable("Unexpected DI type!"); 1683 1684 // Collect info for variables/labels that were optimized out. 1685 ensureAbstractEntityIsCreated(TheCU, DN, Scope); 1686 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1687 && "ensureAbstractEntityIsCreated inserted abstract scopes"); 1688 } 1689 constructAbstractSubprogramScopeDIE(TheCU, AScope); 1690 } 1691 1692 ProcessedSPNodes.insert(SP); 1693 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope); 1694 if (auto *SkelCU = TheCU.getSkeleton()) 1695 if (!LScopes.getAbstractScopesList().empty() && 1696 TheCU.getCUNode()->getSplitDebugInlining()) 1697 SkelCU->constructSubprogramScopeDIE(SP, FnScope); 1698 1699 // Construct call site entries. 1700 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF); 1701 1702 // Clear debug info 1703 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1704 // DbgVariables except those that are also in AbstractVariables (since they 1705 // can be used cross-function) 1706 InfoHolder.getScopeVariables().clear(); 1707 InfoHolder.getScopeLabels().clear(); 1708 PrevLabel = nullptr; 1709 CurFn = nullptr; 1710 } 1711 1712 // Register a source line with debug info. Returns the unique label that was 1713 // emitted and which provides correspondence to the source line list. 1714 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1715 unsigned Flags) { 1716 ::recordSourceLine(*Asm, Line, Col, S, Flags, 1717 Asm->OutStreamer->getContext().getDwarfCompileUnitID(), 1718 getDwarfVersion(), getUnits()); 1719 } 1720 1721 //===----------------------------------------------------------------------===// 1722 // Emit Methods 1723 //===----------------------------------------------------------------------===// 1724 1725 // Emit the debug info section. 1726 void DwarfDebug::emitDebugInfo() { 1727 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1728 Holder.emitUnits(/* UseOffsets */ false); 1729 } 1730 1731 // Emit the abbreviation section. 1732 void DwarfDebug::emitAbbreviations() { 1733 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1734 1735 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1736 } 1737 1738 void DwarfDebug::emitStringOffsetsTableHeader() { 1739 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1740 Holder.getStringPool().emitStringOffsetsTableHeader( 1741 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(), 1742 Holder.getStringOffsetsStartSym()); 1743 } 1744 1745 template <typename AccelTableT> 1746 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 1747 StringRef TableName) { 1748 Asm->OutStreamer->SwitchSection(Section); 1749 1750 // Emit the full data. 1751 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 1752 } 1753 1754 void DwarfDebug::emitAccelDebugNames() { 1755 // Don't emit anything if we have no compilation units to index. 1756 if (getUnits().empty()) 1757 return; 1758 1759 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits()); 1760 } 1761 1762 // Emit visible names into a hashed accelerator table section. 1763 void DwarfDebug::emitAccelNames() { 1764 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1765 "Names"); 1766 } 1767 1768 // Emit objective C classes and categories into a hashed accelerator table 1769 // section. 1770 void DwarfDebug::emitAccelObjC() { 1771 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1772 "ObjC"); 1773 } 1774 1775 // Emit namespace dies into a hashed accelerator table. 1776 void DwarfDebug::emitAccelNamespaces() { 1777 emitAccel(AccelNamespace, 1778 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1779 "namespac"); 1780 } 1781 1782 // Emit type dies into a hashed accelerator table. 1783 void DwarfDebug::emitAccelTypes() { 1784 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1785 "types"); 1786 } 1787 1788 // Public name handling. 1789 // The format for the various pubnames: 1790 // 1791 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1792 // for the DIE that is named. 1793 // 1794 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1795 // into the CU and the index value is computed according to the type of value 1796 // for the DIE that is named. 1797 // 1798 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1799 // it's the offset within the debug_info/debug_types dwo section, however, the 1800 // reference in the pubname header doesn't change. 1801 1802 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1803 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1804 const DIE *Die) { 1805 // Entities that ended up only in a Type Unit reference the CU instead (since 1806 // the pub entry has offsets within the CU there's no real offset that can be 1807 // provided anyway). As it happens all such entities (namespaces and types, 1808 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 1809 // not to be true it would be necessary to persist this information from the 1810 // point at which the entry is added to the index data structure - since by 1811 // the time the index is built from that, the original type/namespace DIE in a 1812 // type unit has already been destroyed so it can't be queried for properties 1813 // like tag, etc. 1814 if (Die->getTag() == dwarf::DW_TAG_compile_unit) 1815 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 1816 dwarf::GIEL_EXTERNAL); 1817 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1818 1819 // We could have a specification DIE that has our most of our knowledge, 1820 // look for that now. 1821 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1822 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1823 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1824 Linkage = dwarf::GIEL_EXTERNAL; 1825 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1826 Linkage = dwarf::GIEL_EXTERNAL; 1827 1828 switch (Die->getTag()) { 1829 case dwarf::DW_TAG_class_type: 1830 case dwarf::DW_TAG_structure_type: 1831 case dwarf::DW_TAG_union_type: 1832 case dwarf::DW_TAG_enumeration_type: 1833 return dwarf::PubIndexEntryDescriptor( 1834 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1835 ? dwarf::GIEL_STATIC 1836 : dwarf::GIEL_EXTERNAL); 1837 case dwarf::DW_TAG_typedef: 1838 case dwarf::DW_TAG_base_type: 1839 case dwarf::DW_TAG_subrange_type: 1840 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1841 case dwarf::DW_TAG_namespace: 1842 return dwarf::GIEK_TYPE; 1843 case dwarf::DW_TAG_subprogram: 1844 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1845 case dwarf::DW_TAG_variable: 1846 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1847 case dwarf::DW_TAG_enumerator: 1848 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1849 dwarf::GIEL_STATIC); 1850 default: 1851 return dwarf::GIEK_NONE; 1852 } 1853 } 1854 1855 /// emitDebugPubSections - Emit visible names and types into debug pubnames and 1856 /// pubtypes sections. 1857 void DwarfDebug::emitDebugPubSections() { 1858 for (const auto &NU : CUMap) { 1859 DwarfCompileUnit *TheU = NU.second; 1860 if (!TheU->hasDwarfPubSections()) 1861 continue; 1862 1863 bool GnuStyle = TheU->getCUNode()->getNameTableKind() == 1864 DICompileUnit::DebugNameTableKind::GNU; 1865 1866 Asm->OutStreamer->SwitchSection( 1867 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1868 : Asm->getObjFileLowering().getDwarfPubNamesSection()); 1869 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 1870 1871 Asm->OutStreamer->SwitchSection( 1872 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1873 : Asm->getObjFileLowering().getDwarfPubTypesSection()); 1874 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 1875 } 1876 } 1877 1878 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) { 1879 if (useSectionsAsReferences()) 1880 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(), 1881 CU.getDebugSectionOffset()); 1882 else 1883 Asm->emitDwarfSymbolReference(CU.getLabelBegin()); 1884 } 1885 1886 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 1887 DwarfCompileUnit *TheU, 1888 const StringMap<const DIE *> &Globals) { 1889 if (auto *Skeleton = TheU->getSkeleton()) 1890 TheU = Skeleton; 1891 1892 // Emit the header. 1893 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1894 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1895 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1896 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1897 1898 Asm->OutStreamer->EmitLabel(BeginLabel); 1899 1900 Asm->OutStreamer->AddComment("DWARF Version"); 1901 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); 1902 1903 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1904 emitSectionReference(*TheU); 1905 1906 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1907 Asm->emitInt32(TheU->getLength()); 1908 1909 // Emit the pubnames for this compilation unit. 1910 for (const auto &GI : Globals) { 1911 const char *Name = GI.getKeyData(); 1912 const DIE *Entity = GI.second; 1913 1914 Asm->OutStreamer->AddComment("DIE offset"); 1915 Asm->emitInt32(Entity->getOffset()); 1916 1917 if (GnuStyle) { 1918 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1919 Asm->OutStreamer->AddComment( 1920 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + 1921 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1922 Asm->emitInt8(Desc.toBits()); 1923 } 1924 1925 Asm->OutStreamer->AddComment("External Name"); 1926 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1927 } 1928 1929 Asm->OutStreamer->AddComment("End Mark"); 1930 Asm->emitInt32(0); 1931 Asm->OutStreamer->EmitLabel(EndLabel); 1932 } 1933 1934 /// Emit null-terminated strings into a debug str section. 1935 void DwarfDebug::emitDebugStr() { 1936 MCSection *StringOffsetsSection = nullptr; 1937 if (useSegmentedStringOffsetsTable()) { 1938 emitStringOffsetsTableHeader(); 1939 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 1940 } 1941 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1942 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 1943 StringOffsetsSection, /* UseRelativeOffsets = */ true); 1944 } 1945 1946 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1947 const DebugLocStream::Entry &Entry, 1948 const DwarfCompileUnit *CU) { 1949 auto &&Comments = DebugLocs.getComments(Entry); 1950 auto Comment = Comments.begin(); 1951 auto End = Comments.end(); 1952 1953 // The expressions are inserted into a byte stream rather early (see 1954 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that 1955 // need to reference a base_type DIE the offset of that DIE is not yet known. 1956 // To deal with this we instead insert a placeholder early and then extract 1957 // it here and replace it with the real reference. 1958 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 1959 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(), 1960 DebugLocs.getBytes(Entry).size()), 1961 Asm->getDataLayout().isLittleEndian(), PtrSize); 1962 DWARFExpression Expr(Data, getDwarfVersion(), PtrSize); 1963 1964 using Encoding = DWARFExpression::Operation::Encoding; 1965 uint32_t Offset = 0; 1966 for (auto &Op : Expr) { 1967 assert(Op.getCode() != dwarf::DW_OP_const_type && 1968 "3 operand ops not yet supported"); 1969 Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : ""); 1970 Offset++; 1971 for (unsigned I = 0; I < 2; ++I) { 1972 if (Op.getDescription().Op[I] == Encoding::SizeNA) 1973 continue; 1974 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) { 1975 if (CU) { 1976 uint64_t Offset = CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset(); 1977 assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit"); 1978 Asm->EmitULEB128(Offset, nullptr, ULEB128PadSize); 1979 } else { 1980 // Emit a reference to the 'generic type'. 1981 Asm->EmitULEB128(0, nullptr, ULEB128PadSize); 1982 } 1983 // Make sure comments stay aligned. 1984 for (unsigned J = 0; J < ULEB128PadSize; ++J) 1985 if (Comment != End) 1986 Comment++; 1987 } else { 1988 for (uint32_t J = Offset; J < Op.getOperandEndOffset(I); ++J) 1989 Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : ""); 1990 } 1991 Offset = Op.getOperandEndOffset(I); 1992 } 1993 assert(Offset == Op.getEndOffset()); 1994 } 1995 } 1996 1997 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1998 const DbgValueLoc &Value, 1999 DwarfExpression &DwarfExpr) { 2000 auto *DIExpr = Value.getExpression(); 2001 DIExpressionCursor ExprCursor(DIExpr); 2002 DwarfExpr.addFragmentOffset(DIExpr); 2003 // Regular entry. 2004 if (Value.isInt()) { 2005 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 2006 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 2007 DwarfExpr.addSignedConstant(Value.getInt()); 2008 else 2009 DwarfExpr.addUnsignedConstant(Value.getInt()); 2010 } else if (Value.isLocation()) { 2011 MachineLocation Location = Value.getLoc(); 2012 if (Location.isIndirect()) 2013 DwarfExpr.setMemoryLocationKind(); 2014 DIExpressionCursor Cursor(DIExpr); 2015 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 2016 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 2017 return; 2018 return DwarfExpr.addExpression(std::move(Cursor)); 2019 } else if (Value.isConstantFP()) { 2020 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt(); 2021 DwarfExpr.addUnsignedConstant(RawBytes); 2022 } 2023 DwarfExpr.addExpression(std::move(ExprCursor)); 2024 } 2025 2026 void DebugLocEntry::finalize(const AsmPrinter &AP, 2027 DebugLocStream::ListBuilder &List, 2028 const DIBasicType *BT, 2029 DwarfCompileUnit &TheCU) { 2030 assert(!Values.empty() && 2031 "location list entries without values are redundant"); 2032 assert(Begin != End && "unexpected location list entry with empty range"); 2033 DebugLocStream::EntryBuilder Entry(List, Begin, End); 2034 BufferByteStreamer Streamer = Entry.getStreamer(); 2035 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU); 2036 const DbgValueLoc &Value = Values[0]; 2037 if (Value.isFragment()) { 2038 // Emit all fragments that belong to the same variable and range. 2039 assert(llvm::all_of(Values, [](DbgValueLoc P) { 2040 return P.isFragment(); 2041 }) && "all values are expected to be fragments"); 2042 assert(std::is_sorted(Values.begin(), Values.end()) && 2043 "fragments are expected to be sorted"); 2044 2045 for (auto Fragment : Values) 2046 emitDebugLocValue(AP, BT, Fragment, DwarfExpr); 2047 2048 } else { 2049 assert(Values.size() == 1 && "only fragments may have >1 value"); 2050 emitDebugLocValue(AP, BT, Value, DwarfExpr); 2051 } 2052 DwarfExpr.finalize(); 2053 } 2054 2055 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, 2056 const DwarfCompileUnit *CU) { 2057 // Emit the size. 2058 Asm->OutStreamer->AddComment("Loc expr size"); 2059 if (getDwarfVersion() >= 5) 2060 Asm->EmitULEB128(DebugLocs.getBytes(Entry).size()); 2061 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max()) 2062 Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 2063 else { 2064 // The entry is too big to fit into 16 bit, drop it as there is nothing we 2065 // can do. 2066 Asm->emitInt16(0); 2067 return; 2068 } 2069 // Emit the entry. 2070 APByteStreamer Streamer(*Asm); 2071 emitDebugLocEntry(Streamer, Entry, CU); 2072 } 2073 2074 // Emit the common part of the DWARF 5 range/locations list tables header. 2075 static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder, 2076 MCSymbol *TableStart, 2077 MCSymbol *TableEnd) { 2078 // Build the table header, which starts with the length field. 2079 Asm->OutStreamer->AddComment("Length"); 2080 Asm->EmitLabelDifference(TableEnd, TableStart, 4); 2081 Asm->OutStreamer->EmitLabel(TableStart); 2082 // Version number (DWARF v5 and later). 2083 Asm->OutStreamer->AddComment("Version"); 2084 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion()); 2085 // Address size. 2086 Asm->OutStreamer->AddComment("Address size"); 2087 Asm->emitInt8(Asm->MAI->getCodePointerSize()); 2088 // Segment selector size. 2089 Asm->OutStreamer->AddComment("Segment selector size"); 2090 Asm->emitInt8(0); 2091 } 2092 2093 // Emit the header of a DWARF 5 range list table list table. Returns the symbol 2094 // that designates the end of the table for the caller to emit when the table is 2095 // complete. 2096 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, 2097 const DwarfFile &Holder) { 2098 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start"); 2099 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end"); 2100 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2101 2102 Asm->OutStreamer->AddComment("Offset entry count"); 2103 Asm->emitInt32(Holder.getRangeLists().size()); 2104 Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym()); 2105 2106 for (const RangeSpanList &List : Holder.getRangeLists()) 2107 Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(), 2108 4); 2109 2110 return TableEnd; 2111 } 2112 2113 // Emit the header of a DWARF 5 locations list table. Returns the symbol that 2114 // designates the end of the table for the caller to emit when the table is 2115 // complete. 2116 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm, 2117 const DwarfFile &Holder) { 2118 MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start"); 2119 MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end"); 2120 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2121 2122 // FIXME: Generate the offsets table and use DW_FORM_loclistx with the 2123 // DW_AT_loclists_base attribute. Until then set the number of offsets to 0. 2124 Asm->OutStreamer->AddComment("Offset entry count"); 2125 Asm->emitInt32(0); 2126 Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym()); 2127 2128 return TableEnd; 2129 } 2130 2131 // Emit locations into the .debug_loc/.debug_rnglists section. 2132 void DwarfDebug::emitDebugLoc() { 2133 if (DebugLocs.getLists().empty()) 2134 return; 2135 2136 bool IsLocLists = getDwarfVersion() >= 5; 2137 MCSymbol *TableEnd = nullptr; 2138 if (IsLocLists) { 2139 Asm->OutStreamer->SwitchSection( 2140 Asm->getObjFileLowering().getDwarfLoclistsSection()); 2141 TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder 2142 : InfoHolder); 2143 } else { 2144 Asm->OutStreamer->SwitchSection( 2145 Asm->getObjFileLowering().getDwarfLocSection()); 2146 } 2147 2148 unsigned char Size = Asm->MAI->getCodePointerSize(); 2149 for (const auto &List : DebugLocs.getLists()) { 2150 Asm->OutStreamer->EmitLabel(List.Label); 2151 2152 const DwarfCompileUnit *CU = List.CU; 2153 const MCSymbol *Base = CU->getBaseAddress(); 2154 for (const auto &Entry : DebugLocs.getEntries(List)) { 2155 if (Base) { 2156 // Set up the range. This range is relative to the entry point of the 2157 // compile unit. This is a hard coded 0 for low_pc when we're emitting 2158 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 2159 if (IsLocLists) { 2160 Asm->OutStreamer->AddComment("DW_LLE_offset_pair"); 2161 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1); 2162 Asm->OutStreamer->AddComment(" starting offset"); 2163 Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base); 2164 Asm->OutStreamer->AddComment(" ending offset"); 2165 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base); 2166 } else { 2167 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 2168 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 2169 } 2170 2171 emitDebugLocEntryLocation(Entry, CU); 2172 continue; 2173 } 2174 2175 // We have no base address. 2176 if (IsLocLists) { 2177 // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or 2178 // DW_LLE_startx_length in case if there is only a single range. 2179 // That should reduce the size of the debug data emited. 2180 // For now just use the DW_LLE_startx_length for all cases. 2181 Asm->OutStreamer->AddComment("DW_LLE_startx_length"); 2182 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2183 Asm->OutStreamer->AddComment(" start idx"); 2184 Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym)); 2185 Asm->OutStreamer->AddComment(" length"); 2186 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym); 2187 } else { 2188 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 2189 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 2190 } 2191 2192 emitDebugLocEntryLocation(Entry, CU); 2193 } 2194 2195 if (IsLocLists) { 2196 // .debug_loclists section ends with DW_LLE_end_of_list. 2197 Asm->OutStreamer->AddComment("DW_LLE_end_of_list"); 2198 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1); 2199 } else { 2200 // Terminate the .debug_loc list with two 0 values. 2201 Asm->OutStreamer->EmitIntValue(0, Size); 2202 Asm->OutStreamer->EmitIntValue(0, Size); 2203 } 2204 } 2205 2206 if (TableEnd) 2207 Asm->OutStreamer->EmitLabel(TableEnd); 2208 } 2209 2210 void DwarfDebug::emitDebugLocDWO() { 2211 for (const auto &List : DebugLocs.getLists()) { 2212 Asm->OutStreamer->SwitchSection( 2213 Asm->getObjFileLowering().getDwarfLocDWOSection()); 2214 Asm->OutStreamer->EmitLabel(List.Label); 2215 for (const auto &Entry : DebugLocs.getEntries(List)) { 2216 // GDB only supports startx_length in pre-standard split-DWARF. 2217 // (in v5 standard loclists, it currently* /only/ supports base_address + 2218 // offset_pair, so the implementations can't really share much since they 2219 // need to use different representations) 2220 // * as of October 2018, at least 2221 // Ideally/in v5, this could use SectionLabels to reuse existing addresses 2222 // in the address pool to minimize object size/relocations. 2223 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2224 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 2225 Asm->EmitULEB128(idx); 2226 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 2227 2228 emitDebugLocEntryLocation(Entry, List.CU); 2229 } 2230 Asm->emitInt8(dwarf::DW_LLE_end_of_list); 2231 } 2232 } 2233 2234 struct ArangeSpan { 2235 const MCSymbol *Start, *End; 2236 }; 2237 2238 // Emit a debug aranges section, containing a CU lookup for any 2239 // address we can tie back to a CU. 2240 void DwarfDebug::emitDebugARanges() { 2241 // Provides a unique id per text section. 2242 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 2243 2244 // Filter labels by section. 2245 for (const SymbolCU &SCU : ArangeLabels) { 2246 if (SCU.Sym->isInSection()) { 2247 // Make a note of this symbol and it's section. 2248 MCSection *Section = &SCU.Sym->getSection(); 2249 if (!Section->getKind().isMetadata()) 2250 SectionMap[Section].push_back(SCU); 2251 } else { 2252 // Some symbols (e.g. common/bss on mach-o) can have no section but still 2253 // appear in the output. This sucks as we rely on sections to build 2254 // arange spans. We can do it without, but it's icky. 2255 SectionMap[nullptr].push_back(SCU); 2256 } 2257 } 2258 2259 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 2260 2261 for (auto &I : SectionMap) { 2262 MCSection *Section = I.first; 2263 SmallVector<SymbolCU, 8> &List = I.second; 2264 if (List.size() < 1) 2265 continue; 2266 2267 // If we have no section (e.g. common), just write out 2268 // individual spans for each symbol. 2269 if (!Section) { 2270 for (const SymbolCU &Cur : List) { 2271 ArangeSpan Span; 2272 Span.Start = Cur.Sym; 2273 Span.End = nullptr; 2274 assert(Cur.CU); 2275 Spans[Cur.CU].push_back(Span); 2276 } 2277 continue; 2278 } 2279 2280 // Sort the symbols by offset within the section. 2281 llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) { 2282 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 2283 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 2284 2285 // Symbols with no order assigned should be placed at the end. 2286 // (e.g. section end labels) 2287 if (IA == 0) 2288 return false; 2289 if (IB == 0) 2290 return true; 2291 return IA < IB; 2292 }); 2293 2294 // Insert a final terminator. 2295 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 2296 2297 // Build spans between each label. 2298 const MCSymbol *StartSym = List[0].Sym; 2299 for (size_t n = 1, e = List.size(); n < e; n++) { 2300 const SymbolCU &Prev = List[n - 1]; 2301 const SymbolCU &Cur = List[n]; 2302 2303 // Try and build the longest span we can within the same CU. 2304 if (Cur.CU != Prev.CU) { 2305 ArangeSpan Span; 2306 Span.Start = StartSym; 2307 Span.End = Cur.Sym; 2308 assert(Prev.CU); 2309 Spans[Prev.CU].push_back(Span); 2310 StartSym = Cur.Sym; 2311 } 2312 } 2313 } 2314 2315 // Start the dwarf aranges section. 2316 Asm->OutStreamer->SwitchSection( 2317 Asm->getObjFileLowering().getDwarfARangesSection()); 2318 2319 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 2320 2321 // Build a list of CUs used. 2322 std::vector<DwarfCompileUnit *> CUs; 2323 for (const auto &it : Spans) { 2324 DwarfCompileUnit *CU = it.first; 2325 CUs.push_back(CU); 2326 } 2327 2328 // Sort the CU list (again, to ensure consistent output order). 2329 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 2330 return A->getUniqueID() < B->getUniqueID(); 2331 }); 2332 2333 // Emit an arange table for each CU we used. 2334 for (DwarfCompileUnit *CU : CUs) { 2335 std::vector<ArangeSpan> &List = Spans[CU]; 2336 2337 // Describe the skeleton CU's offset and length, not the dwo file's. 2338 if (auto *Skel = CU->getSkeleton()) 2339 CU = Skel; 2340 2341 // Emit size of content not including length itself. 2342 unsigned ContentSize = 2343 sizeof(int16_t) + // DWARF ARange version number 2344 sizeof(int32_t) + // Offset of CU in the .debug_info section 2345 sizeof(int8_t) + // Pointer Size (in bytes) 2346 sizeof(int8_t); // Segment Size (in bytes) 2347 2348 unsigned TupleSize = PtrSize * 2; 2349 2350 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2351 unsigned Padding = 2352 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2353 2354 ContentSize += Padding; 2355 ContentSize += (List.size() + 1) * TupleSize; 2356 2357 // For each compile unit, write the list of spans it covers. 2358 Asm->OutStreamer->AddComment("Length of ARange Set"); 2359 Asm->emitInt32(ContentSize); 2360 Asm->OutStreamer->AddComment("DWARF Arange version number"); 2361 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 2362 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 2363 emitSectionReference(*CU); 2364 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 2365 Asm->emitInt8(PtrSize); 2366 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 2367 Asm->emitInt8(0); 2368 2369 Asm->OutStreamer->emitFill(Padding, 0xff); 2370 2371 for (const ArangeSpan &Span : List) { 2372 Asm->EmitLabelReference(Span.Start, PtrSize); 2373 2374 // Calculate the size as being from the span start to it's end. 2375 if (Span.End) { 2376 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2377 } else { 2378 // For symbols without an end marker (e.g. common), we 2379 // write a single arange entry containing just that one symbol. 2380 uint64_t Size = SymSize[Span.Start]; 2381 if (Size == 0) 2382 Size = 1; 2383 2384 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 2385 } 2386 } 2387 2388 Asm->OutStreamer->AddComment("ARange terminator"); 2389 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2390 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2391 } 2392 } 2393 2394 /// Emit a single range list. We handle both DWARF v5 and earlier. 2395 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, 2396 const RangeSpanList &List) { 2397 2398 auto DwarfVersion = DD.getDwarfVersion(); 2399 // Emit our symbol so we can find the beginning of the range. 2400 Asm->OutStreamer->EmitLabel(List.getSym()); 2401 // Gather all the ranges that apply to the same section so they can share 2402 // a base address entry. 2403 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges; 2404 // Size for our labels. 2405 auto Size = Asm->MAI->getCodePointerSize(); 2406 2407 for (const RangeSpan &Range : List.getRanges()) 2408 SectionRanges[&Range.getStart()->getSection()].push_back(&Range); 2409 2410 const DwarfCompileUnit &CU = List.getCU(); 2411 const MCSymbol *CUBase = CU.getBaseAddress(); 2412 bool BaseIsSet = false; 2413 for (const auto &P : SectionRanges) { 2414 // Don't bother with a base address entry if there's only one range in 2415 // this section in this range list - for example ranges for a CU will 2416 // usually consist of single regions from each of many sections 2417 // (-ffunction-sections, or just C++ inline functions) except under LTO 2418 // or optnone where there may be holes in a single CU's section 2419 // contributions. 2420 auto *Base = CUBase; 2421 if (!Base && (P.second.size() > 1 || DwarfVersion < 5) && 2422 (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) { 2423 BaseIsSet = true; 2424 // FIXME/use care: This may not be a useful base address if it's not 2425 // the lowest address/range in this object. 2426 Base = P.second.front()->getStart(); 2427 if (DwarfVersion >= 5) { 2428 Base = DD.getSectionLabel(&Base->getSection()); 2429 Asm->OutStreamer->AddComment("DW_RLE_base_addressx"); 2430 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1); 2431 Asm->OutStreamer->AddComment(" base address index"); 2432 Asm->EmitULEB128(DD.getAddressPool().getIndex(Base)); 2433 } else { 2434 Asm->OutStreamer->EmitIntValue(-1, Size); 2435 Asm->OutStreamer->AddComment(" base address"); 2436 Asm->OutStreamer->EmitSymbolValue(Base, Size); 2437 } 2438 } else if (BaseIsSet && DwarfVersion < 5) { 2439 BaseIsSet = false; 2440 assert(!Base); 2441 Asm->OutStreamer->EmitIntValue(-1, Size); 2442 Asm->OutStreamer->EmitIntValue(0, Size); 2443 } 2444 2445 for (const auto *RS : P.second) { 2446 const MCSymbol *Begin = RS->getStart(); 2447 const MCSymbol *End = RS->getEnd(); 2448 assert(Begin && "Range without a begin symbol?"); 2449 assert(End && "Range without an end symbol?"); 2450 if (Base) { 2451 if (DwarfVersion >= 5) { 2452 // Emit DW_RLE_offset_pair when we have a base. 2453 Asm->OutStreamer->AddComment("DW_RLE_offset_pair"); 2454 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1); 2455 Asm->OutStreamer->AddComment(" starting offset"); 2456 Asm->EmitLabelDifferenceAsULEB128(Begin, Base); 2457 Asm->OutStreamer->AddComment(" ending offset"); 2458 Asm->EmitLabelDifferenceAsULEB128(End, Base); 2459 } else { 2460 Asm->EmitLabelDifference(Begin, Base, Size); 2461 Asm->EmitLabelDifference(End, Base, Size); 2462 } 2463 } else if (DwarfVersion >= 5) { 2464 Asm->OutStreamer->AddComment("DW_RLE_startx_length"); 2465 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1); 2466 Asm->OutStreamer->AddComment(" start index"); 2467 Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin)); 2468 Asm->OutStreamer->AddComment(" length"); 2469 Asm->EmitLabelDifferenceAsULEB128(End, Begin); 2470 } else { 2471 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2472 Asm->OutStreamer->EmitSymbolValue(End, Size); 2473 } 2474 } 2475 } 2476 if (DwarfVersion >= 5) { 2477 Asm->OutStreamer->AddComment("DW_RLE_end_of_list"); 2478 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1); 2479 } else { 2480 // Terminate the list with two 0 values. 2481 Asm->OutStreamer->EmitIntValue(0, Size); 2482 Asm->OutStreamer->EmitIntValue(0, Size); 2483 } 2484 } 2485 2486 static void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm, 2487 const DwarfFile &Holder, MCSymbol *TableEnd) { 2488 for (const RangeSpanList &List : Holder.getRangeLists()) 2489 emitRangeList(DD, Asm, List); 2490 2491 if (TableEnd) 2492 Asm->OutStreamer->EmitLabel(TableEnd); 2493 } 2494 2495 /// Emit address ranges into the .debug_ranges section or into the DWARF v5 2496 /// .debug_rnglists section. 2497 void DwarfDebug::emitDebugRanges() { 2498 if (CUMap.empty()) 2499 return; 2500 2501 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2502 2503 if (Holder.getRangeLists().empty()) 2504 return; 2505 2506 assert(useRangesSection()); 2507 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2508 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2509 })); 2510 2511 // Start the dwarf ranges section. 2512 MCSymbol *TableEnd = nullptr; 2513 if (getDwarfVersion() >= 5) { 2514 Asm->OutStreamer->SwitchSection( 2515 Asm->getObjFileLowering().getDwarfRnglistsSection()); 2516 TableEnd = emitRnglistsTableHeader(Asm, Holder); 2517 } else 2518 Asm->OutStreamer->SwitchSection( 2519 Asm->getObjFileLowering().getDwarfRangesSection()); 2520 2521 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2522 } 2523 2524 void DwarfDebug::emitDebugRangesDWO() { 2525 assert(useSplitDwarf()); 2526 2527 if (CUMap.empty()) 2528 return; 2529 2530 const auto &Holder = InfoHolder; 2531 2532 if (Holder.getRangeLists().empty()) 2533 return; 2534 2535 assert(getDwarfVersion() >= 5); 2536 assert(useRangesSection()); 2537 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2538 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2539 })); 2540 2541 // Start the dwarf ranges section. 2542 Asm->OutStreamer->SwitchSection( 2543 Asm->getObjFileLowering().getDwarfRnglistsDWOSection()); 2544 MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder); 2545 2546 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2547 } 2548 2549 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 2550 for (auto *MN : Nodes) { 2551 if (auto *M = dyn_cast<DIMacro>(MN)) 2552 emitMacro(*M); 2553 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 2554 emitMacroFile(*F, U); 2555 else 2556 llvm_unreachable("Unexpected DI type!"); 2557 } 2558 } 2559 2560 void DwarfDebug::emitMacro(DIMacro &M) { 2561 Asm->EmitULEB128(M.getMacinfoType()); 2562 Asm->EmitULEB128(M.getLine()); 2563 StringRef Name = M.getName(); 2564 StringRef Value = M.getValue(); 2565 Asm->OutStreamer->EmitBytes(Name); 2566 if (!Value.empty()) { 2567 // There should be one space between macro name and macro value. 2568 Asm->emitInt8(' '); 2569 Asm->OutStreamer->EmitBytes(Value); 2570 } 2571 Asm->emitInt8('\0'); 2572 } 2573 2574 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2575 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2576 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2577 Asm->EmitULEB128(F.getLine()); 2578 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2579 handleMacroNodes(F.getElements(), U); 2580 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2581 } 2582 2583 /// Emit macros into a debug macinfo section. 2584 void DwarfDebug::emitDebugMacinfo() { 2585 if (CUMap.empty()) 2586 return; 2587 2588 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2589 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2590 })) 2591 return; 2592 2593 // Start the dwarf macinfo section. 2594 Asm->OutStreamer->SwitchSection( 2595 Asm->getObjFileLowering().getDwarfMacinfoSection()); 2596 2597 for (const auto &P : CUMap) { 2598 auto &TheCU = *P.second; 2599 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 2600 continue; 2601 auto *SkCU = TheCU.getSkeleton(); 2602 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2603 auto *CUNode = cast<DICompileUnit>(P.first); 2604 DIMacroNodeArray Macros = CUNode->getMacros(); 2605 if (!Macros.empty()) { 2606 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2607 handleMacroNodes(Macros, U); 2608 } 2609 } 2610 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2611 Asm->emitInt8(0); 2612 } 2613 2614 // DWARF5 Experimental Separate Dwarf emitters. 2615 2616 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2617 std::unique_ptr<DwarfCompileUnit> NewU) { 2618 2619 if (!CompilationDir.empty()) 2620 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2621 2622 addGnuPubAttributes(*NewU, Die); 2623 2624 SkeletonHolder.addUnit(std::move(NewU)); 2625 } 2626 2627 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2628 2629 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2630 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2631 DwarfCompileUnit &NewCU = *OwnedUnit; 2632 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2633 2634 NewCU.initStmtList(); 2635 2636 if (useSegmentedStringOffsetsTable()) 2637 NewCU.addStringOffsetsStart(); 2638 2639 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2640 2641 return NewCU; 2642 } 2643 2644 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2645 // compile units that would normally be in debug_info. 2646 void DwarfDebug::emitDebugInfoDWO() { 2647 assert(useSplitDwarf() && "No split dwarf debug info?"); 2648 // Don't emit relocations into the dwo file. 2649 InfoHolder.emitUnits(/* UseOffsets */ true); 2650 } 2651 2652 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2653 // abbreviations for the .debug_info.dwo section. 2654 void DwarfDebug::emitDebugAbbrevDWO() { 2655 assert(useSplitDwarf() && "No split dwarf?"); 2656 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2657 } 2658 2659 void DwarfDebug::emitDebugLineDWO() { 2660 assert(useSplitDwarf() && "No split dwarf?"); 2661 SplitTypeUnitFileTable.Emit( 2662 *Asm->OutStreamer, MCDwarfLineTableParams(), 2663 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2664 } 2665 2666 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2667 assert(useSplitDwarf() && "No split dwarf?"); 2668 InfoHolder.getStringPool().emitStringOffsetsTableHeader( 2669 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(), 2670 InfoHolder.getStringOffsetsStartSym()); 2671 } 2672 2673 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2674 // string section and is identical in format to traditional .debug_str 2675 // sections. 2676 void DwarfDebug::emitDebugStrDWO() { 2677 if (useSegmentedStringOffsetsTable()) 2678 emitStringOffsetsTableHeaderDWO(); 2679 assert(useSplitDwarf() && "No split dwarf?"); 2680 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2681 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2682 OffSec, /* UseRelativeOffsets = */ false); 2683 } 2684 2685 // Emit address pool. 2686 void DwarfDebug::emitDebugAddr() { 2687 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 2688 } 2689 2690 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2691 if (!useSplitDwarf()) 2692 return nullptr; 2693 const DICompileUnit *DIUnit = CU.getCUNode(); 2694 SplitTypeUnitFileTable.maybeSetRootFile( 2695 DIUnit->getDirectory(), DIUnit->getFilename(), 2696 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 2697 return &SplitTypeUnitFileTable; 2698 } 2699 2700 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2701 MD5 Hash; 2702 Hash.update(Identifier); 2703 // ... take the least significant 8 bytes and return those. Our MD5 2704 // implementation always returns its results in little endian, so we actually 2705 // need the "high" word. 2706 MD5::MD5Result Result; 2707 Hash.final(Result); 2708 return Result.high(); 2709 } 2710 2711 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2712 StringRef Identifier, DIE &RefDie, 2713 const DICompositeType *CTy) { 2714 // Fast path if we're building some type units and one has already used the 2715 // address pool we know we're going to throw away all this work anyway, so 2716 // don't bother building dependent types. 2717 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2718 return; 2719 2720 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2721 if (!Ins.second) { 2722 CU.addDIETypeSignature(RefDie, Ins.first->second); 2723 return; 2724 } 2725 2726 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2727 AddrPool.resetUsedFlag(); 2728 2729 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2730 getDwoLineTable(CU)); 2731 DwarfTypeUnit &NewTU = *OwnedUnit; 2732 DIE &UnitDie = NewTU.getUnitDie(); 2733 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2734 2735 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2736 CU.getLanguage()); 2737 2738 uint64_t Signature = makeTypeSignature(Identifier); 2739 NewTU.setTypeSignature(Signature); 2740 Ins.first->second = Signature; 2741 2742 if (useSplitDwarf()) { 2743 MCSection *Section = 2744 getDwarfVersion() <= 4 2745 ? Asm->getObjFileLowering().getDwarfTypesDWOSection() 2746 : Asm->getObjFileLowering().getDwarfInfoDWOSection(); 2747 NewTU.setSection(Section); 2748 } else { 2749 MCSection *Section = 2750 getDwarfVersion() <= 4 2751 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature) 2752 : Asm->getObjFileLowering().getDwarfInfoSection(Signature); 2753 NewTU.setSection(Section); 2754 // Non-split type units reuse the compile unit's line table. 2755 CU.applyStmtList(UnitDie); 2756 } 2757 2758 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2759 // units. 2760 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2761 NewTU.addStringOffsetsStart(); 2762 2763 NewTU.setType(NewTU.createTypeDIE(CTy)); 2764 2765 if (TopLevelType) { 2766 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2767 TypeUnitsUnderConstruction.clear(); 2768 2769 // Types referencing entries in the address table cannot be placed in type 2770 // units. 2771 if (AddrPool.hasBeenUsed()) { 2772 2773 // Remove all the types built while building this type. 2774 // This is pessimistic as some of these types might not be dependent on 2775 // the type that used an address. 2776 for (const auto &TU : TypeUnitsToAdd) 2777 TypeSignatures.erase(TU.second); 2778 2779 // Construct this type in the CU directly. 2780 // This is inefficient because all the dependent types will be rebuilt 2781 // from scratch, including building them in type units, discovering that 2782 // they depend on addresses, throwing them out and rebuilding them. 2783 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2784 return; 2785 } 2786 2787 // If the type wasn't dependent on fission addresses, finish adding the type 2788 // and all its dependent types. 2789 for (auto &TU : TypeUnitsToAdd) { 2790 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2791 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2792 } 2793 } 2794 CU.addDIETypeSignature(RefDie, Signature); 2795 } 2796 2797 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD) 2798 : DD(DD), 2799 TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) { 2800 DD->TypeUnitsUnderConstruction.clear(); 2801 assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed()); 2802 } 2803 2804 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() { 2805 DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction); 2806 DD->AddrPool.resetUsedFlag(); 2807 } 2808 2809 DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() { 2810 return NonTypeUnitContext(this); 2811 } 2812 2813 // Add the Name along with its companion DIE to the appropriate accelerator 2814 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 2815 // AccelTableKind::Apple, we use the table we got as an argument). If 2816 // accelerator tables are disabled, this function does nothing. 2817 template <typename DataT> 2818 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU, 2819 AccelTable<DataT> &AppleAccel, StringRef Name, 2820 const DIE &Die) { 2821 if (getAccelTableKind() == AccelTableKind::None) 2822 return; 2823 2824 if (getAccelTableKind() != AccelTableKind::Apple && 2825 CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default) 2826 return; 2827 2828 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2829 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name); 2830 2831 switch (getAccelTableKind()) { 2832 case AccelTableKind::Apple: 2833 AppleAccel.addName(Ref, Die); 2834 break; 2835 case AccelTableKind::Dwarf: 2836 AccelDebugNames.addName(Ref, Die); 2837 break; 2838 case AccelTableKind::Default: 2839 llvm_unreachable("Default should have already been resolved."); 2840 case AccelTableKind::None: 2841 llvm_unreachable("None handled above"); 2842 } 2843 } 2844 2845 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name, 2846 const DIE &Die) { 2847 addAccelNameImpl(CU, AccelNames, Name, Die); 2848 } 2849 2850 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name, 2851 const DIE &Die) { 2852 // ObjC names go only into the Apple accelerator tables. 2853 if (getAccelTableKind() == AccelTableKind::Apple) 2854 addAccelNameImpl(CU, AccelObjC, Name, Die); 2855 } 2856 2857 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name, 2858 const DIE &Die) { 2859 addAccelNameImpl(CU, AccelNamespace, Name, Die); 2860 } 2861 2862 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name, 2863 const DIE &Die, char Flags) { 2864 addAccelNameImpl(CU, AccelTypes, Name, Die); 2865 } 2866 2867 uint16_t DwarfDebug::getDwarfVersion() const { 2868 return Asm->OutStreamer->getContext().getDwarfVersion(); 2869 } 2870 2871 void DwarfDebug::addSectionLabel(const MCSymbol *Sym) { 2872 SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym)); 2873 } 2874 2875 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) { 2876 return SectionLabels.find(S)->second; 2877 } 2878