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