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