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