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