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/TargetRegisterInfo.h"
43 #include "llvm/CodeGen/TargetSubtargetInfo.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DebugInfoMetadata.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/MC/MCAsmInfo.h"
51 #include "llvm/MC/MCContext.h"
52 #include "llvm/MC/MCDwarf.h"
53 #include "llvm/MC/MCSection.h"
54 #include "llvm/MC/MCStreamer.h"
55 #include "llvm/MC/MCSymbol.h"
56 #include "llvm/MC/MCTargetOptions.h"
57 #include "llvm/MC/MachineLocation.h"
58 #include "llvm/MC/SectionKind.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/MD5.h"
65 #include "llvm/Support/MathExtras.h"
66 #include "llvm/Support/Timer.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/Target/TargetLoweringObjectFile.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
82 #define DEBUG_TYPE "dwarfdebug"
85 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
86 cl::desc("Disable debug info printing"));
88 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
89 "use-dwarf-ranges-base-address-specifier", cl::Hidden,
90 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
92 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
94 cl::desc("Generate dwarf aranges"),
97 static cl::opt<bool> SplitDwarfCrossCuReferences(
98 "split-dwarf-cross-cu-references", cl::Hidden,
99 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
101 enum DefaultOnOff { Default, Enable, Disable };
103 static cl::opt<DefaultOnOff> UnknownLocations(
104 "use-unknown-locations", cl::Hidden,
105 cl::desc("Make an absence of debug location information explicit."),
106 cl::values(clEnumVal(Default, "At top of block or after label"),
107 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
110 static cl::opt<DefaultOnOff>
111 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
112 cl::desc("Output prototype dwarf accelerator tables."),
113 cl::values(clEnumVal(Default, "Default for platform"),
114 clEnumVal(Enable, "Enabled"),
115 clEnumVal(Disable, "Disabled")),
118 static cl::opt<DefaultOnOff>
119 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
120 cl::desc("Use inlined strings rather than string section."),
121 cl::values(clEnumVal(Default, "Default for platform"),
122 clEnumVal(Enable, "Enabled"),
123 clEnumVal(Disable, "Disabled")),
127 NoDwarfPubSections("no-dwarf-pub-sections", cl::Hidden,
128 cl::desc("Disable emission of DWARF pub sections."),
132 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
133 cl::desc("Disable emission .debug_ranges section."),
136 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
137 "dwarf-sections-as-references", cl::Hidden,
138 cl::desc("Use sections+offset as references rather than labels."),
139 cl::values(clEnumVal(Default, "Default for platform"),
140 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
143 enum LinkageNameOption {
149 static cl::opt<LinkageNameOption>
150 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
151 cl::desc("Which DWARF linkage-name attributes to emit."),
152 cl::values(clEnumValN(DefaultLinkageNames, "Default",
153 "Default for platform"),
154 clEnumValN(AllLinkageNames, "All", "All"),
155 clEnumValN(AbstractLinkageNames, "Abstract",
156 "Abstract subprograms")),
157 cl::init(DefaultLinkageNames));
159 static const char *const DWARFGroupName = "dwarf";
160 static const char *const DWARFGroupDescription = "DWARF Emission";
161 static const char *const DbgTimerName = "writer";
162 static const char *const DbgTimerDescription = "DWARF Debug Writer";
164 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
166 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
167 : dwarf::OperationEncodingString(Op));
170 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
171 BS.EmitSLEB128(Value, Twine(Value));
174 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
175 BS.EmitULEB128(Value, Twine(Value));
178 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
179 unsigned MachineReg) {
180 // This information is not available while emitting .debug_loc entries.
184 bool DbgVariable::isBlockByrefVariable() const {
185 assert(Var && "Invalid complex DbgVariable!");
186 return Var->getType().resolve()->isBlockByrefStruct();
189 const DIType *DbgVariable::getType() const {
190 DIType *Ty = Var->getType().resolve();
191 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
192 // addresses instead.
193 if (Ty->isBlockByrefStruct()) {
194 /* Byref variables, in Blocks, are declared by the programmer as
195 "SomeType VarName;", but the compiler creates a
196 __Block_byref_x_VarName struct, and gives the variable VarName
197 either the struct, or a pointer to the struct, as its type. This
198 is necessary for various behind-the-scenes things the compiler
199 needs to do with by-reference variables in blocks.
201 However, as far as the original *programmer* is concerned, the
202 variable should still have type 'SomeType', as originally declared.
204 The following function dives into the __Block_byref_x_VarName
205 struct to find the original type of the variable. This will be
206 passed back to the code generating the type for the Debug
207 Information Entry for the variable 'VarName'. 'VarName' will then
208 have the original type 'SomeType' in its debug information.
210 The original type 'SomeType' will be the type of the field named
211 'VarName' inside the __Block_byref_x_VarName struct.
213 NOTE: In order for this to not completely fail on the debugger
214 side, the Debug Information Entry for the variable VarName needs to
215 have a DW_AT_location that tells the debugger how to unwind through
216 the pointers and __Block_byref_x_VarName struct to find the actual
217 value of the variable. The function addBlockByrefType does this. */
218 DIType *subType = Ty;
219 uint16_t tag = Ty->getTag();
221 if (tag == dwarf::DW_TAG_pointer_type)
222 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
224 auto Elements = cast<DICompositeType>(subType)->getElements();
225 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
226 auto *DT = cast<DIDerivedType>(Elements[i]);
227 if (getName() == DT->getName())
228 return resolve(DT->getBaseType());
234 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
235 if (FrameIndexExprs.size() == 1)
236 return FrameIndexExprs;
238 assert(llvm::all_of(FrameIndexExprs,
239 [](const FrameIndexExpr &A) {
240 return A.Expr->isFragment();
242 "multiple FI expressions without DW_OP_LLVM_fragment");
243 std::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(),
244 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
245 return A.Expr->getFragmentInfo()->OffsetInBits <
246 B.Expr->getFragmentInfo()->OffsetInBits;
249 return FrameIndexExprs;
252 void DbgVariable::addMMIEntry(const DbgVariable &V) {
253 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
254 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
255 assert(V.Var == Var && "conflicting variable");
256 assert(V.IA == IA && "conflicting inlined-at location");
258 assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
259 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
261 // FIXME: This logic should not be necessary anymore, as we now have proper
262 // deduplication. However, without it, we currently run into the assertion
263 // below, which means that we are likely dealing with broken input, i.e. two
264 // non-fragment entries for the same variable at different frame indices.
265 if (FrameIndexExprs.size()) {
266 auto *Expr = FrameIndexExprs.back().Expr;
267 if (!Expr || !Expr->isFragment())
271 for (const auto &FIE : V.FrameIndexExprs)
272 // Ignore duplicate entries.
273 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
274 return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
276 FrameIndexExprs.push_back(FIE);
278 assert((FrameIndexExprs.size() == 1 ||
279 llvm::all_of(FrameIndexExprs,
280 [](FrameIndexExpr &FIE) {
281 return FIE.Expr && FIE.Expr->isFragment();
283 "conflicting locations for variable");
286 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
287 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
288 InfoHolder(A, "info_string", DIEValueAllocator),
289 SkeletonHolder(A, "skel_string", DIEValueAllocator),
290 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
291 const Triple &TT = Asm->TM.getTargetTriple();
293 // Make sure we know our "debugger tuning." The target option takes
294 // precedence; fall back to triple-based defaults.
295 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
296 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
298 DebuggerTuning = DebuggerKind::LLDB;
299 else if (TT.isPS4CPU())
300 DebuggerTuning = DebuggerKind::SCE;
302 DebuggerTuning = DebuggerKind::GDB;
304 // Turn on accelerator tables by default, if tuning for LLDB and the target is
306 if (DwarfAccelTables == Default)
307 HasDwarfAccelTables =
308 tuneForLLDB() && A->TM.getTargetTriple().isOSBinFormatMachO();
310 HasDwarfAccelTables = DwarfAccelTables == Enable;
312 UseInlineStrings = DwarfInlinedStrings == Enable;
313 HasAppleExtensionAttributes = tuneForLLDB();
315 // Handle split DWARF.
316 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
318 // SCE defaults to linkage names only for abstract subprograms.
319 if (DwarfLinkageNames == DefaultLinkageNames)
320 UseAllLinkageNames = !tuneForSCE();
322 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
324 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
325 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
326 : MMI->getModule()->getDwarfVersion();
327 // Use dwarf 4 by default if nothing is requested.
328 DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
330 UsePubSections = !NoDwarfPubSections;
331 UseRangesSection = !NoDwarfRangesSection;
333 // Use sections as references.
334 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
336 // Work around a GDB bug. GDB doesn't support the standard opcode;
337 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
338 // is defined as of DWARF 3.
339 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
340 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
341 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
343 // GDB does not fully support the DWARF 4 representation for bitfields.
344 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
346 // The DWARF v5 string offsets table has - possibly shared - contributions
347 // from each compile and type unit each preceded by a header. The string
348 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
349 // a monolithic string offsets table without any header.
350 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
352 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
355 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
356 DwarfDebug::~DwarfDebug() = default;
358 static bool isObjCClass(StringRef Name) {
359 return Name.startswith("+") || Name.startswith("-");
362 static bool hasObjCCategory(StringRef Name) {
363 if (!isObjCClass(Name))
366 return Name.find(") ") != StringRef::npos;
369 static void getObjCClassCategory(StringRef In, StringRef &Class,
370 StringRef &Category) {
371 if (!hasObjCCategory(In)) {
372 Class = In.slice(In.find('[') + 1, In.find(' '));
377 Class = In.slice(In.find('[') + 1, In.find('('));
378 Category = In.slice(In.find('[') + 1, In.find(' '));
381 static StringRef getObjCMethodName(StringRef In) {
382 return In.slice(In.find(' ') + 1, In.find(']'));
385 // Add the various names to the Dwarf accelerator table names.
386 // TODO: Determine whether or not we should add names for programs
387 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
388 // is only slightly different than the lookup of non-standard ObjC names.
389 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
390 if (!SP->isDefinition())
392 addAccelName(SP->getName(), Die);
394 // If the linkage name is different than the name, go ahead and output
395 // that as well into the name table.
396 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
397 addAccelName(SP->getLinkageName(), Die);
399 // If this is an Objective-C selector name add it to the ObjC accelerator
401 if (isObjCClass(SP->getName())) {
402 StringRef Class, Category;
403 getObjCClassCategory(SP->getName(), Class, Category);
404 addAccelObjC(Class, Die);
406 addAccelObjC(Category, Die);
407 // Also add the base method name to the name table.
408 addAccelName(getObjCMethodName(SP->getName()), Die);
412 /// Check whether we should create a DIE for the given Scope, return true
413 /// if we don't create a DIE (the corresponding DIE is null).
414 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
415 if (Scope->isAbstractScope())
418 // We don't create a DIE if there is no Range.
419 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
423 if (Ranges.size() > 1)
426 // We don't create a DIE if we have a single Range and the end label
428 return !getLabelAfterInsn(Ranges.front().second);
431 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
433 if (auto *SkelCU = CU.getSkeleton())
434 if (CU.getCUNode()->getSplitDebugInlining())
438 bool DwarfDebug::shareAcrossDWOCUs() const {
439 return SplitDwarfCrossCuReferences;
442 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
443 LexicalScope *Scope) {
444 assert(Scope && Scope->getScopeNode());
445 assert(Scope->isAbstractScope());
446 assert(!Scope->getInlinedAt());
448 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
450 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
451 // was inlined from another compile unit.
452 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
453 // Avoid building the original CU if it won't be used
454 SrcCU.constructAbstractSubprogramScopeDIE(Scope);
456 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
457 if (auto *SkelCU = CU.getSkeleton()) {
458 (shareAcrossDWOCUs() ? CU : SrcCU)
459 .constructAbstractSubprogramScopeDIE(Scope);
460 if (CU.getCUNode()->getSplitDebugInlining())
461 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
463 CU.constructAbstractSubprogramScopeDIE(Scope);
467 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
468 if (!U.hasDwarfPubSections())
471 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
474 // Create new DwarfCompileUnit for the given metadata node with tag
475 // DW_TAG_compile_unit.
477 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
478 if (auto *CU = CUMap.lookup(DIUnit))
480 StringRef FN = DIUnit->getFilename();
481 CompilationDir = DIUnit->getDirectory();
483 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
484 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
485 DwarfCompileUnit &NewCU = *OwnedUnit;
486 DIE &Die = NewCU.getUnitDie();
487 InfoHolder.addUnit(std::move(OwnedUnit));
488 if (useSplitDwarf()) {
489 NewCU.setSkeleton(constructSkeletonCU(NewCU));
490 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
491 Asm->TM.Options.MCOptions.SplitDwarfFile);
494 for (auto *IE : DIUnit->getImportedEntities())
495 NewCU.addImportedEntity(IE);
497 // LTO with assembly output shares a single line table amongst multiple CUs.
498 // To avoid the compilation directory being ambiguous, let the line table
499 // explicitly describe the directory of all files, never relying on the
500 // compilation directory.
501 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
502 Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
503 NewCU.getUniqueID(), CompilationDir);
505 StringRef Producer = DIUnit->getProducer();
506 StringRef Flags = DIUnit->getFlags();
507 if (!Flags.empty()) {
508 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
509 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
511 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
513 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
514 DIUnit->getSourceLanguage());
515 NewCU.addString(Die, dwarf::DW_AT_name, FN);
517 // Add DW_str_offsets_base to the unit DIE, except for split units.
518 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
519 NewCU.addStringOffsetsStart();
521 if (!useSplitDwarf()) {
522 NewCU.initStmtList();
524 // If we're using split dwarf the compilation dir is going to be in the
525 // skeleton CU and so we don't need to duplicate it here.
526 if (!CompilationDir.empty())
527 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
529 addGnuPubAttributes(NewCU, Die);
532 if (useAppleExtensionAttributes()) {
533 if (DIUnit->isOptimized())
534 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
536 StringRef Flags = DIUnit->getFlags();
538 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
540 if (unsigned RVer = DIUnit->getRuntimeVersion())
541 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
542 dwarf::DW_FORM_data1, RVer);
546 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
548 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
550 if (DIUnit->getDWOId()) {
551 // This CU is either a clang module DWO or a skeleton CU.
552 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
554 if (!DIUnit->getSplitDebugFilename().empty())
555 // This is a prefabricated skeleton CU.
556 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
557 DIUnit->getSplitDebugFilename());
560 CUMap.insert({DIUnit, &NewCU});
561 CUDieMap.insert({&Die, &NewCU});
565 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
566 const DIImportedEntity *N) {
567 if (isa<DILocalScope>(N->getScope()))
569 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
570 D->addChild(TheCU.constructImportedEntityDIE(N));
573 /// Sort and unique GVEs by comparing their fragment offset.
574 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
575 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
576 std::sort(GVEs.begin(), GVEs.end(),
577 [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
578 // Sort order: first null exprs, then exprs without fragment
579 // info, then sort by fragment offset in bits.
580 // FIXME: Come up with a more comprehensive comparator so
581 // the sorting isn't non-deterministic, and so the following
582 // std::unique call works correctly.
583 if (!A.Expr || !B.Expr)
585 auto FragmentA = A.Expr->getFragmentInfo();
586 auto FragmentB = B.Expr->getFragmentInfo();
587 if (!FragmentA || !FragmentB)
589 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
591 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
592 [](DwarfCompileUnit::GlobalExpr A,
593 DwarfCompileUnit::GlobalExpr B) {
594 return A.Expr == B.Expr;
600 // Emit all Dwarf sections that should come prior to the content. Create
601 // global DIEs and emit initial debug info sections. This is invoked by
602 // the target AsmPrinter.
603 void DwarfDebug::beginModule() {
604 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
605 DWARFGroupDescription, TimePassesIsEnabled);
606 if (DisableDebugInfoPrinting)
609 const Module *M = MMI->getModule();
611 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
612 M->debug_compile_units_end());
613 // Tell MMI whether we have debug info.
614 MMI->setDebugInfoAvailability(NumDebugCUs > 0);
615 SingleCU = NumDebugCUs == 1;
616 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
618 for (const GlobalVariable &Global : M->globals()) {
619 SmallVector<DIGlobalVariableExpression *, 1> GVs;
620 Global.getDebugInfo(GVs);
621 for (auto *GVE : GVs)
622 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
625 // Create the symbol that designates the start of the unit's contribution
626 // to the string offsets table. In a split DWARF scenario, only the skeleton
627 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
628 if (useSegmentedStringOffsetsTable())
629 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
630 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
632 for (DICompileUnit *CUNode : M->debug_compile_units()) {
633 // FIXME: Move local imported entities into a list attached to the
634 // subprogram, then this search won't be needed and a
635 // getImportedEntities().empty() test should go below with the rest.
636 bool HasNonLocalImportedEntities = llvm::any_of(
637 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
638 return !isa<DILocalScope>(IE->getScope());
641 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
642 CUNode->getRetainedTypes().empty() &&
643 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
646 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
649 for (auto *GVE : CUNode->getGlobalVariables()) {
650 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
651 // already know about the variable and it isn't adding a constant
653 auto &GVMapEntry = GVMap[GVE->getVariable()];
654 auto *Expr = GVE->getExpression();
655 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
656 GVMapEntry.push_back({nullptr, Expr});
658 DenseSet<DIGlobalVariable *> Processed;
659 for (auto *GVE : CUNode->getGlobalVariables()) {
660 DIGlobalVariable *GV = GVE->getVariable();
661 if (Processed.insert(GV).second)
662 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
665 for (auto *Ty : CUNode->getEnumTypes()) {
666 // The enum types array by design contains pointers to
667 // MDNodes rather than DIRefs. Unique them here.
668 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
670 for (auto *Ty : CUNode->getRetainedTypes()) {
671 // The retained types array by design contains pointers to
672 // MDNodes rather than DIRefs. Unique them here.
673 if (DIType *RT = dyn_cast<DIType>(Ty))
674 // There is no point in force-emitting a forward declaration.
675 CU.getOrCreateTypeDIE(RT);
677 // Emit imported_modules last so that the relevant context is already
679 for (auto *IE : CUNode->getImportedEntities())
680 constructAndAddImportedEntityDIE(CU, IE);
684 void DwarfDebug::finishVariableDefinitions() {
685 for (const auto &Var : ConcreteVariables) {
686 DIE *VariableDie = Var->getDIE();
688 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
689 // in the ConcreteVariables list, rather than looking it up again here.
690 // DIE::getUnit isn't simple - it walks parent pointers, etc.
691 DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie());
693 Unit->finishVariableDefinition(*Var);
697 void DwarfDebug::finishSubprogramDefinitions() {
698 for (const DISubprogram *SP : ProcessedSPNodes) {
699 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
701 getOrCreateDwarfCompileUnit(SP->getUnit()),
702 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
706 void DwarfDebug::finalizeModuleInfo() {
707 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
709 finishSubprogramDefinitions();
711 finishVariableDefinitions();
713 // Include the DWO file name in the hash if there's more than one CU.
714 // This handles ThinLTO's situation where imported CUs may very easily be
715 // duplicate with the same CU partially imported into another ThinLTO unit.
717 if (CUMap.size() > 1)
718 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
720 // Handle anything that needs to be done on a per-unit basis after
721 // all other generation.
722 for (const auto &P : CUMap) {
723 auto &TheCU = *P.second;
724 // Emit DW_AT_containing_type attribute to connect types with their
725 // vtable holding type.
726 TheCU.constructContainingTypeDIEs();
728 // Add CU specific attributes if we need to add any.
729 // If we're splitting the dwarf out now that we've got the entire
730 // CU then add the dwo id to it.
731 auto *SkCU = TheCU.getSkeleton();
732 if (useSplitDwarf()) {
733 // Emit a unique identifier for this CU.
735 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
736 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
737 dwarf::DW_FORM_data8, ID);
738 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
739 dwarf::DW_FORM_data8, ID);
741 // We don't keep track of which addresses are used in which CU so this
742 // is a bit pessimistic under LTO.
743 if (!AddrPool.isEmpty()) {
744 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
745 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
748 if (!SkCU->getRangeLists().empty()) {
749 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
750 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
755 // If we have code split among multiple sections or non-contiguous
756 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
757 // remain in the .o file, otherwise add a DW_AT_low_pc.
758 // FIXME: We should use ranges allow reordering of code ala
759 // .subsections_via_symbols in mach-o. This would mean turning on
760 // ranges for all subprogram DIEs for mach-o.
761 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
762 if (unsigned NumRanges = TheCU.getRanges().size()) {
763 if (NumRanges > 1 && useRangesSection())
764 // A DW_AT_low_pc attribute may also be specified in combination with
765 // DW_AT_ranges to specify the default base address for use in
766 // location lists (see Section 2.6.2) and range lists (see Section
768 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
770 U.setBaseAddress(TheCU.getRanges().front().getStart());
771 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
774 auto *CUNode = cast<DICompileUnit>(P.first);
775 // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
776 if (CUNode->getMacros())
777 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
778 U.getMacroLabelBegin(),
779 TLOF.getDwarfMacinfoSection()->getBeginSymbol());
782 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
783 for (auto *CUNode : MMI->getModule()->debug_compile_units())
784 if (CUNode->getDWOId())
785 getOrCreateDwarfCompileUnit(CUNode);
787 // Compute DIE offsets and sizes.
788 InfoHolder.computeSizeAndOffsets();
790 SkeletonHolder.computeSizeAndOffsets();
793 // Emit all Dwarf sections that should come after the content.
794 void DwarfDebug::endModule() {
795 assert(CurFn == nullptr);
796 assert(CurMI == nullptr);
798 // If we aren't actually generating debug info (check beginModule -
799 // conditionalized on !DisableDebugInfoPrinting and the presence of the
800 // llvm.dbg.cu metadata node)
801 if (!MMI->hasDebugInfo())
804 // Finalize the debug info for the module.
805 finalizeModuleInfo();
812 // Emit info into a debug loc section.
815 // Corresponding abbreviations into a abbrev section.
818 // Emit all the DIEs into a debug info section.
821 // Emit info into a debug aranges section.
822 if (GenerateARangeSection)
825 // Emit info into a debug ranges section.
828 // Emit info into a debug macinfo section.
831 if (useSplitDwarf()) {
834 emitDebugAbbrevDWO();
836 // Emit DWO addresses.
837 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
840 // Emit info into the dwarf accelerator table sections.
841 if (useDwarfAccelTables()) {
844 emitAccelNamespaces();
848 // Emit the pubnames and pubtypes sections if requested.
849 emitDebugPubSections();
852 // FIXME: AbstractVariables.clear();
855 void DwarfDebug::ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV,
856 const MDNode *ScopeNode) {
857 const DILocalVariable *Cleansed = nullptr;
858 if (CU.getExistingAbstractVariable(IV, Cleansed))
861 CU.createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
862 cast<DILocalScope>(ScopeNode)));
865 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU,
866 InlinedVariable IV, const MDNode *ScopeNode) {
867 const DILocalVariable *Cleansed = nullptr;
868 if (CU.getExistingAbstractVariable(IV, Cleansed))
871 if (LexicalScope *Scope =
872 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
873 CU.createAbstractVariable(Cleansed, Scope);
876 // Collect variable information from side table maintained by MF.
877 void DwarfDebug::collectVariableInfoFromMFTable(
878 DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) {
879 SmallDenseMap<InlinedVariable, DbgVariable *> MFVars;
880 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
883 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
884 "Expected inlined-at fields to agree");
886 InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
887 Processed.insert(Var);
888 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
890 // If variable scope is not found then skip this variable.
894 ensureAbstractVariableIsCreatedIfScoped(TheCU, Var, Scope->getScopeNode());
895 auto RegVar = llvm::make_unique<DbgVariable>(Var.first, Var.second);
896 RegVar->initializeMMI(VI.Expr, VI.Slot);
897 if (DbgVariable *DbgVar = MFVars.lookup(Var))
898 DbgVar->addMMIEntry(*RegVar);
899 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
900 MFVars.insert({Var, RegVar.get()});
901 ConcreteVariables.push_back(std::move(RegVar));
906 // Get .debug_loc entry for the instruction range starting at MI.
907 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
908 const DIExpression *Expr = MI->getDebugExpression();
909 assert(MI->getNumOperands() == 4);
910 if (MI->getOperand(0).isReg()) {
911 auto RegOp = MI->getOperand(0);
912 auto Op1 = MI->getOperand(1);
913 // If the second operand is an immediate, this is a
914 // register-indirect address.
915 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
916 MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
917 return DebugLocEntry::Value(Expr, MLoc);
919 if (MI->getOperand(0).isImm())
920 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
921 if (MI->getOperand(0).isFPImm())
922 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
923 if (MI->getOperand(0).isCImm())
924 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
926 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
929 /// \brief If this and Next are describing different fragments of the same
930 /// variable, merge them by appending Next's values to the current
932 /// Return true if the merge was successful.
933 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
934 if (Begin == Next.Begin) {
935 auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
936 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
937 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
940 // We can only merge entries if none of the fragments overlap any others.
941 // In doing so, we can take advantage of the fact that both lists are
943 for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
944 for (; j < Next.Values.size(); ++j) {
945 int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp(
946 cast<DIExpression>(Next.Values[j].Expression));
947 if (res == 0) // The two expressions overlap, we can't merge.
949 // Values[i] is entirely before Next.Values[j],
950 // so go back to the next entry of Values.
953 // Next.Values[j] is entirely before Values[i], so go on to the
954 // next entry of Next.Values.
958 addValues(Next.Values);
965 /// Build the location list for all DBG_VALUEs in the function that
966 /// describe the same variable. If the ranges of several independent
967 /// fragments of the same variable overlap partially, split them up and
968 /// combine the ranges. The resulting DebugLocEntries are will have
969 /// strict monotonically increasing begin addresses and will never
974 // Ranges History [var, loc, fragment ofs size]
975 // 0 | [x, (reg0, fragment 0, 32)]
976 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
978 // 3 | [clobber reg0]
979 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
984 // [0-1] [x, (reg0, fragment 0, 32)]
985 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)]
986 // [3-4] [x, (reg1, fragment 32, 32)]
987 // [4- ] [x, (mem, fragment 0, 64)]
989 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
990 const DbgValueHistoryMap::InstrRanges &Ranges) {
991 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
993 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
994 const MachineInstr *Begin = I->first;
995 const MachineInstr *End = I->second;
996 assert(Begin->isDebugValue() && "Invalid History entry");
998 // Check if a variable is inaccessible in this range.
999 if (Begin->getNumOperands() > 1 &&
1000 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1005 // If this fragment overlaps with any open ranges, truncate them.
1006 const DIExpression *DIExpr = Begin->getDebugExpression();
1007 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
1008 return DIExpr->fragmentsOverlap(R.getExpression());
1010 OpenRanges.erase(Last, OpenRanges.end());
1012 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1013 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1015 const MCSymbol *EndLabel;
1017 EndLabel = getLabelAfterInsn(End);
1018 else if (std::next(I) == Ranges.end())
1019 EndLabel = Asm->getFunctionEnd();
1021 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1022 assert(EndLabel && "Forgot label after instruction ending a range!");
1024 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1026 auto Value = getDebugLocValue(Begin);
1027 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1028 bool couldMerge = false;
1030 // If this is a fragment, it may belong to the current DebugLocEntry.
1031 if (DIExpr->isFragment()) {
1032 // Add this value to the list of open ranges.
1033 OpenRanges.push_back(Value);
1035 // Attempt to add the fragment to the last entry.
1036 if (!DebugLoc.empty())
1037 if (DebugLoc.back().MergeValues(Loc))
1042 // Need to add a new DebugLocEntry. Add all values from still
1043 // valid non-overlapping fragments.
1044 if (OpenRanges.size())
1045 Loc.addValues(OpenRanges);
1047 DebugLoc.push_back(std::move(Loc));
1050 // Attempt to coalesce the ranges of two otherwise identical
1052 auto CurEntry = DebugLoc.rbegin();
1054 dbgs() << CurEntry->getValues().size() << " Values:\n";
1055 for (auto &Value : CurEntry->getValues())
1057 dbgs() << "-----\n";
1060 auto PrevEntry = std::next(CurEntry);
1061 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1062 DebugLoc.pop_back();
1066 DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU,
1067 LexicalScope &Scope,
1068 InlinedVariable IV) {
1069 ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode());
1070 ConcreteVariables.push_back(
1071 llvm::make_unique<DbgVariable>(IV.first, IV.second));
1072 InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
1073 return ConcreteVariables.back().get();
1076 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1077 /// enclosing lexical scope. The check ensures there are no other instructions
1078 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1079 /// either open or otherwise rolls off the end of the scope.
1080 static bool validThroughout(LexicalScopes &LScopes,
1081 const MachineInstr *DbgValue,
1082 const MachineInstr *RangeEnd) {
1083 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1084 auto MBB = DbgValue->getParent();
1085 auto DL = DbgValue->getDebugLoc();
1086 auto *LScope = LScopes.findLexicalScope(DL);
1087 // Scope doesn't exist; this is a dead DBG_VALUE.
1090 auto &LSRange = LScope->getRanges();
1091 if (LSRange.size() == 0)
1094 // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1095 const MachineInstr *LScopeBegin = LSRange.front().first;
1096 // Early exit if the lexical scope begins outside of the current block.
1097 if (LScopeBegin->getParent() != MBB)
1099 MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1100 for (++Pred; Pred != MBB->rend(); ++Pred) {
1101 if (Pred->getFlag(MachineInstr::FrameSetup))
1103 auto PredDL = Pred->getDebugLoc();
1104 if (!PredDL || Pred->isMetaInstruction())
1106 // Check whether the instruction preceding the DBG_VALUE is in the same
1107 // (sub)scope as the DBG_VALUE.
1108 if (DL->getScope() == PredDL->getScope())
1110 auto *PredScope = LScopes.findLexicalScope(PredDL);
1111 if (!PredScope || LScope->dominates(PredScope))
1115 // If the range of the DBG_VALUE is open-ended, report success.
1119 // Fail if there are instructions belonging to our scope in another block.
1120 const MachineInstr *LScopeEnd = LSRange.back().second;
1121 if (LScopeEnd->getParent() != MBB)
1124 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1125 // throughout the function. This is a hack, presumably for DWARF v2 and not
1126 // necessarily correct. It would be much better to use a dbg.declare instead
1127 // if we know the constant is live throughout the scope.
1128 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1134 // Find variables for each lexical scope.
1135 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
1136 const DISubprogram *SP,
1137 DenseSet<InlinedVariable> &Processed) {
1138 // Grab the variable info that was squirreled away in the MMI side-table.
1139 collectVariableInfoFromMFTable(TheCU, Processed);
1141 for (const auto &I : DbgValues) {
1142 InlinedVariable IV = I.first;
1143 if (Processed.count(IV))
1146 // Instruction ranges, specifying where IV is accessible.
1147 const auto &Ranges = I.second;
1151 LexicalScope *Scope = nullptr;
1152 if (const DILocation *IA = IV.second)
1153 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
1155 Scope = LScopes.findLexicalScope(IV.first->getScope());
1156 // If variable scope is not found then skip this variable.
1160 Processed.insert(IV);
1161 DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV);
1163 const MachineInstr *MInsn = Ranges.front().first;
1164 assert(MInsn->isDebugValue() && "History must begin with debug value");
1166 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1167 if (Ranges.size() == 1 &&
1168 validThroughout(LScopes, MInsn, Ranges.front().second)) {
1169 RegVar->initializeDbgValue(MInsn);
1173 // Handle multiple DBG_VALUE instructions describing one variable.
1174 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1176 // Build the location list for this variable.
1177 SmallVector<DebugLocEntry, 8> Entries;
1178 buildLocationList(Entries, Ranges);
1180 // If the variable has a DIBasicType, extract it. Basic types cannot have
1181 // unique identifiers, so don't bother resolving the type with the
1183 const DIBasicType *BT = dyn_cast<DIBasicType>(
1184 static_cast<const Metadata *>(IV.first->getType()));
1186 // Finalize the entry by lowering it into a DWARF bytestream.
1187 for (auto &Entry : Entries)
1188 Entry.finalize(*Asm, List, BT);
1191 // Collect info for variables that were optimized out.
1192 for (const DILocalVariable *DV : SP->getVariables()) {
1193 if (Processed.insert(InlinedVariable(DV, nullptr)).second)
1194 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
1195 createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr));
1199 // Process beginning of an instruction.
1200 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1201 DebugHandlerBase::beginInstruction(MI);
1204 const auto *SP = MI->getMF()->getFunction().getSubprogram();
1205 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1208 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1209 // If the instruction is part of the function frame setup code, do not emit
1210 // any line record, as there is no correspondence with any user code.
1211 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1213 const DebugLoc &DL = MI->getDebugLoc();
1214 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1215 // the last line number actually emitted, to see if it was line 0.
1216 unsigned LastAsmLine =
1217 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1219 if (DL == PrevInstLoc) {
1220 // If we have an ongoing unspecified location, nothing to do here.
1223 // We have an explicit location, same as the previous location.
1224 // But we might be coming back to it after a line 0 record.
1225 if (LastAsmLine == 0 && DL.getLine() != 0) {
1226 // Reinstate the source location but not marked as a statement.
1227 const MDNode *Scope = DL.getScope();
1228 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1234 // We have an unspecified location, which might want to be line 0.
1235 // If we have already emitted a line-0 record, don't repeat it.
1236 if (LastAsmLine == 0)
1238 // If user said Don't Do That, don't do that.
1239 if (UnknownLocations == Disable)
1241 // See if we have a reason to emit a line-0 record now.
1242 // Reasons to emit a line-0 record include:
1243 // - User asked for it (UnknownLocations).
1244 // - Instruction has a label, so it's referenced from somewhere else,
1245 // possibly debug information; we want it to have a source location.
1246 // - Instruction is at the top of a block; we don't want to inherit the
1247 // location from the physically previous (maybe unrelated) block.
1248 if (UnknownLocations == Enable || PrevLabel ||
1249 (PrevInstBB && PrevInstBB != MI->getParent())) {
1250 // Preserve the file and column numbers, if we can, to save space in
1251 // the encoded line table.
1252 // Do not update PrevInstLoc, it remembers the last non-0 line.
1253 const MDNode *Scope = nullptr;
1254 unsigned Column = 0;
1256 Scope = PrevInstLoc.getScope();
1257 Column = PrevInstLoc.getCol();
1259 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1264 // We have an explicit location, different from the previous location.
1265 // Don't repeat a line-0 record, but otherwise emit the new location.
1266 // (The new location might be an explicit line 0, which we do emit.)
1267 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
1270 if (DL == PrologEndLoc) {
1271 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1272 PrologEndLoc = DebugLoc();
1274 // If the line changed, we call that a new statement; unless we went to
1275 // line 0 and came back, in which case it is not a new statement.
1276 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1277 if (DL.getLine() && DL.getLine() != OldLine)
1278 Flags |= DWARF2_FLAG_IS_STMT;
1280 const MDNode *Scope = DL.getScope();
1281 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1283 // If we're not at line 0, remember this location.
1288 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1289 // First known non-DBG_VALUE and non-frame setup location marks
1290 // the beginning of the function body.
1291 for (const auto &MBB : *MF)
1292 for (const auto &MI : MBB)
1293 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1295 return MI.getDebugLoc();
1299 // Gather pre-function debug information. Assumes being called immediately
1300 // after the function entry point has been emitted.
1301 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1304 auto *SP = MF->getFunction().getSubprogram();
1305 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1306 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1309 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1311 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1312 // belongs to so that we add to the correct per-cu line table in the
1314 if (Asm->OutStreamer->hasRawTextSupport())
1315 // Use a single line table if we are generating assembly.
1316 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1318 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1320 // Record beginning of function.
1321 PrologEndLoc = findPrologueEndLoc(MF);
1323 // We'd like to list the prologue as "not statements" but GDB behaves
1324 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1325 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1326 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1330 void DwarfDebug::skippedNonDebugFunction() {
1331 // If we don't have a subprogram for this function then there will be a hole
1332 // in the range information. Keep note of this by setting the previously used
1333 // section to nullptr.
1338 // Gather and emit post-function debug information.
1339 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1340 const DISubprogram *SP = MF->getFunction().getSubprogram();
1342 assert(CurFn == MF &&
1343 "endFunction should be called with the same function as beginFunction");
1345 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1346 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1348 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1349 assert(!FnScope || SP == FnScope->getScopeNode());
1350 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1352 DenseSet<InlinedVariable> ProcessedVars;
1353 collectVariableInfo(TheCU, SP, ProcessedVars);
1355 // Add the range of this function to the list of ranges for the CU.
1356 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1358 // Under -gmlt, skip building the subprogram if there are no inlined
1359 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1360 // is still needed as we need its source location.
1361 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1362 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1363 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1364 assert(InfoHolder.getScopeVariables().empty());
1365 PrevLabel = nullptr;
1371 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1373 // Construct abstract scopes.
1374 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1375 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1376 // Collect info for variables that were optimized out.
1377 for (const DILocalVariable *DV : SP->getVariables()) {
1378 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1380 ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr),
1382 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1383 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1385 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1388 ProcessedSPNodes.insert(SP);
1389 TheCU.constructSubprogramScopeDIE(SP, FnScope);
1390 if (auto *SkelCU = TheCU.getSkeleton())
1391 if (!LScopes.getAbstractScopesList().empty() &&
1392 TheCU.getCUNode()->getSplitDebugInlining())
1393 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1396 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1397 // DbgVariables except those that are also in AbstractVariables (since they
1398 // can be used cross-function)
1399 InfoHolder.getScopeVariables().clear();
1400 PrevLabel = nullptr;
1404 // Register a source line with debug info. Returns the unique label that was
1405 // emitted and which provides correspondence to the source line list.
1406 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1409 unsigned FileNo = 1;
1410 unsigned Discriminator = 0;
1411 if (auto *Scope = cast_or_null<DIScope>(S)) {
1412 Fn = Scope->getFilename();
1413 if (Line != 0 && getDwarfVersion() >= 4)
1414 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1415 Discriminator = LBF->getDiscriminator();
1417 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1418 FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1419 .getOrCreateSourceID(Scope->getFile());
1421 Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1425 //===----------------------------------------------------------------------===//
1427 //===----------------------------------------------------------------------===//
1429 // Emit the debug info section.
1430 void DwarfDebug::emitDebugInfo() {
1431 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1432 Holder.emitUnits(/* UseOffsets */ false);
1435 // Emit the abbreviation section.
1436 void DwarfDebug::emitAbbreviations() {
1437 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1439 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1442 void DwarfDebug::emitStringOffsetsTableHeader() {
1443 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1444 Holder.emitStringOffsetsTableHeader(
1445 Asm->getObjFileLowering().getDwarfStrOffSection());
1448 template <typename AccelTableT>
1449 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1450 StringRef TableName) {
1451 Asm->OutStreamer->SwitchSection(Section);
1453 // Emit the full data.
1454 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1457 // Emit visible names into a hashed accelerator table section.
1458 void DwarfDebug::emitAccelNames() {
1459 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1463 // Emit objective C classes and categories into a hashed accelerator table
1465 void DwarfDebug::emitAccelObjC() {
1466 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1470 // Emit namespace dies into a hashed accelerator table.
1471 void DwarfDebug::emitAccelNamespaces() {
1472 emitAccel(AccelNamespace,
1473 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1477 // Emit type dies into a hashed accelerator table.
1478 void DwarfDebug::emitAccelTypes() {
1479 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1483 // Public name handling.
1484 // The format for the various pubnames:
1486 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1487 // for the DIE that is named.
1489 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1490 // into the CU and the index value is computed according to the type of value
1491 // for the DIE that is named.
1493 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1494 // it's the offset within the debug_info/debug_types dwo section, however, the
1495 // reference in the pubname header doesn't change.
1497 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1498 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1500 // Entities that ended up only in a Type Unit reference the CU instead (since
1501 // the pub entry has offsets within the CU there's no real offset that can be
1502 // provided anyway). As it happens all such entities (namespaces and types,
1503 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1504 // not to be true it would be necessary to persist this information from the
1505 // point at which the entry is added to the index data structure - since by
1506 // the time the index is built from that, the original type/namespace DIE in a
1507 // type unit has already been destroyed so it can't be queried for properties
1509 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1510 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1511 dwarf::GIEL_EXTERNAL);
1512 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1514 // We could have a specification DIE that has our most of our knowledge,
1515 // look for that now.
1516 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1517 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1518 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1519 Linkage = dwarf::GIEL_EXTERNAL;
1520 } else if (Die->findAttribute(dwarf::DW_AT_external))
1521 Linkage = dwarf::GIEL_EXTERNAL;
1523 switch (Die->getTag()) {
1524 case dwarf::DW_TAG_class_type:
1525 case dwarf::DW_TAG_structure_type:
1526 case dwarf::DW_TAG_union_type:
1527 case dwarf::DW_TAG_enumeration_type:
1528 return dwarf::PubIndexEntryDescriptor(
1529 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1530 ? dwarf::GIEL_STATIC
1531 : dwarf::GIEL_EXTERNAL);
1532 case dwarf::DW_TAG_typedef:
1533 case dwarf::DW_TAG_base_type:
1534 case dwarf::DW_TAG_subrange_type:
1535 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1536 case dwarf::DW_TAG_namespace:
1537 return dwarf::GIEK_TYPE;
1538 case dwarf::DW_TAG_subprogram:
1539 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1540 case dwarf::DW_TAG_variable:
1541 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1542 case dwarf::DW_TAG_enumerator:
1543 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1544 dwarf::GIEL_STATIC);
1546 return dwarf::GIEK_NONE;
1550 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
1551 /// pubtypes sections.
1552 void DwarfDebug::emitDebugPubSections() {
1553 for (const auto &NU : CUMap) {
1554 DwarfCompileUnit *TheU = NU.second;
1555 if (!TheU->hasDwarfPubSections())
1558 bool GnuStyle = TheU->getCUNode()->getGnuPubnames();
1560 Asm->OutStreamer->SwitchSection(
1561 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1562 : Asm->getObjFileLowering().getDwarfPubNamesSection());
1563 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
1565 Asm->OutStreamer->SwitchSection(
1566 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1567 : Asm->getObjFileLowering().getDwarfPubTypesSection());
1568 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
1572 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
1573 if (useSectionsAsReferences())
1574 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
1575 CU.getDebugSectionOffset());
1577 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
1580 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1581 DwarfCompileUnit *TheU,
1582 const StringMap<const DIE *> &Globals) {
1583 if (auto *Skeleton = TheU->getSkeleton())
1587 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1588 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1589 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1590 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1592 Asm->OutStreamer->EmitLabel(BeginLabel);
1594 Asm->OutStreamer->AddComment("DWARF Version");
1595 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1597 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1598 emitSectionReference(*TheU);
1600 Asm->OutStreamer->AddComment("Compilation Unit Length");
1601 Asm->EmitInt32(TheU->getLength());
1603 // Emit the pubnames for this compilation unit.
1604 for (const auto &GI : Globals) {
1605 const char *Name = GI.getKeyData();
1606 const DIE *Entity = GI.second;
1608 Asm->OutStreamer->AddComment("DIE offset");
1609 Asm->EmitInt32(Entity->getOffset());
1612 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1613 Asm->OutStreamer->AddComment(
1614 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1615 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1616 Asm->EmitInt8(Desc.toBits());
1619 Asm->OutStreamer->AddComment("External Name");
1620 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1623 Asm->OutStreamer->AddComment("End Mark");
1625 Asm->OutStreamer->EmitLabel(EndLabel);
1628 /// Emit null-terminated strings into a debug str section.
1629 void DwarfDebug::emitDebugStr() {
1630 MCSection *StringOffsetsSection = nullptr;
1631 if (useSegmentedStringOffsetsTable()) {
1632 emitStringOffsetsTableHeader();
1633 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1635 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1636 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
1637 StringOffsetsSection, /* UseRelativeOffsets = */ true);
1640 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1641 const DebugLocStream::Entry &Entry) {
1642 auto &&Comments = DebugLocs.getComments(Entry);
1643 auto Comment = Comments.begin();
1644 auto End = Comments.end();
1645 for (uint8_t Byte : DebugLocs.getBytes(Entry))
1646 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1649 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1650 ByteStreamer &Streamer,
1651 const DebugLocEntry::Value &Value,
1652 DwarfExpression &DwarfExpr) {
1653 auto *DIExpr = Value.getExpression();
1654 DIExpressionCursor ExprCursor(DIExpr);
1655 DwarfExpr.addFragmentOffset(DIExpr);
1657 if (Value.isInt()) {
1658 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1659 BT->getEncoding() == dwarf::DW_ATE_signed_char))
1660 DwarfExpr.addSignedConstant(Value.getInt());
1662 DwarfExpr.addUnsignedConstant(Value.getInt());
1663 } else if (Value.isLocation()) {
1664 MachineLocation Location = Value.getLoc();
1665 if (Location.isIndirect())
1666 DwarfExpr.setMemoryLocationKind();
1667 DIExpressionCursor Cursor(DIExpr);
1668 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1669 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1671 return DwarfExpr.addExpression(std::move(Cursor));
1672 } else if (Value.isConstantFP()) {
1673 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1674 DwarfExpr.addUnsignedConstant(RawBytes);
1676 DwarfExpr.addExpression(std::move(ExprCursor));
1679 void DebugLocEntry::finalize(const AsmPrinter &AP,
1680 DebugLocStream::ListBuilder &List,
1681 const DIBasicType *BT) {
1682 DebugLocStream::EntryBuilder Entry(List, Begin, End);
1683 BufferByteStreamer Streamer = Entry.getStreamer();
1684 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
1685 const DebugLocEntry::Value &Value = Values[0];
1686 if (Value.isFragment()) {
1687 // Emit all fragments that belong to the same variable and range.
1688 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
1689 return P.isFragment();
1690 }) && "all values are expected to be fragments");
1691 assert(std::is_sorted(Values.begin(), Values.end()) &&
1692 "fragments are expected to be sorted");
1694 for (auto Fragment : Values)
1695 emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr);
1698 assert(Values.size() == 1 && "only fragments may have >1 value");
1699 emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr);
1701 DwarfExpr.finalize();
1704 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1706 Asm->OutStreamer->AddComment("Loc expr size");
1707 Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1710 APByteStreamer Streamer(*Asm);
1711 emitDebugLocEntry(Streamer, Entry);
1714 // Emit locations into the debug loc section.
1715 void DwarfDebug::emitDebugLoc() {
1716 if (DebugLocs.getLists().empty())
1719 // Start the dwarf loc section.
1720 Asm->OutStreamer->SwitchSection(
1721 Asm->getObjFileLowering().getDwarfLocSection());
1722 unsigned char Size = Asm->MAI->getCodePointerSize();
1723 for (const auto &List : DebugLocs.getLists()) {
1724 Asm->OutStreamer->EmitLabel(List.Label);
1725 const DwarfCompileUnit *CU = List.CU;
1726 for (const auto &Entry : DebugLocs.getEntries(List)) {
1727 // Set up the range. This range is relative to the entry point of the
1728 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1729 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1730 if (auto *Base = CU->getBaseAddress()) {
1731 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1732 Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1734 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1735 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1738 emitDebugLocEntryLocation(Entry);
1740 Asm->OutStreamer->EmitIntValue(0, Size);
1741 Asm->OutStreamer->EmitIntValue(0, Size);
1745 void DwarfDebug::emitDebugLocDWO() {
1746 Asm->OutStreamer->SwitchSection(
1747 Asm->getObjFileLowering().getDwarfLocDWOSection());
1748 for (const auto &List : DebugLocs.getLists()) {
1749 Asm->OutStreamer->EmitLabel(List.Label);
1750 for (const auto &Entry : DebugLocs.getEntries(List)) {
1751 // Just always use start_length for now - at least that's one address
1752 // rather than two. We could get fancier and try to, say, reuse an
1753 // address we know we've emitted elsewhere (the start of the function?
1754 // The start of the CU or CU subrange that encloses this range?)
1755 Asm->EmitInt8(dwarf::DW_LLE_startx_length);
1756 unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1757 Asm->EmitULEB128(idx);
1758 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1760 emitDebugLocEntryLocation(Entry);
1762 Asm->EmitInt8(dwarf::DW_LLE_end_of_list);
1767 const MCSymbol *Start, *End;
1770 // Emit a debug aranges section, containing a CU lookup for any
1771 // address we can tie back to a CU.
1772 void DwarfDebug::emitDebugARanges() {
1773 // Provides a unique id per text section.
1774 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1776 // Filter labels by section.
1777 for (const SymbolCU &SCU : ArangeLabels) {
1778 if (SCU.Sym->isInSection()) {
1779 // Make a note of this symbol and it's section.
1780 MCSection *Section = &SCU.Sym->getSection();
1781 if (!Section->getKind().isMetadata())
1782 SectionMap[Section].push_back(SCU);
1784 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1785 // appear in the output. This sucks as we rely on sections to build
1786 // arange spans. We can do it without, but it's icky.
1787 SectionMap[nullptr].push_back(SCU);
1791 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1793 for (auto &I : SectionMap) {
1794 MCSection *Section = I.first;
1795 SmallVector<SymbolCU, 8> &List = I.second;
1796 if (List.size() < 1)
1799 // If we have no section (e.g. common), just write out
1800 // individual spans for each symbol.
1802 for (const SymbolCU &Cur : List) {
1804 Span.Start = Cur.Sym;
1807 Spans[Cur.CU].push_back(Span);
1812 // Sort the symbols by offset within the section.
1814 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
1815 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1816 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1818 // Symbols with no order assigned should be placed at the end.
1819 // (e.g. section end labels)
1827 // Insert a final terminator.
1828 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
1830 // Build spans between each label.
1831 const MCSymbol *StartSym = List[0].Sym;
1832 for (size_t n = 1, e = List.size(); n < e; n++) {
1833 const SymbolCU &Prev = List[n - 1];
1834 const SymbolCU &Cur = List[n];
1836 // Try and build the longest span we can within the same CU.
1837 if (Cur.CU != Prev.CU) {
1839 Span.Start = StartSym;
1842 Spans[Prev.CU].push_back(Span);
1848 // Start the dwarf aranges section.
1849 Asm->OutStreamer->SwitchSection(
1850 Asm->getObjFileLowering().getDwarfARangesSection());
1852 unsigned PtrSize = Asm->MAI->getCodePointerSize();
1854 // Build a list of CUs used.
1855 std::vector<DwarfCompileUnit *> CUs;
1856 for (const auto &it : Spans) {
1857 DwarfCompileUnit *CU = it.first;
1861 // Sort the CU list (again, to ensure consistent output order).
1862 std::sort(CUs.begin(), CUs.end(),
1863 [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
1864 return A->getUniqueID() < B->getUniqueID();
1867 // Emit an arange table for each CU we used.
1868 for (DwarfCompileUnit *CU : CUs) {
1869 std::vector<ArangeSpan> &List = Spans[CU];
1871 // Describe the skeleton CU's offset and length, not the dwo file's.
1872 if (auto *Skel = CU->getSkeleton())
1875 // Emit size of content not including length itself.
1876 unsigned ContentSize =
1877 sizeof(int16_t) + // DWARF ARange version number
1878 sizeof(int32_t) + // Offset of CU in the .debug_info section
1879 sizeof(int8_t) + // Pointer Size (in bytes)
1880 sizeof(int8_t); // Segment Size (in bytes)
1882 unsigned TupleSize = PtrSize * 2;
1884 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1886 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1888 ContentSize += Padding;
1889 ContentSize += (List.size() + 1) * TupleSize;
1891 // For each compile unit, write the list of spans it covers.
1892 Asm->OutStreamer->AddComment("Length of ARange Set");
1893 Asm->EmitInt32(ContentSize);
1894 Asm->OutStreamer->AddComment("DWARF Arange version number");
1895 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1896 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1897 emitSectionReference(*CU);
1898 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1899 Asm->EmitInt8(PtrSize);
1900 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1903 Asm->OutStreamer->emitFill(Padding, 0xff);
1905 for (const ArangeSpan &Span : List) {
1906 Asm->EmitLabelReference(Span.Start, PtrSize);
1908 // Calculate the size as being from the span start to it's end.
1910 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1912 // For symbols without an end marker (e.g. common), we
1913 // write a single arange entry containing just that one symbol.
1914 uint64_t Size = SymSize[Span.Start];
1918 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1922 Asm->OutStreamer->AddComment("ARange terminator");
1923 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1924 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1928 /// Emit address ranges into a debug ranges section.
1929 void DwarfDebug::emitDebugRanges() {
1933 if (!useRangesSection()) {
1934 assert(llvm::all_of(
1936 [](const decltype(CUMap)::const_iterator::value_type &Pair) {
1937 return Pair.second->getRangeLists().empty();
1939 "No debug ranges expected.");
1943 // Start the dwarf ranges section.
1944 Asm->OutStreamer->SwitchSection(
1945 Asm->getObjFileLowering().getDwarfRangesSection());
1947 // Size for our labels.
1948 unsigned char Size = Asm->MAI->getCodePointerSize();
1950 // Grab the specific ranges for the compile units in the module.
1951 for (const auto &I : CUMap) {
1952 DwarfCompileUnit *TheCU = I.second;
1954 if (auto *Skel = TheCU->getSkeleton())
1957 // Iterate over the misc ranges for the compile units in the module.
1958 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1959 // Emit our symbol so we can find the beginning of the range.
1960 Asm->OutStreamer->EmitLabel(List.getSym());
1962 // Gather all the ranges that apply to the same section so they can share
1963 // a base address entry.
1964 MapVector<const MCSection *, std::vector<const RangeSpan *>> MV;
1965 for (const RangeSpan &Range : List.getRanges()) {
1966 MV[&Range.getStart()->getSection()].push_back(&Range);
1969 auto *CUBase = TheCU->getBaseAddress();
1970 bool BaseIsSet = false;
1971 for (const auto &P : MV) {
1972 // Don't bother with a base address entry if there's only one range in
1973 // this section in this range list - for example ranges for a CU will
1974 // usually consist of single regions from each of many sections
1975 // (-ffunction-sections, or just C++ inline functions) except under LTO
1976 // or optnone where there may be holes in a single CU's section
1978 auto *Base = CUBase;
1979 if (!Base && P.second.size() > 1 &&
1980 UseDwarfRangesBaseAddressSpecifier) {
1982 // FIXME/use care: This may not be a useful base address if it's not
1983 // the lowest address/range in this object.
1984 Base = P.second.front()->getStart();
1985 Asm->OutStreamer->EmitIntValue(-1, Size);
1986 Asm->OutStreamer->EmitSymbolValue(Base, Size);
1987 } else if (BaseIsSet) {
1989 Asm->OutStreamer->EmitIntValue(-1, Size);
1990 Asm->OutStreamer->EmitIntValue(0, Size);
1993 for (const auto *RS : P.second) {
1994 const MCSymbol *Begin = RS->getStart();
1995 const MCSymbol *End = RS->getEnd();
1996 assert(Begin && "Range without a begin symbol?");
1997 assert(End && "Range without an end symbol?");
1999 Asm->EmitLabelDifference(Begin, Base, Size);
2000 Asm->EmitLabelDifference(End, Base, Size);
2002 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2003 Asm->OutStreamer->EmitSymbolValue(End, Size);
2008 // And terminate the list with two 0 values.
2009 Asm->OutStreamer->EmitIntValue(0, Size);
2010 Asm->OutStreamer->EmitIntValue(0, Size);
2015 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2016 for (auto *MN : Nodes) {
2017 if (auto *M = dyn_cast<DIMacro>(MN))
2019 else if (auto *F = dyn_cast<DIMacroFile>(MN))
2020 emitMacroFile(*F, U);
2022 llvm_unreachable("Unexpected DI type!");
2026 void DwarfDebug::emitMacro(DIMacro &M) {
2027 Asm->EmitULEB128(M.getMacinfoType());
2028 Asm->EmitULEB128(M.getLine());
2029 StringRef Name = M.getName();
2030 StringRef Value = M.getValue();
2031 Asm->OutStreamer->EmitBytes(Name);
2032 if (!Value.empty()) {
2033 // There should be one space between macro name and macro value.
2035 Asm->OutStreamer->EmitBytes(Value);
2037 Asm->EmitInt8('\0');
2040 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2041 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2042 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2043 Asm->EmitULEB128(F.getLine());
2044 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
2045 handleMacroNodes(F.getElements(), U);
2046 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2049 /// Emit macros into a debug macinfo section.
2050 void DwarfDebug::emitDebugMacinfo() {
2054 // Start the dwarf macinfo section.
2055 Asm->OutStreamer->SwitchSection(
2056 Asm->getObjFileLowering().getDwarfMacinfoSection());
2058 for (const auto &P : CUMap) {
2059 auto &TheCU = *P.second;
2060 auto *SkCU = TheCU.getSkeleton();
2061 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2062 auto *CUNode = cast<DICompileUnit>(P.first);
2063 DIMacroNodeArray Macros = CUNode->getMacros();
2064 if (!Macros.empty()) {
2065 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2066 handleMacroNodes(Macros, U);
2069 Asm->OutStreamer->AddComment("End Of Macro List Mark");
2073 // DWARF5 Experimental Separate Dwarf emitters.
2075 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2076 std::unique_ptr<DwarfCompileUnit> NewU) {
2077 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2078 Asm->TM.Options.MCOptions.SplitDwarfFile);
2080 if (!CompilationDir.empty())
2081 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2083 addGnuPubAttributes(*NewU, Die);
2085 SkeletonHolder.addUnit(std::move(NewU));
2088 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2089 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2090 // DW_AT_addr_base, DW_AT_ranges_base.
2091 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2093 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
2094 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2095 DwarfCompileUnit &NewCU = *OwnedUnit;
2096 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2098 NewCU.initStmtList();
2100 if (useSegmentedStringOffsetsTable())
2101 NewCU.addStringOffsetsStart();
2103 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2108 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2109 // compile units that would normally be in debug_info.
2110 void DwarfDebug::emitDebugInfoDWO() {
2111 assert(useSplitDwarf() && "No split dwarf debug info?");
2112 // Don't emit relocations into the dwo file.
2113 InfoHolder.emitUnits(/* UseOffsets */ true);
2116 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2117 // abbreviations for the .debug_info.dwo section.
2118 void DwarfDebug::emitDebugAbbrevDWO() {
2119 assert(useSplitDwarf() && "No split dwarf?");
2120 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2123 void DwarfDebug::emitDebugLineDWO() {
2124 assert(useSplitDwarf() && "No split dwarf?");
2125 SplitTypeUnitFileTable.Emit(
2126 *Asm->OutStreamer, MCDwarfLineTableParams(),
2127 Asm->getObjFileLowering().getDwarfLineDWOSection());
2130 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2131 assert(useSplitDwarf() && "No split dwarf?");
2132 InfoHolder.emitStringOffsetsTableHeader(
2133 Asm->getObjFileLowering().getDwarfStrOffDWOSection());
2136 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2137 // string section and is identical in format to traditional .debug_str
2139 void DwarfDebug::emitDebugStrDWO() {
2140 if (useSegmentedStringOffsetsTable())
2141 emitStringOffsetsTableHeaderDWO();
2142 assert(useSplitDwarf() && "No split dwarf?");
2143 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2144 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2145 OffSec, /* UseRelativeOffsets = */ false);
2148 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2149 if (!useSplitDwarf())
2152 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
2153 return &SplitTypeUnitFileTable;
2156 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2158 Hash.update(Identifier);
2159 // ... take the least significant 8 bytes and return those. Our MD5
2160 // implementation always returns its results in little endian, so we actually
2161 // need the "high" word.
2162 MD5::MD5Result Result;
2164 return Result.high();
2167 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2168 StringRef Identifier, DIE &RefDie,
2169 const DICompositeType *CTy) {
2170 // Fast path if we're building some type units and one has already used the
2171 // address pool we know we're going to throw away all this work anyway, so
2172 // don't bother building dependent types.
2173 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2176 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2178 CU.addDIETypeSignature(RefDie, Ins.first->second);
2182 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2183 AddrPool.resetUsedFlag();
2185 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2186 getDwoLineTable(CU));
2187 DwarfTypeUnit &NewTU = *OwnedUnit;
2188 DIE &UnitDie = NewTU.getUnitDie();
2189 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2191 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2194 uint64_t Signature = makeTypeSignature(Identifier);
2195 NewTU.setTypeSignature(Signature);
2196 Ins.first->second = Signature;
2198 if (useSplitDwarf())
2199 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2201 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2202 // Non-split type units reuse the compile unit's line table.
2203 CU.applyStmtList(UnitDie);
2206 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2208 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2209 NewTU.addStringOffsetsStart();
2211 NewTU.setType(NewTU.createTypeDIE(CTy));
2214 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2215 TypeUnitsUnderConstruction.clear();
2217 // Types referencing entries in the address table cannot be placed in type
2219 if (AddrPool.hasBeenUsed()) {
2221 // Remove all the types built while building this type.
2222 // This is pessimistic as some of these types might not be dependent on
2223 // the type that used an address.
2224 for (const auto &TU : TypeUnitsToAdd)
2225 TypeSignatures.erase(TU.second);
2227 // Construct this type in the CU directly.
2228 // This is inefficient because all the dependent types will be rebuilt
2229 // from scratch, including building them in type units, discovering that
2230 // they depend on addresses, throwing them out and rebuilding them.
2231 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2235 // If the type wasn't dependent on fission addresses, finish adding the type
2236 // and all its dependent types.
2237 for (auto &TU : TypeUnitsToAdd) {
2238 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2239 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2242 CU.addDIETypeSignature(RefDie, Signature);
2245 // Accelerator table mutators - add each name along with its companion
2246 // DIE to the proper table while ensuring that the name that we're going
2247 // to reference is in the string table. We do this since the names we
2248 // add may not only be identical to the names in the DIE.
2249 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2250 if (!useDwarfAccelTables())
2252 AccelNames.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2255 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2256 if (!useDwarfAccelTables())
2258 AccelObjC.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2261 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2262 if (!useDwarfAccelTables())
2264 AccelNamespace.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2267 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2268 if (!useDwarfAccelTables())
2270 AccelTypes.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2273 uint16_t DwarfDebug::getDwarfVersion() const {
2274 return Asm->OutStreamer->getContext().getDwarfVersion();