1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
15 #include "ByteStreamer.h"
17 #include "DebugLocEntry.h"
18 #include "DebugLocStream.h"
19 #include "DwarfCompileUnit.h"
20 #include "DwarfExpression.h"
21 #include "DwarfFile.h"
22 #include "DwarfUnit.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringRef.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/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DebugLoc.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCContext.h"
53 #include "llvm/MC/MCDwarf.h"
54 #include "llvm/MC/MCSection.h"
55 #include "llvm/MC/MCStreamer.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/MC/MCTargetOptions.h"
58 #include "llvm/MC/MachineLocation.h"
59 #include "llvm/MC/SectionKind.h"
60 #include "llvm/Pass.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/MD5.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Timer.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetLoweringObjectFile.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Target/TargetOptions.h"
83 #define DEBUG_TYPE "dwarfdebug"
86 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
87 cl::desc("Disable debug info printing"));
89 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
90 "use-dwarf-ranges-base-address-specifier", cl::Hidden,
91 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
93 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
95 cl::desc("Generate dwarf aranges"),
99 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
100 cl::desc("Generate DWARF4 type units."),
103 static cl::opt<bool> SplitDwarfCrossCuReferences(
104 "split-dwarf-cross-cu-references", cl::Hidden,
105 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
107 enum DefaultOnOff { Default, Enable, Disable };
109 static cl::opt<DefaultOnOff> UnknownLocations(
110 "use-unknown-locations", cl::Hidden,
111 cl::desc("Make an absence of debug location information explicit."),
112 cl::values(clEnumVal(Default, "At top of block or after label"),
113 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
116 static cl::opt<AccelTableKind> AccelTables(
117 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
118 cl::values(clEnumValN(AccelTableKind::Default, "Default",
119 "Default for platform"),
120 clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
121 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
122 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
123 cl::init(AccelTableKind::Default));
125 static cl::opt<DefaultOnOff>
126 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
127 cl::desc("Use inlined strings rather than string section."),
128 cl::values(clEnumVal(Default, "Default for platform"),
129 clEnumVal(Enable, "Enabled"),
130 clEnumVal(Disable, "Disabled")),
134 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
135 cl::desc("Disable emission .debug_ranges section."),
138 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
139 "dwarf-sections-as-references", cl::Hidden,
140 cl::desc("Use sections+offset as references rather than labels."),
141 cl::values(clEnumVal(Default, "Default for platform"),
142 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
145 enum LinkageNameOption {
151 static cl::opt<LinkageNameOption>
152 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
153 cl::desc("Which DWARF linkage-name attributes to emit."),
154 cl::values(clEnumValN(DefaultLinkageNames, "Default",
155 "Default for platform"),
156 clEnumValN(AllLinkageNames, "All", "All"),
157 clEnumValN(AbstractLinkageNames, "Abstract",
158 "Abstract subprograms")),
159 cl::init(DefaultLinkageNames));
161 static const char *const DWARFGroupName = "dwarf";
162 static const char *const DWARFGroupDescription = "DWARF Emission";
163 static const char *const DbgTimerName = "writer";
164 static const char *const DbgTimerDescription = "DWARF Debug Writer";
166 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
168 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
169 : dwarf::OperationEncodingString(Op));
172 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
173 BS.EmitSLEB128(Value, Twine(Value));
176 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
177 BS.EmitULEB128(Value, Twine(Value));
180 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
181 unsigned MachineReg) {
182 // This information is not available while emitting .debug_loc entries.
186 bool DbgVariable::isBlockByrefVariable() const {
187 assert(getVariable() && "Invalid complex DbgVariable!");
188 return getVariable()->getType().resolve()->isBlockByrefStruct();
191 const DIType *DbgVariable::getType() const {
192 DIType *Ty = getVariable()->getType().resolve();
193 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
194 // addresses instead.
195 if (Ty->isBlockByrefStruct()) {
196 /* Byref variables, in Blocks, are declared by the programmer as
197 "SomeType VarName;", but the compiler creates a
198 __Block_byref_x_VarName struct, and gives the variable VarName
199 either the struct, or a pointer to the struct, as its type. This
200 is necessary for various behind-the-scenes things the compiler
201 needs to do with by-reference variables in blocks.
203 However, as far as the original *programmer* is concerned, the
204 variable should still have type 'SomeType', as originally declared.
206 The following function dives into the __Block_byref_x_VarName
207 struct to find the original type of the variable. This will be
208 passed back to the code generating the type for the Debug
209 Information Entry for the variable 'VarName'. 'VarName' will then
210 have the original type 'SomeType' in its debug information.
212 The original type 'SomeType' will be the type of the field named
213 'VarName' inside the __Block_byref_x_VarName struct.
215 NOTE: In order for this to not completely fail on the debugger
216 side, the Debug Information Entry for the variable VarName needs to
217 have a DW_AT_location that tells the debugger how to unwind through
218 the pointers and __Block_byref_x_VarName struct to find the actual
219 value of the variable. The function addBlockByrefType does this. */
220 DIType *subType = Ty;
221 uint16_t tag = Ty->getTag();
223 if (tag == dwarf::DW_TAG_pointer_type)
224 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
226 auto Elements = cast<DICompositeType>(subType)->getElements();
227 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
228 auto *DT = cast<DIDerivedType>(Elements[i]);
229 if (getName() == DT->getName())
230 return resolve(DT->getBaseType());
236 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
237 if (FrameIndexExprs.size() == 1)
238 return FrameIndexExprs;
240 assert(llvm::all_of(FrameIndexExprs,
241 [](const FrameIndexExpr &A) {
242 return A.Expr->isFragment();
244 "multiple FI expressions without DW_OP_LLVM_fragment");
245 llvm::sort(FrameIndexExprs,
246 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
247 return A.Expr->getFragmentInfo()->OffsetInBits <
248 B.Expr->getFragmentInfo()->OffsetInBits;
251 return FrameIndexExprs;
254 void DbgVariable::addMMIEntry(const DbgVariable &V) {
255 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
256 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
257 assert(V.getVariable() == getVariable() && "conflicting variable");
258 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
260 assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
261 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
263 // FIXME: This logic should not be necessary anymore, as we now have proper
264 // deduplication. However, without it, we currently run into the assertion
265 // below, which means that we are likely dealing with broken input, i.e. two
266 // non-fragment entries for the same variable at different frame indices.
267 if (FrameIndexExprs.size()) {
268 auto *Expr = FrameIndexExprs.back().Expr;
269 if (!Expr || !Expr->isFragment())
273 for (const auto &FIE : V.FrameIndexExprs)
274 // Ignore duplicate entries.
275 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
276 return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
278 FrameIndexExprs.push_back(FIE);
280 assert((FrameIndexExprs.size() == 1 ||
281 llvm::all_of(FrameIndexExprs,
282 [](FrameIndexExpr &FIE) {
283 return FIE.Expr && FIE.Expr->isFragment();
285 "conflicting locations for variable");
288 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
289 bool GenerateTypeUnits,
292 // Honor an explicit request.
293 if (AccelTables != AccelTableKind::Default)
296 // Accelerator tables with type units are currently not supported.
297 if (GenerateTypeUnits)
298 return AccelTableKind::None;
300 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
301 // always implies debug_names. For lower standard versions we use apple
302 // accelerator tables on apple platforms and debug_names elsewhere.
303 if (DwarfVersion >= 5)
304 return AccelTableKind::Dwarf;
305 if (Tuning == DebuggerKind::LLDB)
306 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
307 : AccelTableKind::Dwarf;
308 return AccelTableKind::None;
311 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
312 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
313 InfoHolder(A, "info_string", DIEValueAllocator),
314 SkeletonHolder(A, "skel_string", DIEValueAllocator),
315 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
316 const Triple &TT = Asm->TM.getTargetTriple();
318 // Make sure we know our "debugger tuning." The target option takes
319 // precedence; fall back to triple-based defaults.
320 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
321 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
323 DebuggerTuning = DebuggerKind::LLDB;
324 else if (TT.isPS4CPU())
325 DebuggerTuning = DebuggerKind::SCE;
327 DebuggerTuning = DebuggerKind::GDB;
329 if (DwarfInlinedStrings == Default)
330 UseInlineStrings = TT.isNVPTX();
332 UseInlineStrings = DwarfInlinedStrings == Enable;
334 UseLocSection = !TT.isNVPTX();
336 HasAppleExtensionAttributes = tuneForLLDB();
338 // Handle split DWARF.
339 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
341 // SCE defaults to linkage names only for abstract subprograms.
342 if (DwarfLinkageNames == DefaultLinkageNames)
343 UseAllLinkageNames = !tuneForSCE();
345 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
347 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
348 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
349 : MMI->getModule()->getDwarfVersion();
350 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
352 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
354 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
356 // Use sections as references. Force for NVPTX.
357 if (DwarfSectionsAsReferences == Default)
358 UseSectionsAsReferences = TT.isNVPTX();
360 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
362 // Don't generate type units for unsupported object file formats.
364 A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
366 TheAccelTableKind = computeAccelTableKind(
367 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
369 // Work around a GDB bug. GDB doesn't support the standard opcode;
370 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
371 // is defined as of DWARF 3.
372 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
373 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
374 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
376 // GDB does not fully support the DWARF 4 representation for bitfields.
377 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
379 // The DWARF v5 string offsets table has - possibly shared - contributions
380 // from each compile and type unit each preceded by a header. The string
381 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
382 // a monolithic string offsets table without any header.
383 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
385 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
388 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
389 DwarfDebug::~DwarfDebug() = default;
391 static bool isObjCClass(StringRef Name) {
392 return Name.startswith("+") || Name.startswith("-");
395 static bool hasObjCCategory(StringRef Name) {
396 if (!isObjCClass(Name))
399 return Name.find(") ") != StringRef::npos;
402 static void getObjCClassCategory(StringRef In, StringRef &Class,
403 StringRef &Category) {
404 if (!hasObjCCategory(In)) {
405 Class = In.slice(In.find('[') + 1, In.find(' '));
410 Class = In.slice(In.find('[') + 1, In.find('('));
411 Category = In.slice(In.find('[') + 1, In.find(' '));
414 static StringRef getObjCMethodName(StringRef In) {
415 return In.slice(In.find(' ') + 1, In.find(']'));
418 // Add the various names to the Dwarf accelerator table names.
419 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
420 const DISubprogram *SP, DIE &Die) {
421 if (getAccelTableKind() != AccelTableKind::Apple &&
422 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
425 if (!SP->isDefinition())
428 if (SP->getName() != "")
429 addAccelName(CU, SP->getName(), Die);
431 // If the linkage name is different than the name, go ahead and output that as
432 // well into the name table. Only do that if we are going to actually emit
434 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
435 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
436 addAccelName(CU, SP->getLinkageName(), Die);
438 // If this is an Objective-C selector name add it to the ObjC accelerator
440 if (isObjCClass(SP->getName())) {
441 StringRef Class, Category;
442 getObjCClassCategory(SP->getName(), Class, Category);
443 addAccelObjC(CU, Class, Die);
445 addAccelObjC(CU, Category, Die);
446 // Also add the base method name to the name table.
447 addAccelName(CU, getObjCMethodName(SP->getName()), Die);
451 /// Check whether we should create a DIE for the given Scope, return true
452 /// if we don't create a DIE (the corresponding DIE is null).
453 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
454 if (Scope->isAbstractScope())
457 // We don't create a DIE if there is no Range.
458 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
462 if (Ranges.size() > 1)
465 // We don't create a DIE if we have a single Range and the end label
467 return !getLabelAfterInsn(Ranges.front().second);
470 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
472 if (auto *SkelCU = CU.getSkeleton())
473 if (CU.getCUNode()->getSplitDebugInlining())
477 bool DwarfDebug::shareAcrossDWOCUs() const {
478 return SplitDwarfCrossCuReferences;
481 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
482 LexicalScope *Scope) {
483 assert(Scope && Scope->getScopeNode());
484 assert(Scope->isAbstractScope());
485 assert(!Scope->getInlinedAt());
487 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
489 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
490 // was inlined from another compile unit.
491 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
492 // Avoid building the original CU if it won't be used
493 SrcCU.constructAbstractSubprogramScopeDIE(Scope);
495 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
496 if (auto *SkelCU = CU.getSkeleton()) {
497 (shareAcrossDWOCUs() ? CU : SrcCU)
498 .constructAbstractSubprogramScopeDIE(Scope);
499 if (CU.getCUNode()->getSplitDebugInlining())
500 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
502 CU.constructAbstractSubprogramScopeDIE(Scope);
506 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
507 DwarfCompileUnit &CU, DIE &ScopeDIE,
508 const MachineFunction &MF) {
509 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
510 // the subprogram is required to have one.
511 if (!SP.areAllCallsDescribed() || !SP.isDefinition())
514 // Use DW_AT_call_all_calls to express that call site entries are present
515 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
516 // because one of its requirements is not met: call site entries for
517 // optimized-out calls are elided.
518 CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls);
520 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
521 assert(TII && "TargetInstrInfo not found: cannot label tail calls");
523 // Emit call site entries for each call or tail call in the function.
524 for (const MachineBasicBlock &MBB : MF) {
525 for (const MachineInstr &MI : MBB.instrs()) {
526 // Skip instructions which aren't calls. Both calls and tail-calling jump
527 // instructions (e.g TAILJMPd64) are classified correctly here.
531 // TODO: Add support for targets with delay slots (see: beginInstruction).
532 if (MI.hasDelaySlot())
535 // If this is a direct call, find the callee's subprogram.
536 const MachineOperand &CalleeOp = MI.getOperand(0);
537 if (!CalleeOp.isGlobal())
539 const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
540 if (!CalleeDecl || !CalleeDecl->getSubprogram())
543 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
544 // TODO: Add support for indirect calls.
546 bool IsTail = TII->isTailCall(MI);
548 // For tail calls, no return PC information is needed. For regular calls,
549 // the return PC is needed to disambiguate paths in the call graph which
550 // could lead to some target function.
551 const MCExpr *PCOffset =
552 IsTail ? nullptr : getFunctionLocalOffsetAfterInsn(&MI);
554 assert((IsTail || PCOffset) && "Call without return PC information");
555 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
556 << CalleeDecl->getName() << (IsTail ? " [tail]" : "")
558 CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(),
564 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
565 if (!U.hasDwarfPubSections())
568 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
571 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
572 DwarfCompileUnit &NewCU) {
573 DIE &Die = NewCU.getUnitDie();
574 StringRef FN = DIUnit->getFilename();
576 StringRef Producer = DIUnit->getProducer();
577 StringRef Flags = DIUnit->getFlags();
578 if (!Flags.empty() && !useAppleExtensionAttributes()) {
579 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
580 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
582 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
584 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
585 DIUnit->getSourceLanguage());
586 NewCU.addString(Die, dwarf::DW_AT_name, FN);
588 // Add DW_str_offsets_base to the unit DIE, except for split units.
589 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
590 NewCU.addStringOffsetsStart();
592 if (!useSplitDwarf()) {
593 NewCU.initStmtList();
595 // If we're using split dwarf the compilation dir is going to be in the
596 // skeleton CU and so we don't need to duplicate it here.
597 if (!CompilationDir.empty())
598 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
600 addGnuPubAttributes(NewCU, Die);
603 if (useAppleExtensionAttributes()) {
604 if (DIUnit->isOptimized())
605 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
607 StringRef Flags = DIUnit->getFlags();
609 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
611 if (unsigned RVer = DIUnit->getRuntimeVersion())
612 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
613 dwarf::DW_FORM_data1, RVer);
616 if (DIUnit->getDWOId()) {
617 // This CU is either a clang module DWO or a skeleton CU.
618 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
620 if (!DIUnit->getSplitDebugFilename().empty())
621 // This is a prefabricated skeleton CU.
622 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
623 DIUnit->getSplitDebugFilename());
626 // Create new DwarfCompileUnit for the given metadata node with tag
627 // DW_TAG_compile_unit.
629 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
630 if (auto *CU = CUMap.lookup(DIUnit))
633 CompilationDir = DIUnit->getDirectory();
635 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
636 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
637 DwarfCompileUnit &NewCU = *OwnedUnit;
638 InfoHolder.addUnit(std::move(OwnedUnit));
640 for (auto *IE : DIUnit->getImportedEntities())
641 NewCU.addImportedEntity(IE);
643 // LTO with assembly output shares a single line table amongst multiple CUs.
644 // To avoid the compilation directory being ambiguous, let the line table
645 // explicitly describe the directory of all files, never relying on the
646 // compilation directory.
647 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
648 Asm->OutStreamer->emitDwarfFile0Directive(
649 CompilationDir, DIUnit->getFilename(),
650 NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
651 NewCU.getUniqueID());
653 if (useSplitDwarf()) {
654 NewCU.setSkeleton(constructSkeletonCU(NewCU));
655 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
657 finishUnitAttributes(DIUnit, NewCU);
658 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
661 CUMap.insert({DIUnit, &NewCU});
662 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
666 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
667 const DIImportedEntity *N) {
668 if (isa<DILocalScope>(N->getScope()))
670 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
671 D->addChild(TheCU.constructImportedEntityDIE(N));
674 /// Sort and unique GVEs by comparing their fragment offset.
675 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
676 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
678 GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
679 // Sort order: first null exprs, then exprs without fragment
680 // info, then sort by fragment offset in bits.
681 // FIXME: Come up with a more comprehensive comparator so
682 // the sorting isn't non-deterministic, and so the following
683 // std::unique call works correctly.
684 if (!A.Expr || !B.Expr)
686 auto FragmentA = A.Expr->getFragmentInfo();
687 auto FragmentB = B.Expr->getFragmentInfo();
688 if (!FragmentA || !FragmentB)
690 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
692 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
693 [](DwarfCompileUnit::GlobalExpr A,
694 DwarfCompileUnit::GlobalExpr B) {
695 return A.Expr == B.Expr;
701 // Emit all Dwarf sections that should come prior to the content. Create
702 // global DIEs and emit initial debug info sections. This is invoked by
703 // the target AsmPrinter.
704 void DwarfDebug::beginModule() {
705 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
706 DWARFGroupDescription, TimePassesIsEnabled);
707 if (DisableDebugInfoPrinting) {
708 MMI->setDebugInfoAvailability(false);
712 const Module *M = MMI->getModule();
714 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
715 M->debug_compile_units_end());
716 // Tell MMI whether we have debug info.
717 assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
718 "DebugInfoAvailabilty initialized unexpectedly");
719 SingleCU = NumDebugCUs == 1;
720 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
722 for (const GlobalVariable &Global : M->globals()) {
723 SmallVector<DIGlobalVariableExpression *, 1> GVs;
724 Global.getDebugInfo(GVs);
725 for (auto *GVE : GVs)
726 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
729 // Create the symbol that designates the start of the unit's contribution
730 // to the string offsets table. In a split DWARF scenario, only the skeleton
731 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
732 if (useSegmentedStringOffsetsTable())
733 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
734 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
737 // Create the symbols that designates the start of the DWARF v5 range list
738 // and locations list tables. They are located past the table headers.
739 if (getDwarfVersion() >= 5) {
740 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
741 Holder.setRnglistsTableBaseSym(
742 Asm->createTempSymbol("rnglists_table_base"));
743 Holder.setLoclistsTableBaseSym(
744 Asm->createTempSymbol("loclists_table_base"));
747 InfoHolder.setRnglistsTableBaseSym(
748 Asm->createTempSymbol("rnglists_dwo_table_base"));
751 // Create the symbol that points to the first entry following the debug
752 // address table (.debug_addr) header.
753 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
755 for (DICompileUnit *CUNode : M->debug_compile_units()) {
756 // FIXME: Move local imported entities into a list attached to the
757 // subprogram, then this search won't be needed and a
758 // getImportedEntities().empty() test should go below with the rest.
759 bool HasNonLocalImportedEntities = llvm::any_of(
760 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
761 return !isa<DILocalScope>(IE->getScope());
764 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
765 CUNode->getRetainedTypes().empty() &&
766 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
769 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
772 for (auto *GVE : CUNode->getGlobalVariables()) {
773 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
774 // already know about the variable and it isn't adding a constant
776 auto &GVMapEntry = GVMap[GVE->getVariable()];
777 auto *Expr = GVE->getExpression();
778 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
779 GVMapEntry.push_back({nullptr, Expr});
781 DenseSet<DIGlobalVariable *> Processed;
782 for (auto *GVE : CUNode->getGlobalVariables()) {
783 DIGlobalVariable *GV = GVE->getVariable();
784 if (Processed.insert(GV).second)
785 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
788 for (auto *Ty : CUNode->getEnumTypes()) {
789 // The enum types array by design contains pointers to
790 // MDNodes rather than DIRefs. Unique them here.
791 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
793 for (auto *Ty : CUNode->getRetainedTypes()) {
794 // The retained types array by design contains pointers to
795 // MDNodes rather than DIRefs. Unique them here.
796 if (DIType *RT = dyn_cast<DIType>(Ty))
797 // There is no point in force-emitting a forward declaration.
798 CU.getOrCreateTypeDIE(RT);
800 // Emit imported_modules last so that the relevant context is already
802 for (auto *IE : CUNode->getImportedEntities())
803 constructAndAddImportedEntityDIE(CU, IE);
807 void DwarfDebug::finishEntityDefinitions() {
808 for (const auto &Entity : ConcreteEntities) {
809 DIE *Die = Entity->getDIE();
811 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
812 // in the ConcreteEntities list, rather than looking it up again here.
813 // DIE::getUnit isn't simple - it walks parent pointers, etc.
814 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
816 Unit->finishEntityDefinition(Entity.get());
820 void DwarfDebug::finishSubprogramDefinitions() {
821 for (const DISubprogram *SP : ProcessedSPNodes) {
822 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
824 getOrCreateDwarfCompileUnit(SP->getUnit()),
825 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
829 void DwarfDebug::finalizeModuleInfo() {
830 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
832 finishSubprogramDefinitions();
834 finishEntityDefinitions();
836 // Include the DWO file name in the hash if there's more than one CU.
837 // This handles ThinLTO's situation where imported CUs may very easily be
838 // duplicate with the same CU partially imported into another ThinLTO unit.
840 if (CUMap.size() > 1)
841 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
843 // Handle anything that needs to be done on a per-unit basis after
844 // all other generation.
845 for (const auto &P : CUMap) {
846 auto &TheCU = *P.second;
847 if (TheCU.getCUNode()->isDebugDirectivesOnly())
849 // Emit DW_AT_containing_type attribute to connect types with their
850 // vtable holding type.
851 TheCU.constructContainingTypeDIEs();
853 // Add CU specific attributes if we need to add any.
854 // If we're splitting the dwarf out now that we've got the entire
855 // CU then add the dwo id to it.
856 auto *SkCU = TheCU.getSkeleton();
857 if (useSplitDwarf() && !empty(TheCU.getUnitDie().children())) {
858 finishUnitAttributes(TheCU.getCUNode(), TheCU);
859 TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
860 Asm->TM.Options.MCOptions.SplitDwarfFile);
861 SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
862 Asm->TM.Options.MCOptions.SplitDwarfFile);
863 // Emit a unique identifier for this CU.
865 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
866 if (getDwarfVersion() >= 5) {
870 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
871 dwarf::DW_FORM_data8, ID);
872 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
873 dwarf::DW_FORM_data8, ID);
876 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
877 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
878 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
882 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
885 // If we have code split among multiple sections or non-contiguous
886 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
887 // remain in the .o file, otherwise add a DW_AT_low_pc.
888 // FIXME: We should use ranges allow reordering of code ala
889 // .subsections_via_symbols in mach-o. This would mean turning on
890 // ranges for all subprogram DIEs for mach-o.
891 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
893 // We don't keep track of which addresses are used in which CU so this
894 // is a bit pessimistic under LTO.
895 if (!AddrPool.isEmpty() &&
896 (getDwarfVersion() >= 5 ||
897 (SkCU && !empty(TheCU.getUnitDie().children()))))
898 U.addAddrTableBase();
900 if (unsigned NumRanges = TheCU.getRanges().size()) {
901 if (NumRanges > 1 && useRangesSection())
902 // A DW_AT_low_pc attribute may also be specified in combination with
903 // DW_AT_ranges to specify the default base address for use in
904 // location lists (see Section 2.6.2) and range lists (see Section
906 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
908 U.setBaseAddress(TheCU.getRanges().front().getStart());
909 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
912 if (getDwarfVersion() >= 5) {
913 if (U.hasRangeLists())
916 if (!DebugLocs.getLists().empty() && !useSplitDwarf())
920 auto *CUNode = cast<DICompileUnit>(P.first);
921 // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
922 if (CUNode->getMacros())
923 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
924 U.getMacroLabelBegin(),
925 TLOF.getDwarfMacinfoSection()->getBeginSymbol());
928 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
929 for (auto *CUNode : MMI->getModule()->debug_compile_units())
930 if (CUNode->getDWOId())
931 getOrCreateDwarfCompileUnit(CUNode);
933 // Compute DIE offsets and sizes.
934 InfoHolder.computeSizeAndOffsets();
936 SkeletonHolder.computeSizeAndOffsets();
939 // Emit all Dwarf sections that should come after the content.
940 void DwarfDebug::endModule() {
941 assert(CurFn == nullptr);
942 assert(CurMI == nullptr);
944 // If we aren't actually generating debug info (check beginModule -
945 // conditionalized on !DisableDebugInfoPrinting and the presence of the
946 // llvm.dbg.cu metadata node)
947 if (!MMI->hasDebugInfo())
950 // Finalize the debug info for the module.
951 finalizeModuleInfo();
958 // Emit info into a debug loc section.
961 // Corresponding abbreviations into a abbrev section.
964 // Emit all the DIEs into a debug info section.
967 // Emit info into a debug aranges section.
968 if (GenerateARangeSection)
971 // Emit info into a debug ranges section.
974 // Emit info into a debug macinfo section.
977 if (useSplitDwarf()) {
980 emitDebugAbbrevDWO();
982 emitDebugRangesDWO();
987 // Emit info into the dwarf accelerator table sections.
988 switch (getAccelTableKind()) {
989 case AccelTableKind::Apple:
992 emitAccelNamespaces();
995 case AccelTableKind::Dwarf:
996 emitAccelDebugNames();
998 case AccelTableKind::None:
1000 case AccelTableKind::Default:
1001 llvm_unreachable("Default should have already been resolved.");
1004 // Emit the pubnames and pubtypes sections if requested.
1005 emitDebugPubSections();
1008 // FIXME: AbstractVariables.clear();
1011 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1013 const MDNode *ScopeNode) {
1014 if (CU.getExistingAbstractEntity(Node))
1017 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1018 cast<DILocalScope>(ScopeNode)));
1021 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1022 const DINode *Node, const MDNode *ScopeNode) {
1023 if (CU.getExistingAbstractEntity(Node))
1026 if (LexicalScope *Scope =
1027 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1028 CU.createAbstractEntity(Node, Scope);
1031 // Collect variable information from side table maintained by MF.
1032 void DwarfDebug::collectVariableInfoFromMFTable(
1033 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1034 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1035 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1038 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1039 "Expected inlined-at fields to agree");
1041 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1042 Processed.insert(Var);
1043 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1045 // If variable scope is not found then skip this variable.
1049 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1050 auto RegVar = llvm::make_unique<DbgVariable>(
1051 cast<DILocalVariable>(Var.first), Var.second);
1052 RegVar->initializeMMI(VI.Expr, VI.Slot);
1053 if (DbgVariable *DbgVar = MFVars.lookup(Var))
1054 DbgVar->addMMIEntry(*RegVar);
1055 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1056 MFVars.insert({Var, RegVar.get()});
1057 ConcreteEntities.push_back(std::move(RegVar));
1062 // Get .debug_loc entry for the instruction range starting at MI.
1063 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1064 const DIExpression *Expr = MI->getDebugExpression();
1065 assert(MI->getNumOperands() == 4);
1066 if (MI->getOperand(0).isReg()) {
1067 auto RegOp = MI->getOperand(0);
1068 auto Op1 = MI->getOperand(1);
1069 // If the second operand is an immediate, this is a
1070 // register-indirect address.
1071 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
1072 MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
1073 return DebugLocEntry::Value(Expr, MLoc);
1075 if (MI->getOperand(0).isImm())
1076 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
1077 if (MI->getOperand(0).isFPImm())
1078 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
1079 if (MI->getOperand(0).isCImm())
1080 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
1082 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1085 /// If this and Next are describing different fragments of the same
1086 /// variable, merge them by appending Next's values to the current
1088 /// Return true if the merge was successful.
1089 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
1090 if (Begin == Next.Begin) {
1091 auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
1092 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
1093 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
1096 // We can only merge entries if none of the fragments overlap any others.
1097 // In doing so, we can take advantage of the fact that both lists are
1099 for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
1100 for (; j < Next.Values.size(); ++j) {
1101 int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp(
1102 cast<DIExpression>(Next.Values[j].Expression));
1103 if (res == 0) // The two expressions overlap, we can't merge.
1105 // Values[i] is entirely before Next.Values[j],
1106 // so go back to the next entry of Values.
1109 // Next.Values[j] is entirely before Values[i], so go on to the
1110 // next entry of Next.Values.
1114 addValues(Next.Values);
1121 /// Build the location list for all DBG_VALUEs in the function that
1122 /// describe the same variable. If the ranges of several independent
1123 /// fragments of the same variable overlap partially, split them up and
1124 /// combine the ranges. The resulting DebugLocEntries are will have
1125 /// strict monotonically increasing begin addresses and will never
1130 // Ranges History [var, loc, fragment ofs size]
1131 // 0 | [x, (reg0, fragment 0, 32)]
1132 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
1134 // 3 | [clobber reg0]
1135 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
1140 // [0-1] [x, (reg0, fragment 0, 32)]
1141 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1142 // [3-4] [x, (reg1, fragment 32, 32)]
1143 // [4- ] [x, (mem, fragment 0, 64)]
1145 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1146 const DbgValueHistoryMap::InstrRanges &Ranges) {
1147 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1149 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1150 const MachineInstr *Begin = I->first;
1151 const MachineInstr *End = I->second;
1152 assert(Begin->isDebugValue() && "Invalid History entry");
1154 // Check if a variable is inaccessible in this range.
1155 if (Begin->getNumOperands() > 1 &&
1156 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1161 // If this fragment overlaps with any open ranges, truncate them.
1162 const DIExpression *DIExpr = Begin->getDebugExpression();
1163 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
1164 return DIExpr->fragmentsOverlap(R.getExpression());
1166 OpenRanges.erase(Last, OpenRanges.end());
1168 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1169 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1171 const MCSymbol *EndLabel;
1173 EndLabel = getLabelAfterInsn(End);
1174 else if (std::next(I) == Ranges.end())
1175 EndLabel = Asm->getFunctionEnd();
1177 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1178 assert(EndLabel && "Forgot label after instruction ending a range!");
1180 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1182 auto Value = getDebugLocValue(Begin);
1184 // Omit entries with empty ranges as they do not have any effect in DWARF.
1185 if (StartLabel == EndLabel) {
1186 // If this is a fragment, we must still add the value to the list of
1187 // open ranges, since it may describe non-overlapping parts of the
1189 if (DIExpr->isFragment())
1190 OpenRanges.push_back(Value);
1191 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1195 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1196 bool couldMerge = false;
1198 // If this is a fragment, it may belong to the current DebugLocEntry.
1199 if (DIExpr->isFragment()) {
1200 // Add this value to the list of open ranges.
1201 OpenRanges.push_back(Value);
1203 // Attempt to add the fragment to the last entry.
1204 if (!DebugLoc.empty())
1205 if (DebugLoc.back().MergeValues(Loc))
1210 // Need to add a new DebugLocEntry. Add all values from still
1211 // valid non-overlapping fragments.
1212 if (OpenRanges.size())
1213 Loc.addValues(OpenRanges);
1215 DebugLoc.push_back(std::move(Loc));
1218 // Attempt to coalesce the ranges of two otherwise identical
1220 auto CurEntry = DebugLoc.rbegin();
1222 dbgs() << CurEntry->getValues().size() << " Values:\n";
1223 for (auto &Value : CurEntry->getValues())
1225 dbgs() << "-----\n";
1228 auto PrevEntry = std::next(CurEntry);
1229 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1230 DebugLoc.pop_back();
1234 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1235 LexicalScope &Scope,
1237 const DILocation *Location,
1238 const MCSymbol *Sym) {
1239 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1240 if (isa<const DILocalVariable>(Node)) {
1241 ConcreteEntities.push_back(
1242 llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1244 InfoHolder.addScopeVariable(&Scope,
1245 cast<DbgVariable>(ConcreteEntities.back().get()));
1246 } else if (isa<const DILabel>(Node)) {
1247 ConcreteEntities.push_back(
1248 llvm::make_unique<DbgLabel>(cast<const DILabel>(Node),
1250 InfoHolder.addScopeLabel(&Scope,
1251 cast<DbgLabel>(ConcreteEntities.back().get()));
1253 return ConcreteEntities.back().get();
1256 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1257 /// enclosing lexical scope. The check ensures there are no other instructions
1258 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1259 /// either open or otherwise rolls off the end of the scope.
1260 static bool validThroughout(LexicalScopes &LScopes,
1261 const MachineInstr *DbgValue,
1262 const MachineInstr *RangeEnd) {
1263 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1264 auto MBB = DbgValue->getParent();
1265 auto DL = DbgValue->getDebugLoc();
1266 auto *LScope = LScopes.findLexicalScope(DL);
1267 // Scope doesn't exist; this is a dead DBG_VALUE.
1270 auto &LSRange = LScope->getRanges();
1271 if (LSRange.size() == 0)
1274 // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1275 const MachineInstr *LScopeBegin = LSRange.front().first;
1276 // Early exit if the lexical scope begins outside of the current block.
1277 if (LScopeBegin->getParent() != MBB)
1279 MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1280 for (++Pred; Pred != MBB->rend(); ++Pred) {
1281 if (Pred->getFlag(MachineInstr::FrameSetup))
1283 auto PredDL = Pred->getDebugLoc();
1284 if (!PredDL || Pred->isMetaInstruction())
1286 // Check whether the instruction preceding the DBG_VALUE is in the same
1287 // (sub)scope as the DBG_VALUE.
1288 if (DL->getScope() == PredDL->getScope())
1290 auto *PredScope = LScopes.findLexicalScope(PredDL);
1291 if (!PredScope || LScope->dominates(PredScope))
1295 // If the range of the DBG_VALUE is open-ended, report success.
1299 // Fail if there are instructions belonging to our scope in another block.
1300 const MachineInstr *LScopeEnd = LSRange.back().second;
1301 if (LScopeEnd->getParent() != MBB)
1304 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1305 // throughout the function. This is a hack, presumably for DWARF v2 and not
1306 // necessarily correct. It would be much better to use a dbg.declare instead
1307 // if we know the constant is live throughout the scope.
1308 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1314 // Find variables for each lexical scope.
1315 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1316 const DISubprogram *SP,
1317 DenseSet<InlinedEntity> &Processed) {
1318 // Grab the variable info that was squirreled away in the MMI side-table.
1319 collectVariableInfoFromMFTable(TheCU, Processed);
1321 for (const auto &I : DbgValues) {
1322 InlinedEntity IV = I.first;
1323 if (Processed.count(IV))
1326 // Instruction ranges, specifying where IV is accessible.
1327 const auto &Ranges = I.second;
1331 LexicalScope *Scope = nullptr;
1332 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1333 if (const DILocation *IA = IV.second)
1334 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1336 Scope = LScopes.findLexicalScope(LocalVar->getScope());
1337 // If variable scope is not found then skip this variable.
1341 Processed.insert(IV);
1342 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1343 *Scope, LocalVar, IV.second));
1345 const MachineInstr *MInsn = Ranges.front().first;
1346 assert(MInsn->isDebugValue() && "History must begin with debug value");
1348 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1349 if (Ranges.size() == 1 &&
1350 validThroughout(LScopes, MInsn, Ranges.front().second)) {
1351 RegVar->initializeDbgValue(MInsn);
1354 // Do not emit location lists if .debug_loc secton is disabled.
1355 if (!useLocSection())
1358 // Handle multiple DBG_VALUE instructions describing one variable.
1359 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1361 // Build the location list for this variable.
1362 SmallVector<DebugLocEntry, 8> Entries;
1363 buildLocationList(Entries, Ranges);
1365 // If the variable has a DIBasicType, extract it. Basic types cannot have
1366 // unique identifiers, so don't bother resolving the type with the
1368 const DIBasicType *BT = dyn_cast<DIBasicType>(
1369 static_cast<const Metadata *>(LocalVar->getType()));
1371 // Finalize the entry by lowering it into a DWARF bytestream.
1372 for (auto &Entry : Entries)
1373 Entry.finalize(*Asm, List, BT);
1376 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1377 // DWARF-related DbgLabel.
1378 for (const auto &I : DbgLabels) {
1379 InlinedEntity IL = I.first;
1380 const MachineInstr *MI = I.second;
1384 LexicalScope *Scope = nullptr;
1385 const DILabel *Label = cast<DILabel>(IL.first);
1386 // Get inlined DILocation if it is inlined label.
1387 if (const DILocation *IA = IL.second)
1388 Scope = LScopes.findInlinedScope(Label->getScope(), IA);
1390 Scope = LScopes.findLexicalScope(Label->getScope());
1391 // If label scope is not found then skip this label.
1395 Processed.insert(IL);
1396 /// At this point, the temporary label is created.
1397 /// Save the temporary label to DbgLabel entity to get the
1398 /// actually address when generating Dwarf DIE.
1399 MCSymbol *Sym = getLabelBeforeInsn(MI);
1400 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1403 // Collect info for variables/labels that were optimized out.
1404 for (const DINode *DN : SP->getRetainedNodes()) {
1405 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1407 LexicalScope *Scope = nullptr;
1408 if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1409 Scope = LScopes.findLexicalScope(DV->getScope());
1410 } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1411 Scope = LScopes.findLexicalScope(DL->getScope());
1415 createConcreteEntity(TheCU, *Scope, DN, nullptr);
1419 // Process beginning of an instruction.
1420 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1421 DebugHandlerBase::beginInstruction(MI);
1424 const auto *SP = MI->getMF()->getFunction().getSubprogram();
1425 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1428 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1429 // If the instruction is part of the function frame setup code, do not emit
1430 // any line record, as there is no correspondence with any user code.
1431 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1433 const DebugLoc &DL = MI->getDebugLoc();
1434 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1435 // the last line number actually emitted, to see if it was line 0.
1436 unsigned LastAsmLine =
1437 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1439 // Request a label after the call in order to emit AT_return_pc information
1440 // in call site entries. TODO: Add support for targets with delay slots.
1441 if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1442 requestLabelAfterInsn(MI);
1444 if (DL == PrevInstLoc) {
1445 // If we have an ongoing unspecified location, nothing to do here.
1448 // We have an explicit location, same as the previous location.
1449 // But we might be coming back to it after a line 0 record.
1450 if (LastAsmLine == 0 && DL.getLine() != 0) {
1451 // Reinstate the source location but not marked as a statement.
1452 const MDNode *Scope = DL.getScope();
1453 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1459 // We have an unspecified location, which might want to be line 0.
1460 // If we have already emitted a line-0 record, don't repeat it.
1461 if (LastAsmLine == 0)
1463 // If user said Don't Do That, don't do that.
1464 if (UnknownLocations == Disable)
1466 // See if we have a reason to emit a line-0 record now.
1467 // Reasons to emit a line-0 record include:
1468 // - User asked for it (UnknownLocations).
1469 // - Instruction has a label, so it's referenced from somewhere else,
1470 // possibly debug information; we want it to have a source location.
1471 // - Instruction is at the top of a block; we don't want to inherit the
1472 // location from the physically previous (maybe unrelated) block.
1473 if (UnknownLocations == Enable || PrevLabel ||
1474 (PrevInstBB && PrevInstBB != MI->getParent())) {
1475 // Preserve the file and column numbers, if we can, to save space in
1476 // the encoded line table.
1477 // Do not update PrevInstLoc, it remembers the last non-0 line.
1478 const MDNode *Scope = nullptr;
1479 unsigned Column = 0;
1481 Scope = PrevInstLoc.getScope();
1482 Column = PrevInstLoc.getCol();
1484 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1489 // We have an explicit location, different from the previous location.
1490 // Don't repeat a line-0 record, but otherwise emit the new location.
1491 // (The new location might be an explicit line 0, which we do emit.)
1492 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
1495 if (DL == PrologEndLoc) {
1496 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1497 PrologEndLoc = DebugLoc();
1499 // If the line changed, we call that a new statement; unless we went to
1500 // line 0 and came back, in which case it is not a new statement.
1501 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1502 if (DL.getLine() && DL.getLine() != OldLine)
1503 Flags |= DWARF2_FLAG_IS_STMT;
1505 const MDNode *Scope = DL.getScope();
1506 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1508 // If we're not at line 0, remember this location.
1513 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1514 // First known non-DBG_VALUE and non-frame setup location marks
1515 // the beginning of the function body.
1516 for (const auto &MBB : *MF)
1517 for (const auto &MI : MBB)
1518 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1520 return MI.getDebugLoc();
1524 // Gather pre-function debug information. Assumes being called immediately
1525 // after the function entry point has been emitted.
1526 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1529 auto *SP = MF->getFunction().getSubprogram();
1530 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1531 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1534 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1536 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1537 // belongs to so that we add to the correct per-cu line table in the
1539 if (Asm->OutStreamer->hasRawTextSupport())
1540 // Use a single line table if we are generating assembly.
1541 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1543 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1545 // Record beginning of function.
1546 PrologEndLoc = findPrologueEndLoc(MF);
1548 // We'd like to list the prologue as "not statements" but GDB behaves
1549 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1550 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1551 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1555 void DwarfDebug::skippedNonDebugFunction() {
1556 // If we don't have a subprogram for this function then there will be a hole
1557 // in the range information. Keep note of this by setting the previously used
1558 // section to nullptr.
1563 // Gather and emit post-function debug information.
1564 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1565 const DISubprogram *SP = MF->getFunction().getSubprogram();
1567 assert(CurFn == MF &&
1568 "endFunction should be called with the same function as beginFunction");
1570 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1571 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1573 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1574 assert(!FnScope || SP == FnScope->getScopeNode());
1575 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1576 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1577 PrevLabel = nullptr;
1582 DenseSet<InlinedEntity> Processed;
1583 collectEntityInfo(TheCU, SP, Processed);
1585 // Add the range of this function to the list of ranges for the CU.
1586 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1588 // Under -gmlt, skip building the subprogram if there are no inlined
1589 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1590 // is still needed as we need its source location.
1591 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1592 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1593 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1594 assert(InfoHolder.getScopeVariables().empty());
1595 PrevLabel = nullptr;
1601 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1603 // Construct abstract scopes.
1604 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1605 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1606 for (const DINode *DN : SP->getRetainedNodes()) {
1607 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1610 const MDNode *Scope = nullptr;
1611 if (auto *DV = dyn_cast<DILocalVariable>(DN))
1612 Scope = DV->getScope();
1613 else if (auto *DL = dyn_cast<DILabel>(DN))
1614 Scope = DL->getScope();
1616 llvm_unreachable("Unexpected DI type!");
1618 // Collect info for variables/labels that were optimized out.
1619 ensureAbstractEntityIsCreated(TheCU, DN, Scope);
1620 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1621 && "ensureAbstractEntityIsCreated inserted abstract scopes");
1623 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1626 ProcessedSPNodes.insert(SP);
1627 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
1628 if (auto *SkelCU = TheCU.getSkeleton())
1629 if (!LScopes.getAbstractScopesList().empty() &&
1630 TheCU.getCUNode()->getSplitDebugInlining())
1631 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1633 // Construct call site entries.
1634 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
1637 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1638 // DbgVariables except those that are also in AbstractVariables (since they
1639 // can be used cross-function)
1640 InfoHolder.getScopeVariables().clear();
1641 InfoHolder.getScopeLabels().clear();
1642 PrevLabel = nullptr;
1646 // Register a source line with debug info. Returns the unique label that was
1647 // emitted and which provides correspondence to the source line list.
1648 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1651 unsigned FileNo = 1;
1652 unsigned Discriminator = 0;
1653 if (auto *Scope = cast_or_null<DIScope>(S)) {
1654 Fn = Scope->getFilename();
1655 if (Line != 0 && getDwarfVersion() >= 4)
1656 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1657 Discriminator = LBF->getDiscriminator();
1659 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1660 FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1661 .getOrCreateSourceID(Scope->getFile());
1663 Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1667 //===----------------------------------------------------------------------===//
1669 //===----------------------------------------------------------------------===//
1671 // Emit the debug info section.
1672 void DwarfDebug::emitDebugInfo() {
1673 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1674 Holder.emitUnits(/* UseOffsets */ false);
1677 // Emit the abbreviation section.
1678 void DwarfDebug::emitAbbreviations() {
1679 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1681 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1684 void DwarfDebug::emitStringOffsetsTableHeader() {
1685 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1686 Holder.getStringPool().emitStringOffsetsTableHeader(
1687 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
1688 Holder.getStringOffsetsStartSym());
1691 template <typename AccelTableT>
1692 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1693 StringRef TableName) {
1694 Asm->OutStreamer->SwitchSection(Section);
1696 // Emit the full data.
1697 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1700 void DwarfDebug::emitAccelDebugNames() {
1701 // Don't emit anything if we have no compilation units to index.
1702 if (getUnits().empty())
1705 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1708 // Emit visible names into a hashed accelerator table section.
1709 void DwarfDebug::emitAccelNames() {
1710 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1714 // Emit objective C classes and categories into a hashed accelerator table
1716 void DwarfDebug::emitAccelObjC() {
1717 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1721 // Emit namespace dies into a hashed accelerator table.
1722 void DwarfDebug::emitAccelNamespaces() {
1723 emitAccel(AccelNamespace,
1724 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1728 // Emit type dies into a hashed accelerator table.
1729 void DwarfDebug::emitAccelTypes() {
1730 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1734 // Public name handling.
1735 // The format for the various pubnames:
1737 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1738 // for the DIE that is named.
1740 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1741 // into the CU and the index value is computed according to the type of value
1742 // for the DIE that is named.
1744 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1745 // it's the offset within the debug_info/debug_types dwo section, however, the
1746 // reference in the pubname header doesn't change.
1748 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1749 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1751 // Entities that ended up only in a Type Unit reference the CU instead (since
1752 // the pub entry has offsets within the CU there's no real offset that can be
1753 // provided anyway). As it happens all such entities (namespaces and types,
1754 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1755 // not to be true it would be necessary to persist this information from the
1756 // point at which the entry is added to the index data structure - since by
1757 // the time the index is built from that, the original type/namespace DIE in a
1758 // type unit has already been destroyed so it can't be queried for properties
1760 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1761 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1762 dwarf::GIEL_EXTERNAL);
1763 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1765 // We could have a specification DIE that has our most of our knowledge,
1766 // look for that now.
1767 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1768 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1769 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1770 Linkage = dwarf::GIEL_EXTERNAL;
1771 } else if (Die->findAttribute(dwarf::DW_AT_external))
1772 Linkage = dwarf::GIEL_EXTERNAL;
1774 switch (Die->getTag()) {
1775 case dwarf::DW_TAG_class_type:
1776 case dwarf::DW_TAG_structure_type:
1777 case dwarf::DW_TAG_union_type:
1778 case dwarf::DW_TAG_enumeration_type:
1779 return dwarf::PubIndexEntryDescriptor(
1780 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1781 ? dwarf::GIEL_STATIC
1782 : dwarf::GIEL_EXTERNAL);
1783 case dwarf::DW_TAG_typedef:
1784 case dwarf::DW_TAG_base_type:
1785 case dwarf::DW_TAG_subrange_type:
1786 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1787 case dwarf::DW_TAG_namespace:
1788 return dwarf::GIEK_TYPE;
1789 case dwarf::DW_TAG_subprogram:
1790 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1791 case dwarf::DW_TAG_variable:
1792 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1793 case dwarf::DW_TAG_enumerator:
1794 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1795 dwarf::GIEL_STATIC);
1797 return dwarf::GIEK_NONE;
1801 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
1802 /// pubtypes sections.
1803 void DwarfDebug::emitDebugPubSections() {
1804 for (const auto &NU : CUMap) {
1805 DwarfCompileUnit *TheU = NU.second;
1806 if (!TheU->hasDwarfPubSections())
1809 bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
1810 DICompileUnit::DebugNameTableKind::GNU;
1812 Asm->OutStreamer->SwitchSection(
1813 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1814 : Asm->getObjFileLowering().getDwarfPubNamesSection());
1815 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
1817 Asm->OutStreamer->SwitchSection(
1818 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1819 : Asm->getObjFileLowering().getDwarfPubTypesSection());
1820 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
1824 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
1825 if (useSectionsAsReferences())
1826 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
1827 CU.getDebugSectionOffset());
1829 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
1832 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1833 DwarfCompileUnit *TheU,
1834 const StringMap<const DIE *> &Globals) {
1835 if (auto *Skeleton = TheU->getSkeleton())
1839 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1840 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1841 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1842 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1844 Asm->OutStreamer->EmitLabel(BeginLabel);
1846 Asm->OutStreamer->AddComment("DWARF Version");
1847 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
1849 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1850 emitSectionReference(*TheU);
1852 Asm->OutStreamer->AddComment("Compilation Unit Length");
1853 Asm->emitInt32(TheU->getLength());
1855 // Emit the pubnames for this compilation unit.
1856 for (const auto &GI : Globals) {
1857 const char *Name = GI.getKeyData();
1858 const DIE *Entity = GI.second;
1860 Asm->OutStreamer->AddComment("DIE offset");
1861 Asm->emitInt32(Entity->getOffset());
1864 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1865 Asm->OutStreamer->AddComment(
1866 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
1867 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1868 Asm->emitInt8(Desc.toBits());
1871 Asm->OutStreamer->AddComment("External Name");
1872 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1875 Asm->OutStreamer->AddComment("End Mark");
1877 Asm->OutStreamer->EmitLabel(EndLabel);
1880 /// Emit null-terminated strings into a debug str section.
1881 void DwarfDebug::emitDebugStr() {
1882 MCSection *StringOffsetsSection = nullptr;
1883 if (useSegmentedStringOffsetsTable()) {
1884 emitStringOffsetsTableHeader();
1885 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1887 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1888 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
1889 StringOffsetsSection, /* UseRelativeOffsets = */ true);
1892 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1893 const DebugLocStream::Entry &Entry) {
1894 auto &&Comments = DebugLocs.getComments(Entry);
1895 auto Comment = Comments.begin();
1896 auto End = Comments.end();
1897 for (uint8_t Byte : DebugLocs.getBytes(Entry))
1898 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1901 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1902 const DebugLocEntry::Value &Value,
1903 DwarfExpression &DwarfExpr) {
1904 auto *DIExpr = Value.getExpression();
1905 DIExpressionCursor ExprCursor(DIExpr);
1906 DwarfExpr.addFragmentOffset(DIExpr);
1908 if (Value.isInt()) {
1909 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1910 BT->getEncoding() == dwarf::DW_ATE_signed_char))
1911 DwarfExpr.addSignedConstant(Value.getInt());
1913 DwarfExpr.addUnsignedConstant(Value.getInt());
1914 } else if (Value.isLocation()) {
1915 MachineLocation Location = Value.getLoc();
1916 if (Location.isIndirect())
1917 DwarfExpr.setMemoryLocationKind();
1918 DIExpressionCursor Cursor(DIExpr);
1919 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1920 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1922 return DwarfExpr.addExpression(std::move(Cursor));
1923 } else if (Value.isConstantFP()) {
1924 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1925 DwarfExpr.addUnsignedConstant(RawBytes);
1927 DwarfExpr.addExpression(std::move(ExprCursor));
1930 void DebugLocEntry::finalize(const AsmPrinter &AP,
1931 DebugLocStream::ListBuilder &List,
1932 const DIBasicType *BT) {
1933 assert(Begin != End && "unexpected location list entry with empty range");
1934 DebugLocStream::EntryBuilder Entry(List, Begin, End);
1935 BufferByteStreamer Streamer = Entry.getStreamer();
1936 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
1937 const DebugLocEntry::Value &Value = Values[0];
1938 if (Value.isFragment()) {
1939 // Emit all fragments that belong to the same variable and range.
1940 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
1941 return P.isFragment();
1942 }) && "all values are expected to be fragments");
1943 assert(std::is_sorted(Values.begin(), Values.end()) &&
1944 "fragments are expected to be sorted");
1946 for (auto Fragment : Values)
1947 emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
1950 assert(Values.size() == 1 && "only fragments may have >1 value");
1951 emitDebugLocValue(AP, BT, Value, DwarfExpr);
1953 DwarfExpr.finalize();
1956 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1958 Asm->OutStreamer->AddComment("Loc expr size");
1959 if (getDwarfVersion() >= 5)
1960 Asm->EmitULEB128(DebugLocs.getBytes(Entry).size());
1962 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
1964 APByteStreamer Streamer(*Asm);
1965 emitDebugLocEntry(Streamer, Entry);
1968 // Emit the common part of the DWARF 5 range/locations list tables header.
1969 static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder,
1970 MCSymbol *TableStart,
1971 MCSymbol *TableEnd) {
1972 // Build the table header, which starts with the length field.
1973 Asm->OutStreamer->AddComment("Length");
1974 Asm->EmitLabelDifference(TableEnd, TableStart, 4);
1975 Asm->OutStreamer->EmitLabel(TableStart);
1976 // Version number (DWARF v5 and later).
1977 Asm->OutStreamer->AddComment("Version");
1978 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
1980 Asm->OutStreamer->AddComment("Address size");
1981 Asm->emitInt8(Asm->MAI->getCodePointerSize());
1982 // Segment selector size.
1983 Asm->OutStreamer->AddComment("Segment selector size");
1987 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
1988 // that designates the end of the table for the caller to emit when the table is
1990 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
1991 const DwarfFile &Holder) {
1992 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
1993 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
1994 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
1996 Asm->OutStreamer->AddComment("Offset entry count");
1997 Asm->emitInt32(Holder.getRangeLists().size());
1998 Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym());
2000 for (const RangeSpanList &List : Holder.getRangeLists())
2001 Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(),
2007 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2008 // designates the end of the table for the caller to emit when the table is
2010 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2011 const DwarfFile &Holder) {
2012 MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2013 MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2014 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
2016 // FIXME: Generate the offsets table and use DW_FORM_loclistx with the
2017 // DW_AT_loclists_base attribute. Until then set the number of offsets to 0.
2018 Asm->OutStreamer->AddComment("Offset entry count");
2020 Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym());
2025 // Emit locations into the .debug_loc/.debug_rnglists section.
2026 void DwarfDebug::emitDebugLoc() {
2027 if (DebugLocs.getLists().empty())
2030 bool IsLocLists = getDwarfVersion() >= 5;
2031 MCSymbol *TableEnd = nullptr;
2033 Asm->OutStreamer->SwitchSection(
2034 Asm->getObjFileLowering().getDwarfLoclistsSection());
2035 TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder
2038 Asm->OutStreamer->SwitchSection(
2039 Asm->getObjFileLowering().getDwarfLocSection());
2042 unsigned char Size = Asm->MAI->getCodePointerSize();
2043 for (const auto &List : DebugLocs.getLists()) {
2044 Asm->OutStreamer->EmitLabel(List.Label);
2046 const DwarfCompileUnit *CU = List.CU;
2047 const MCSymbol *Base = CU->getBaseAddress();
2048 for (const auto &Entry : DebugLocs.getEntries(List)) {
2050 // Set up the range. This range is relative to the entry point of the
2051 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2052 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2054 Asm->OutStreamer->AddComment("DW_LLE_offset_pair");
2055 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1);
2056 Asm->OutStreamer->AddComment(" starting offset");
2057 Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base);
2058 Asm->OutStreamer->AddComment(" ending offset");
2059 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base);
2061 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
2062 Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
2065 emitDebugLocEntryLocation(Entry);
2069 // We have no base address.
2071 // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or
2072 // DW_LLE_startx_length in case if there is only a single range.
2073 // That should reduce the size of the debug data emited.
2074 // For now just use the DW_LLE_startx_length for all cases.
2075 Asm->OutStreamer->AddComment("DW_LLE_startx_length");
2076 Asm->emitInt8(dwarf::DW_LLE_startx_length);
2077 Asm->OutStreamer->AddComment(" start idx");
2078 Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym));
2079 Asm->OutStreamer->AddComment(" length");
2080 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym);
2082 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
2083 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
2086 emitDebugLocEntryLocation(Entry);
2090 // .debug_loclists section ends with DW_LLE_end_of_list.
2091 Asm->OutStreamer->AddComment("DW_LLE_end_of_list");
2092 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1);
2094 // Terminate the .debug_loc list with two 0 values.
2095 Asm->OutStreamer->EmitIntValue(0, Size);
2096 Asm->OutStreamer->EmitIntValue(0, Size);
2101 Asm->OutStreamer->EmitLabel(TableEnd);
2104 void DwarfDebug::emitDebugLocDWO() {
2105 Asm->OutStreamer->SwitchSection(
2106 Asm->getObjFileLowering().getDwarfLocDWOSection());
2107 for (const auto &List : DebugLocs.getLists()) {
2108 Asm->OutStreamer->EmitLabel(List.Label);
2109 for (const auto &Entry : DebugLocs.getEntries(List)) {
2110 // GDB only supports startx_length in pre-standard split-DWARF.
2111 // (in v5 standard loclists, it currently* /only/ supports base_address +
2112 // offset_pair, so the implementations can't really share much since they
2113 // need to use different representations)
2114 // * as of October 2018, at least
2115 // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2116 // in the address pool to minimize object size/relocations.
2117 Asm->emitInt8(dwarf::DW_LLE_startx_length);
2118 unsigned idx = AddrPool.getIndex(Entry.BeginSym);
2119 Asm->EmitULEB128(idx);
2120 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
2122 emitDebugLocEntryLocation(Entry);
2124 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2129 const MCSymbol *Start, *End;
2132 // Emit a debug aranges section, containing a CU lookup for any
2133 // address we can tie back to a CU.
2134 void DwarfDebug::emitDebugARanges() {
2135 // Provides a unique id per text section.
2136 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2138 // Filter labels by section.
2139 for (const SymbolCU &SCU : ArangeLabels) {
2140 if (SCU.Sym->isInSection()) {
2141 // Make a note of this symbol and it's section.
2142 MCSection *Section = &SCU.Sym->getSection();
2143 if (!Section->getKind().isMetadata())
2144 SectionMap[Section].push_back(SCU);
2146 // Some symbols (e.g. common/bss on mach-o) can have no section but still
2147 // appear in the output. This sucks as we rely on sections to build
2148 // arange spans. We can do it without, but it's icky.
2149 SectionMap[nullptr].push_back(SCU);
2153 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2155 for (auto &I : SectionMap) {
2156 MCSection *Section = I.first;
2157 SmallVector<SymbolCU, 8> &List = I.second;
2158 if (List.size() < 1)
2161 // If we have no section (e.g. common), just write out
2162 // individual spans for each symbol.
2164 for (const SymbolCU &Cur : List) {
2166 Span.Start = Cur.Sym;
2169 Spans[Cur.CU].push_back(Span);
2174 // Sort the symbols by offset within the section.
2176 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
2177 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2178 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2180 // Symbols with no order assigned should be placed at the end.
2181 // (e.g. section end labels)
2189 // Insert a final terminator.
2190 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2192 // Build spans between each label.
2193 const MCSymbol *StartSym = List[0].Sym;
2194 for (size_t n = 1, e = List.size(); n < e; n++) {
2195 const SymbolCU &Prev = List[n - 1];
2196 const SymbolCU &Cur = List[n];
2198 // Try and build the longest span we can within the same CU.
2199 if (Cur.CU != Prev.CU) {
2201 Span.Start = StartSym;
2204 Spans[Prev.CU].push_back(Span);
2210 // Start the dwarf aranges section.
2211 Asm->OutStreamer->SwitchSection(
2212 Asm->getObjFileLowering().getDwarfARangesSection());
2214 unsigned PtrSize = Asm->MAI->getCodePointerSize();
2216 // Build a list of CUs used.
2217 std::vector<DwarfCompileUnit *> CUs;
2218 for (const auto &it : Spans) {
2219 DwarfCompileUnit *CU = it.first;
2223 // Sort the CU list (again, to ensure consistent output order).
2224 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2225 return A->getUniqueID() < B->getUniqueID();
2228 // Emit an arange table for each CU we used.
2229 for (DwarfCompileUnit *CU : CUs) {
2230 std::vector<ArangeSpan> &List = Spans[CU];
2232 // Describe the skeleton CU's offset and length, not the dwo file's.
2233 if (auto *Skel = CU->getSkeleton())
2236 // Emit size of content not including length itself.
2237 unsigned ContentSize =
2238 sizeof(int16_t) + // DWARF ARange version number
2239 sizeof(int32_t) + // Offset of CU in the .debug_info section
2240 sizeof(int8_t) + // Pointer Size (in bytes)
2241 sizeof(int8_t); // Segment Size (in bytes)
2243 unsigned TupleSize = PtrSize * 2;
2245 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2247 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2249 ContentSize += Padding;
2250 ContentSize += (List.size() + 1) * TupleSize;
2252 // For each compile unit, write the list of spans it covers.
2253 Asm->OutStreamer->AddComment("Length of ARange Set");
2254 Asm->emitInt32(ContentSize);
2255 Asm->OutStreamer->AddComment("DWARF Arange version number");
2256 Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2257 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2258 emitSectionReference(*CU);
2259 Asm->OutStreamer->AddComment("Address Size (in bytes)");
2260 Asm->emitInt8(PtrSize);
2261 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2264 Asm->OutStreamer->emitFill(Padding, 0xff);
2266 for (const ArangeSpan &Span : List) {
2267 Asm->EmitLabelReference(Span.Start, PtrSize);
2269 // Calculate the size as being from the span start to it's end.
2271 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2273 // For symbols without an end marker (e.g. common), we
2274 // write a single arange entry containing just that one symbol.
2275 uint64_t Size = SymSize[Span.Start];
2279 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
2283 Asm->OutStreamer->AddComment("ARange terminator");
2284 Asm->OutStreamer->EmitIntValue(0, PtrSize);
2285 Asm->OutStreamer->EmitIntValue(0, PtrSize);
2289 /// Emit a single range list. We handle both DWARF v5 and earlier.
2290 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2291 const RangeSpanList &List) {
2293 auto DwarfVersion = DD.getDwarfVersion();
2294 // Emit our symbol so we can find the beginning of the range.
2295 Asm->OutStreamer->EmitLabel(List.getSym());
2296 // Gather all the ranges that apply to the same section so they can share
2297 // a base address entry.
2298 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges;
2299 // Size for our labels.
2300 auto Size = Asm->MAI->getCodePointerSize();
2302 for (const RangeSpan &Range : List.getRanges())
2303 SectionRanges[&Range.getStart()->getSection()].push_back(&Range);
2305 const DwarfCompileUnit &CU = List.getCU();
2306 const MCSymbol *CUBase = CU.getBaseAddress();
2307 bool BaseIsSet = false;
2308 for (const auto &P : SectionRanges) {
2309 // Don't bother with a base address entry if there's only one range in
2310 // this section in this range list - for example ranges for a CU will
2311 // usually consist of single regions from each of many sections
2312 // (-ffunction-sections, or just C++ inline functions) except under LTO
2313 // or optnone where there may be holes in a single CU's section
2315 auto *Base = CUBase;
2316 if (!Base && (P.second.size() > 1 || DwarfVersion < 5) &&
2317 (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) {
2319 // FIXME/use care: This may not be a useful base address if it's not
2320 // the lowest address/range in this object.
2321 Base = P.second.front()->getStart();
2322 if (DwarfVersion >= 5) {
2323 Base = DD.getSectionLabel(&Base->getSection());
2324 Asm->OutStreamer->AddComment("DW_RLE_base_addressx");
2325 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1);
2326 Asm->OutStreamer->AddComment(" base address index");
2327 Asm->EmitULEB128(DD.getAddressPool().getIndex(Base));
2329 Asm->OutStreamer->EmitIntValue(-1, Size);
2330 Asm->OutStreamer->AddComment(" base address");
2331 Asm->OutStreamer->EmitSymbolValue(Base, Size);
2333 } else if (BaseIsSet && DwarfVersion < 5) {
2336 Asm->OutStreamer->EmitIntValue(-1, Size);
2337 Asm->OutStreamer->EmitIntValue(0, Size);
2340 for (const auto *RS : P.second) {
2341 const MCSymbol *Begin = RS->getStart();
2342 const MCSymbol *End = RS->getEnd();
2343 assert(Begin && "Range without a begin symbol?");
2344 assert(End && "Range without an end symbol?");
2346 if (DwarfVersion >= 5) {
2347 // Emit DW_RLE_offset_pair when we have a base.
2348 Asm->OutStreamer->AddComment("DW_RLE_offset_pair");
2349 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1);
2350 Asm->OutStreamer->AddComment(" starting offset");
2351 Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
2352 Asm->OutStreamer->AddComment(" ending offset");
2353 Asm->EmitLabelDifferenceAsULEB128(End, Base);
2355 Asm->EmitLabelDifference(Begin, Base, Size);
2356 Asm->EmitLabelDifference(End, Base, Size);
2358 } else if (DwarfVersion >= 5) {
2359 Asm->OutStreamer->AddComment("DW_RLE_startx_length");
2360 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1);
2361 Asm->OutStreamer->AddComment(" start index");
2362 Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
2363 Asm->OutStreamer->AddComment(" length");
2364 Asm->EmitLabelDifferenceAsULEB128(End, Begin);
2366 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2367 Asm->OutStreamer->EmitSymbolValue(End, Size);
2371 if (DwarfVersion >= 5) {
2372 Asm->OutStreamer->AddComment("DW_RLE_end_of_list");
2373 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1);
2375 // Terminate the list with two 0 values.
2376 Asm->OutStreamer->EmitIntValue(0, Size);
2377 Asm->OutStreamer->EmitIntValue(0, Size);
2381 static void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm,
2382 const DwarfFile &Holder, MCSymbol *TableEnd) {
2383 for (const RangeSpanList &List : Holder.getRangeLists())
2384 emitRangeList(DD, Asm, List);
2387 Asm->OutStreamer->EmitLabel(TableEnd);
2390 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2391 /// .debug_rnglists section.
2392 void DwarfDebug::emitDebugRanges() {
2396 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2398 if (Holder.getRangeLists().empty())
2401 assert(useRangesSection());
2402 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2403 return Pair.second->getCUNode()->isDebugDirectivesOnly();
2406 // Start the dwarf ranges section.
2407 MCSymbol *TableEnd = nullptr;
2408 if (getDwarfVersion() >= 5) {
2409 Asm->OutStreamer->SwitchSection(
2410 Asm->getObjFileLowering().getDwarfRnglistsSection());
2411 TableEnd = emitRnglistsTableHeader(Asm, Holder);
2413 Asm->OutStreamer->SwitchSection(
2414 Asm->getObjFileLowering().getDwarfRangesSection());
2416 emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2419 void DwarfDebug::emitDebugRangesDWO() {
2420 assert(useSplitDwarf());
2425 const auto &Holder = InfoHolder;
2427 if (Holder.getRangeLists().empty())
2430 assert(getDwarfVersion() >= 5);
2431 assert(useRangesSection());
2432 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2433 return Pair.second->getCUNode()->isDebugDirectivesOnly();
2436 // Start the dwarf ranges section.
2437 Asm->OutStreamer->SwitchSection(
2438 Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2439 MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder);
2441 emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2444 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2445 for (auto *MN : Nodes) {
2446 if (auto *M = dyn_cast<DIMacro>(MN))
2448 else if (auto *F = dyn_cast<DIMacroFile>(MN))
2449 emitMacroFile(*F, U);
2451 llvm_unreachable("Unexpected DI type!");
2455 void DwarfDebug::emitMacro(DIMacro &M) {
2456 Asm->EmitULEB128(M.getMacinfoType());
2457 Asm->EmitULEB128(M.getLine());
2458 StringRef Name = M.getName();
2459 StringRef Value = M.getValue();
2460 Asm->OutStreamer->EmitBytes(Name);
2461 if (!Value.empty()) {
2462 // There should be one space between macro name and macro value.
2464 Asm->OutStreamer->EmitBytes(Value);
2466 Asm->emitInt8('\0');
2469 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2470 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2471 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2472 Asm->EmitULEB128(F.getLine());
2473 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
2474 handleMacroNodes(F.getElements(), U);
2475 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2478 /// Emit macros into a debug macinfo section.
2479 void DwarfDebug::emitDebugMacinfo() {
2483 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2484 return Pair.second->getCUNode()->isDebugDirectivesOnly();
2488 // Start the dwarf macinfo section.
2489 Asm->OutStreamer->SwitchSection(
2490 Asm->getObjFileLowering().getDwarfMacinfoSection());
2492 for (const auto &P : CUMap) {
2493 auto &TheCU = *P.second;
2494 if (TheCU.getCUNode()->isDebugDirectivesOnly())
2496 auto *SkCU = TheCU.getSkeleton();
2497 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2498 auto *CUNode = cast<DICompileUnit>(P.first);
2499 DIMacroNodeArray Macros = CUNode->getMacros();
2500 if (!Macros.empty()) {
2501 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2502 handleMacroNodes(Macros, U);
2505 Asm->OutStreamer->AddComment("End Of Macro List Mark");
2509 // DWARF5 Experimental Separate Dwarf emitters.
2511 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2512 std::unique_ptr<DwarfCompileUnit> NewU) {
2514 if (!CompilationDir.empty())
2515 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2517 addGnuPubAttributes(*NewU, Die);
2519 SkeletonHolder.addUnit(std::move(NewU));
2522 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2524 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
2525 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2526 DwarfCompileUnit &NewCU = *OwnedUnit;
2527 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2529 NewCU.initStmtList();
2531 if (useSegmentedStringOffsetsTable())
2532 NewCU.addStringOffsetsStart();
2534 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2539 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2540 // compile units that would normally be in debug_info.
2541 void DwarfDebug::emitDebugInfoDWO() {
2542 assert(useSplitDwarf() && "No split dwarf debug info?");
2543 // Don't emit relocations into the dwo file.
2544 InfoHolder.emitUnits(/* UseOffsets */ true);
2547 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2548 // abbreviations for the .debug_info.dwo section.
2549 void DwarfDebug::emitDebugAbbrevDWO() {
2550 assert(useSplitDwarf() && "No split dwarf?");
2551 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2554 void DwarfDebug::emitDebugLineDWO() {
2555 assert(useSplitDwarf() && "No split dwarf?");
2556 SplitTypeUnitFileTable.Emit(
2557 *Asm->OutStreamer, MCDwarfLineTableParams(),
2558 Asm->getObjFileLowering().getDwarfLineDWOSection());
2561 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2562 assert(useSplitDwarf() && "No split dwarf?");
2563 InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2564 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2565 InfoHolder.getStringOffsetsStartSym());
2568 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2569 // string section and is identical in format to traditional .debug_str
2571 void DwarfDebug::emitDebugStrDWO() {
2572 if (useSegmentedStringOffsetsTable())
2573 emitStringOffsetsTableHeaderDWO();
2574 assert(useSplitDwarf() && "No split dwarf?");
2575 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2576 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2577 OffSec, /* UseRelativeOffsets = */ false);
2580 // Emit address pool.
2581 void DwarfDebug::emitDebugAddr() {
2582 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2585 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2586 if (!useSplitDwarf())
2588 const DICompileUnit *DIUnit = CU.getCUNode();
2589 SplitTypeUnitFileTable.maybeSetRootFile(
2590 DIUnit->getDirectory(), DIUnit->getFilename(),
2591 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2592 return &SplitTypeUnitFileTable;
2595 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2597 Hash.update(Identifier);
2598 // ... take the least significant 8 bytes and return those. Our MD5
2599 // implementation always returns its results in little endian, so we actually
2600 // need the "high" word.
2601 MD5::MD5Result Result;
2603 return Result.high();
2606 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2607 StringRef Identifier, DIE &RefDie,
2608 const DICompositeType *CTy) {
2609 // Fast path if we're building some type units and one has already used the
2610 // address pool we know we're going to throw away all this work anyway, so
2611 // don't bother building dependent types.
2612 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2615 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2617 CU.addDIETypeSignature(RefDie, Ins.first->second);
2621 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2622 AddrPool.resetUsedFlag();
2624 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2625 getDwoLineTable(CU));
2626 DwarfTypeUnit &NewTU = *OwnedUnit;
2627 DIE &UnitDie = NewTU.getUnitDie();
2628 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2630 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2633 uint64_t Signature = makeTypeSignature(Identifier);
2634 NewTU.setTypeSignature(Signature);
2635 Ins.first->second = Signature;
2637 if (useSplitDwarf()) {
2638 MCSection *Section =
2639 getDwarfVersion() <= 4
2640 ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
2641 : Asm->getObjFileLowering().getDwarfInfoDWOSection();
2642 NewTU.setSection(Section);
2644 MCSection *Section =
2645 getDwarfVersion() <= 4
2646 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
2647 : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
2648 NewTU.setSection(Section);
2649 // Non-split type units reuse the compile unit's line table.
2650 CU.applyStmtList(UnitDie);
2653 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2655 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2656 NewTU.addStringOffsetsStart();
2658 NewTU.setType(NewTU.createTypeDIE(CTy));
2661 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2662 TypeUnitsUnderConstruction.clear();
2664 // Types referencing entries in the address table cannot be placed in type
2666 if (AddrPool.hasBeenUsed()) {
2668 // Remove all the types built while building this type.
2669 // This is pessimistic as some of these types might not be dependent on
2670 // the type that used an address.
2671 for (const auto &TU : TypeUnitsToAdd)
2672 TypeSignatures.erase(TU.second);
2674 // Construct this type in the CU directly.
2675 // This is inefficient because all the dependent types will be rebuilt
2676 // from scratch, including building them in type units, discovering that
2677 // they depend on addresses, throwing them out and rebuilding them.
2678 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2682 // If the type wasn't dependent on fission addresses, finish adding the type
2683 // and all its dependent types.
2684 for (auto &TU : TypeUnitsToAdd) {
2685 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2686 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2689 CU.addDIETypeSignature(RefDie, Signature);
2692 // Add the Name along with its companion DIE to the appropriate accelerator
2693 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
2694 // AccelTableKind::Apple, we use the table we got as an argument). If
2695 // accelerator tables are disabled, this function does nothing.
2696 template <typename DataT>
2697 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
2698 AccelTable<DataT> &AppleAccel, StringRef Name,
2700 if (getAccelTableKind() == AccelTableKind::None)
2703 if (getAccelTableKind() != AccelTableKind::Apple &&
2704 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
2707 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2708 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
2710 switch (getAccelTableKind()) {
2711 case AccelTableKind::Apple:
2712 AppleAccel.addName(Ref, Die);
2714 case AccelTableKind::Dwarf:
2715 AccelDebugNames.addName(Ref, Die);
2717 case AccelTableKind::Default:
2718 llvm_unreachable("Default should have already been resolved.");
2719 case AccelTableKind::None:
2720 llvm_unreachable("None handled above");
2724 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
2726 addAccelNameImpl(CU, AccelNames, Name, Die);
2729 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
2731 // ObjC names go only into the Apple accelerator tables.
2732 if (getAccelTableKind() == AccelTableKind::Apple)
2733 addAccelNameImpl(CU, AccelObjC, Name, Die);
2736 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
2738 addAccelNameImpl(CU, AccelNamespace, Name, Die);
2741 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
2742 const DIE &Die, char Flags) {
2743 addAccelNameImpl(CU, AccelTypes, Name, Die);
2746 uint16_t DwarfDebug::getDwarfVersion() const {
2747 return Asm->OutStreamer->getContext().getDwarfVersion();
2750 void DwarfDebug::addSectionLabel(const MCSymbol *Sym) {
2751 SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym));
2754 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
2755 return SectionLabels.find(S)->second;