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