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