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