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