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