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