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/TargetLoweringObjectFile.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/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 enum LinkageNameOption {
124 static cl::opt<LinkageNameOption>
125 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
126 cl::desc("Which DWARF linkage-name attributes to emit."),
127 cl::values(clEnumValN(DefaultLinkageNames, "Default",
128 "Default for platform"),
129 clEnumValN(AllLinkageNames, "All", "All"),
130 clEnumValN(AbstractLinkageNames, "Abstract",
131 "Abstract subprograms")),
132 cl::init(DefaultLinkageNames));
134 static const char *const DWARFGroupName = "dwarf";
135 static const char *const DWARFGroupDescription = "DWARF Emission";
136 static const char *const DbgTimerName = "writer";
137 static const char *const DbgTimerDescription = "DWARF Debug Writer";
139 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
141 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
142 : dwarf::OperationEncodingString(Op));
145 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
146 BS.EmitSLEB128(Value, Twine(Value));
149 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
150 BS.EmitULEB128(Value, Twine(Value));
153 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
154 unsigned MachineReg) {
155 // This information is not available while emitting .debug_loc entries.
159 bool DbgVariable::isBlockByrefVariable() const {
160 assert(Var && "Invalid complex DbgVariable!");
161 return Var->getType().resolve()->isBlockByrefStruct();
164 const DIType *DbgVariable::getType() const {
165 DIType *Ty = Var->getType().resolve();
166 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
167 // addresses instead.
168 if (Ty->isBlockByrefStruct()) {
169 /* Byref variables, in Blocks, are declared by the programmer as
170 "SomeType VarName;", but the compiler creates a
171 __Block_byref_x_VarName struct, and gives the variable VarName
172 either the struct, or a pointer to the struct, as its type. This
173 is necessary for various behind-the-scenes things the compiler
174 needs to do with by-reference variables in blocks.
176 However, as far as the original *programmer* is concerned, the
177 variable should still have type 'SomeType', as originally declared.
179 The following function dives into the __Block_byref_x_VarName
180 struct to find the original type of the variable. This will be
181 passed back to the code generating the type for the Debug
182 Information Entry for the variable 'VarName'. 'VarName' will then
183 have the original type 'SomeType' in its debug information.
185 The original type 'SomeType' will be the type of the field named
186 'VarName' inside the __Block_byref_x_VarName struct.
188 NOTE: In order for this to not completely fail on the debugger
189 side, the Debug Information Entry for the variable VarName needs to
190 have a DW_AT_location that tells the debugger how to unwind through
191 the pointers and __Block_byref_x_VarName struct to find the actual
192 value of the variable. The function addBlockByrefType does this. */
193 DIType *subType = Ty;
194 uint16_t tag = Ty->getTag();
196 if (tag == dwarf::DW_TAG_pointer_type)
197 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
199 auto Elements = cast<DICompositeType>(subType)->getElements();
200 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
201 auto *DT = cast<DIDerivedType>(Elements[i]);
202 if (getName() == DT->getName())
203 return resolve(DT->getBaseType());
209 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
210 if (FrameIndexExprs.size() == 1)
211 return FrameIndexExprs;
213 assert(llvm::all_of(FrameIndexExprs,
214 [](const FrameIndexExpr &A) {
215 return A.Expr->isFragment();
217 "multiple FI expressions without DW_OP_LLVM_fragment");
218 std::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(),
219 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
220 return A.Expr->getFragmentInfo()->OffsetInBits <
221 B.Expr->getFragmentInfo()->OffsetInBits;
224 return FrameIndexExprs;
227 void DbgVariable::addMMIEntry(const DbgVariable &V) {
228 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
229 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
230 assert(V.Var == Var && "conflicting variable");
231 assert(V.IA == IA && "conflicting inlined-at location");
233 assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
234 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
236 // FIXME: This logic should not be necessary anymore, as we now have proper
237 // deduplication. However, without it, we currently run into the assertion
238 // below, which means that we are likely dealing with broken input, i.e. two
239 // non-fragment entries for the same variable at different frame indices.
240 if (FrameIndexExprs.size()) {
241 auto *Expr = FrameIndexExprs.back().Expr;
242 if (!Expr || !Expr->isFragment())
246 for (const auto &FIE : V.FrameIndexExprs)
247 // Ignore duplicate entries.
248 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
249 return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
251 FrameIndexExprs.push_back(FIE);
253 assert((FrameIndexExprs.size() == 1 ||
254 llvm::all_of(FrameIndexExprs,
255 [](FrameIndexExpr &FIE) {
256 return FIE.Expr && FIE.Expr->isFragment();
258 "conflicting locations for variable");
261 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
262 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
263 InfoHolder(A, "info_string", DIEValueAllocator),
264 SkeletonHolder(A, "skel_string", DIEValueAllocator),
265 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
266 const Triple &TT = Asm->TM.getTargetTriple();
268 // Make sure we know our "debugger tuning." The target option takes
269 // precedence; fall back to triple-based defaults.
270 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
271 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
273 DebuggerTuning = DebuggerKind::LLDB;
274 else if (TT.isPS4CPU())
275 DebuggerTuning = DebuggerKind::SCE;
277 DebuggerTuning = DebuggerKind::GDB;
279 // Turn on accelerator tables by default, if tuning for LLDB and the target is
281 if (DwarfAccelTables == Default)
282 HasDwarfAccelTables =
283 tuneForLLDB() && A->TM.getTargetTriple().isOSBinFormatMachO();
285 HasDwarfAccelTables = DwarfAccelTables == Enable;
287 HasAppleExtensionAttributes = tuneForLLDB();
289 // Handle split DWARF.
290 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
292 // SCE defaults to linkage names only for abstract subprograms.
293 if (DwarfLinkageNames == DefaultLinkageNames)
294 UseAllLinkageNames = !tuneForSCE();
296 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
298 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
299 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
300 : MMI->getModule()->getDwarfVersion();
301 // Use dwarf 4 by default if nothing is requested.
302 DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
304 // Work around a GDB bug. GDB doesn't support the standard opcode;
305 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
306 // is defined as of DWARF 3.
307 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
308 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
309 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
311 // GDB does not fully support the DWARF 4 representation for bitfields.
312 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
314 // The DWARF v5 string offsets table has - possibly shared - contributions
315 // from each compile and type unit each preceded by a header. The string
316 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
317 // a monolithic string offsets table without any header.
318 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
320 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
323 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
324 DwarfDebug::~DwarfDebug() = default;
326 static bool isObjCClass(StringRef Name) {
327 return Name.startswith("+") || Name.startswith("-");
330 static bool hasObjCCategory(StringRef Name) {
331 if (!isObjCClass(Name))
334 return Name.find(") ") != StringRef::npos;
337 static void getObjCClassCategory(StringRef In, StringRef &Class,
338 StringRef &Category) {
339 if (!hasObjCCategory(In)) {
340 Class = In.slice(In.find('[') + 1, In.find(' '));
345 Class = In.slice(In.find('[') + 1, In.find('('));
346 Category = In.slice(In.find('[') + 1, In.find(' '));
349 static StringRef getObjCMethodName(StringRef In) {
350 return In.slice(In.find(' ') + 1, In.find(']'));
353 // Add the various names to the Dwarf accelerator table names.
354 // TODO: Determine whether or not we should add names for programs
355 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
356 // is only slightly different than the lookup of non-standard ObjC names.
357 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
358 if (!SP->isDefinition())
360 addAccelName(SP->getName(), Die);
362 // If the linkage name is different than the name, go ahead and output
363 // that as well into the name table.
364 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
365 addAccelName(SP->getLinkageName(), Die);
367 // If this is an Objective-C selector name add it to the ObjC accelerator
369 if (isObjCClass(SP->getName())) {
370 StringRef Class, Category;
371 getObjCClassCategory(SP->getName(), Class, Category);
372 addAccelObjC(Class, Die);
374 addAccelObjC(Category, Die);
375 // Also add the base method name to the name table.
376 addAccelName(getObjCMethodName(SP->getName()), Die);
380 /// Check whether we should create a DIE for the given Scope, return true
381 /// if we don't create a DIE (the corresponding DIE is null).
382 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
383 if (Scope->isAbstractScope())
386 // We don't create a DIE if there is no Range.
387 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
391 if (Ranges.size() > 1)
394 // We don't create a DIE if we have a single Range and the end label
396 return !getLabelAfterInsn(Ranges.front().second);
399 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
401 if (auto *SkelCU = CU.getSkeleton())
402 if (CU.getCUNode()->getSplitDebugInlining())
406 bool DwarfDebug::shareAcrossDWOCUs() const {
407 return SplitDwarfCrossCuReferences;
410 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
411 LexicalScope *Scope) {
412 assert(Scope && Scope->getScopeNode());
413 assert(Scope->isAbstractScope());
414 assert(!Scope->getInlinedAt());
416 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
418 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
419 // was inlined from another compile unit.
420 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
421 // Avoid building the original CU if it won't be used
422 SrcCU.constructAbstractSubprogramScopeDIE(Scope);
424 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
425 if (auto *SkelCU = CU.getSkeleton()) {
426 (shareAcrossDWOCUs() ? CU : SrcCU)
427 .constructAbstractSubprogramScopeDIE(Scope);
428 if (CU.getCUNode()->getSplitDebugInlining())
429 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
431 CU.constructAbstractSubprogramScopeDIE(Scope);
435 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
436 if (!U.hasDwarfPubSections())
439 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
442 // Create new DwarfCompileUnit for the given metadata node with tag
443 // DW_TAG_compile_unit.
445 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
446 if (auto *CU = CUMap.lookup(DIUnit))
448 StringRef FN = DIUnit->getFilename();
449 CompilationDir = DIUnit->getDirectory();
451 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
452 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
453 DwarfCompileUnit &NewCU = *OwnedUnit;
454 DIE &Die = NewCU.getUnitDie();
455 InfoHolder.addUnit(std::move(OwnedUnit));
456 if (useSplitDwarf()) {
457 NewCU.setSkeleton(constructSkeletonCU(NewCU));
458 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
459 Asm->TM.Options.MCOptions.SplitDwarfFile);
462 for (auto *IE : DIUnit->getImportedEntities())
463 NewCU.addImportedEntity(IE);
465 // LTO with assembly output shares a single line table amongst multiple CUs.
466 // To avoid the compilation directory being ambiguous, let the line table
467 // explicitly describe the directory of all files, never relying on the
468 // compilation directory.
469 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
470 Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
471 NewCU.getUniqueID(), CompilationDir);
473 StringRef Producer = DIUnit->getProducer();
474 StringRef Flags = DIUnit->getFlags();
475 if (!Flags.empty()) {
476 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
477 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
479 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
481 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
482 DIUnit->getSourceLanguage());
483 NewCU.addString(Die, dwarf::DW_AT_name, FN);
485 // Add DW_str_offsets_base to the unit DIE, except for split units.
486 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
487 NewCU.addStringOffsetsStart();
489 if (!useSplitDwarf()) {
490 NewCU.initStmtList();
492 // If we're using split dwarf the compilation dir is going to be in the
493 // skeleton CU and so we don't need to duplicate it here.
494 if (!CompilationDir.empty())
495 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
497 addGnuPubAttributes(NewCU, Die);
500 if (useAppleExtensionAttributes()) {
501 if (DIUnit->isOptimized())
502 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
504 StringRef Flags = DIUnit->getFlags();
506 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
508 if (unsigned RVer = DIUnit->getRuntimeVersion())
509 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
510 dwarf::DW_FORM_data1, RVer);
514 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
516 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
518 if (DIUnit->getDWOId()) {
519 // This CU is either a clang module DWO or a skeleton CU.
520 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
522 if (!DIUnit->getSplitDebugFilename().empty())
523 // This is a prefabricated skeleton CU.
524 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
525 DIUnit->getSplitDebugFilename());
528 CUMap.insert({DIUnit, &NewCU});
529 CUDieMap.insert({&Die, &NewCU});
533 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
534 const DIImportedEntity *N) {
535 if (isa<DILocalScope>(N->getScope()))
537 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
538 D->addChild(TheCU.constructImportedEntityDIE(N));
541 /// Sort and unique GVEs by comparing their fragment offset.
542 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
543 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
544 std::sort(GVEs.begin(), GVEs.end(),
545 [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
546 // Sort order: first null exprs, then exprs without fragment
547 // info, then sort by fragment offset in bits.
548 // FIXME: Come up with a more comprehensive comparator so
549 // the sorting isn't non-deterministic, and so the following
550 // std::unique call works correctly.
551 if (!A.Expr || !B.Expr)
553 auto FragmentA = A.Expr->getFragmentInfo();
554 auto FragmentB = B.Expr->getFragmentInfo();
555 if (!FragmentA || !FragmentB)
557 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
559 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
560 [](DwarfCompileUnit::GlobalExpr A,
561 DwarfCompileUnit::GlobalExpr B) {
562 return A.Expr == B.Expr;
568 // Emit all Dwarf sections that should come prior to the content. Create
569 // global DIEs and emit initial debug info sections. This is invoked by
570 // the target AsmPrinter.
571 void DwarfDebug::beginModule() {
572 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
573 DWARFGroupDescription, TimePassesIsEnabled);
574 if (DisableDebugInfoPrinting)
577 const Module *M = MMI->getModule();
579 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
580 M->debug_compile_units_end());
581 // Tell MMI whether we have debug info.
582 MMI->setDebugInfoAvailability(NumDebugCUs > 0);
583 SingleCU = NumDebugCUs == 1;
584 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
586 for (const GlobalVariable &Global : M->globals()) {
587 SmallVector<DIGlobalVariableExpression *, 1> GVs;
588 Global.getDebugInfo(GVs);
589 for (auto *GVE : GVs)
590 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
593 // Create the symbol that designates the start of the unit's contribution
594 // to the string offsets table. In a split DWARF scenario, only the skeleton
595 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
596 if (useSegmentedStringOffsetsTable())
597 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
598 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
600 for (DICompileUnit *CUNode : M->debug_compile_units()) {
601 // FIXME: Move local imported entities into a list attached to the
602 // subprogram, then this search won't be needed and a
603 // getImportedEntities().empty() test should go below with the rest.
604 bool HasNonLocalImportedEntities = llvm::any_of(
605 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
606 return !isa<DILocalScope>(IE->getScope());
609 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
610 CUNode->getRetainedTypes().empty() &&
611 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
614 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
617 for (auto *GVE : CUNode->getGlobalVariables()) {
618 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
619 // already know about the variable and it isn't adding a constant
621 auto &GVMapEntry = GVMap[GVE->getVariable()];
622 auto *Expr = GVE->getExpression();
623 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
624 GVMapEntry.push_back({nullptr, Expr});
626 DenseSet<DIGlobalVariable *> Processed;
627 for (auto *GVE : CUNode->getGlobalVariables()) {
628 DIGlobalVariable *GV = GVE->getVariable();
629 if (Processed.insert(GV).second)
630 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
633 for (auto *Ty : CUNode->getEnumTypes()) {
634 // The enum types array by design contains pointers to
635 // MDNodes rather than DIRefs. Unique them here.
636 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
638 for (auto *Ty : CUNode->getRetainedTypes()) {
639 // The retained types array by design contains pointers to
640 // MDNodes rather than DIRefs. Unique them here.
641 if (DIType *RT = dyn_cast<DIType>(Ty))
642 // There is no point in force-emitting a forward declaration.
643 CU.getOrCreateTypeDIE(RT);
645 // Emit imported_modules last so that the relevant context is already
647 for (auto *IE : CUNode->getImportedEntities())
648 constructAndAddImportedEntityDIE(CU, IE);
652 void DwarfDebug::finishVariableDefinitions() {
653 for (const auto &Var : ConcreteVariables) {
654 DIE *VariableDie = Var->getDIE();
656 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
657 // in the ConcreteVariables list, rather than looking it up again here.
658 // DIE::getUnit isn't simple - it walks parent pointers, etc.
659 DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie());
661 Unit->finishVariableDefinition(*Var);
665 void DwarfDebug::finishSubprogramDefinitions() {
666 for (const DISubprogram *SP : ProcessedSPNodes) {
667 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
669 getOrCreateDwarfCompileUnit(SP->getUnit()),
670 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
674 void DwarfDebug::finalizeModuleInfo() {
675 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
677 finishSubprogramDefinitions();
679 finishVariableDefinitions();
681 // Include the DWO file name in the hash if there's more than one CU.
682 // This handles ThinLTO's situation where imported CUs may very easily be
683 // duplicate with the same CU partially imported into another ThinLTO unit.
685 if (CUMap.size() > 1)
686 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
688 // Handle anything that needs to be done on a per-unit basis after
689 // all other generation.
690 for (const auto &P : CUMap) {
691 auto &TheCU = *P.second;
692 // Emit DW_AT_containing_type attribute to connect types with their
693 // vtable holding type.
694 TheCU.constructContainingTypeDIEs();
696 // Add CU specific attributes if we need to add any.
697 // If we're splitting the dwarf out now that we've got the entire
698 // CU then add the dwo id to it.
699 auto *SkCU = TheCU.getSkeleton();
700 if (useSplitDwarf()) {
701 // Emit a unique identifier for this CU.
703 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
704 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
705 dwarf::DW_FORM_data8, ID);
706 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
707 dwarf::DW_FORM_data8, ID);
709 // We don't keep track of which addresses are used in which CU so this
710 // is a bit pessimistic under LTO.
711 if (!AddrPool.isEmpty()) {
712 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
713 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
716 if (!SkCU->getRangeLists().empty()) {
717 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
718 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
723 // If we have code split among multiple sections or non-contiguous
724 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
725 // remain in the .o file, otherwise add a DW_AT_low_pc.
726 // FIXME: We should use ranges allow reordering of code ala
727 // .subsections_via_symbols in mach-o. This would mean turning on
728 // ranges for all subprogram DIEs for mach-o.
729 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
730 if (unsigned NumRanges = TheCU.getRanges().size()) {
732 // A DW_AT_low_pc attribute may also be specified in combination with
733 // DW_AT_ranges to specify the default base address for use in
734 // location lists (see Section 2.6.2) and range lists (see Section
736 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
738 U.setBaseAddress(TheCU.getRanges().front().getStart());
739 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
742 auto *CUNode = cast<DICompileUnit>(P.first);
743 // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
744 if (CUNode->getMacros())
745 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
746 U.getMacroLabelBegin(),
747 TLOF.getDwarfMacinfoSection()->getBeginSymbol());
750 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
751 for (auto *CUNode : MMI->getModule()->debug_compile_units())
752 if (CUNode->getDWOId())
753 getOrCreateDwarfCompileUnit(CUNode);
755 // Compute DIE offsets and sizes.
756 InfoHolder.computeSizeAndOffsets();
758 SkeletonHolder.computeSizeAndOffsets();
761 // Emit all Dwarf sections that should come after the content.
762 void DwarfDebug::endModule() {
763 assert(CurFn == nullptr);
764 assert(CurMI == nullptr);
766 // If we aren't actually generating debug info (check beginModule -
767 // conditionalized on !DisableDebugInfoPrinting and the presence of the
768 // llvm.dbg.cu metadata node)
769 if (!MMI->hasDebugInfo())
772 // Finalize the debug info for the module.
773 finalizeModuleInfo();
780 // Emit info into a debug loc section.
783 // Corresponding abbreviations into a abbrev section.
786 // Emit all the DIEs into a debug info section.
789 // Emit info into a debug aranges section.
790 if (GenerateARangeSection)
793 // Emit info into a debug ranges section.
796 // Emit info into a debug macinfo section.
799 if (useSplitDwarf()) {
802 emitDebugAbbrevDWO();
804 // Emit DWO addresses.
805 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
808 // Emit info into the dwarf accelerator table sections.
809 if (useDwarfAccelTables()) {
812 emitAccelNamespaces();
816 // Emit the pubnames and pubtypes sections if requested.
817 emitDebugPubSections();
820 // FIXME: AbstractVariables.clear();
823 void DwarfDebug::ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV,
824 const MDNode *ScopeNode) {
825 const DILocalVariable *Cleansed = nullptr;
826 if (CU.getExistingAbstractVariable(IV, Cleansed))
829 CU.createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
830 cast<DILocalScope>(ScopeNode)));
833 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU,
834 InlinedVariable IV, const MDNode *ScopeNode) {
835 const DILocalVariable *Cleansed = nullptr;
836 if (CU.getExistingAbstractVariable(IV, Cleansed))
839 if (LexicalScope *Scope =
840 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
841 CU.createAbstractVariable(Cleansed, Scope);
844 // Collect variable information from side table maintained by MF.
845 void DwarfDebug::collectVariableInfoFromMFTable(
846 DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) {
847 SmallDenseMap<InlinedVariable, DbgVariable *> MFVars;
848 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
851 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
852 "Expected inlined-at fields to agree");
854 InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
855 Processed.insert(Var);
856 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
858 // If variable scope is not found then skip this variable.
862 ensureAbstractVariableIsCreatedIfScoped(TheCU, Var, Scope->getScopeNode());
863 auto RegVar = llvm::make_unique<DbgVariable>(Var.first, Var.second);
864 RegVar->initializeMMI(VI.Expr, VI.Slot);
865 if (DbgVariable *DbgVar = MFVars.lookup(Var))
866 DbgVar->addMMIEntry(*RegVar);
867 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
868 MFVars.insert({Var, RegVar.get()});
869 ConcreteVariables.push_back(std::move(RegVar));
874 // Get .debug_loc entry for the instruction range starting at MI.
875 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
876 const DIExpression *Expr = MI->getDebugExpression();
877 assert(MI->getNumOperands() == 4);
878 if (MI->getOperand(0).isReg()) {
879 auto RegOp = MI->getOperand(0);
880 auto Op1 = MI->getOperand(1);
881 // If the second operand is an immediate, this is a
882 // register-indirect address.
883 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
884 MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
885 return DebugLocEntry::Value(Expr, MLoc);
887 if (MI->getOperand(0).isImm())
888 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
889 if (MI->getOperand(0).isFPImm())
890 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
891 if (MI->getOperand(0).isCImm())
892 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
894 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
897 /// \brief If this and Next are describing different fragments of the same
898 /// variable, merge them by appending Next's values to the current
900 /// Return true if the merge was successful.
901 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
902 if (Begin == Next.Begin) {
903 auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
904 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
905 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
908 // We can only merge entries if none of the fragments overlap any others.
909 // In doing so, we can take advantage of the fact that both lists are
911 for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
912 for (; j < Next.Values.size(); ++j) {
913 int res = DebugHandlerBase::fragmentCmp(
914 cast<DIExpression>(Values[i].Expression),
915 cast<DIExpression>(Next.Values[j].Expression));
916 if (res == 0) // The two expressions overlap, we can't merge.
918 // Values[i] is entirely before Next.Values[j],
919 // so go back to the next entry of Values.
922 // Next.Values[j] is entirely before Values[i], so go on to the
923 // next entry of Next.Values.
927 addValues(Next.Values);
934 /// Build the location list for all DBG_VALUEs in the function that
935 /// describe the same variable. If the ranges of several independent
936 /// fragments of the same variable overlap partially, split them up and
937 /// combine the ranges. The resulting DebugLocEntries are will have
938 /// strict monotonically increasing begin addresses and will never
943 // Ranges History [var, loc, fragment ofs size]
944 // 0 | [x, (reg0, fragment 0, 32)]
945 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
947 // 3 | [clobber reg0]
948 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
953 // [0-1] [x, (reg0, fragment 0, 32)]
954 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)]
955 // [3-4] [x, (reg1, fragment 32, 32)]
956 // [4- ] [x, (mem, fragment 0, 64)]
958 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
959 const DbgValueHistoryMap::InstrRanges &Ranges) {
960 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
962 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
963 const MachineInstr *Begin = I->first;
964 const MachineInstr *End = I->second;
965 assert(Begin->isDebugValue() && "Invalid History entry");
967 // Check if a variable is inaccessible in this range.
968 if (Begin->getNumOperands() > 1 &&
969 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
974 // If this fragment overlaps with any open ranges, truncate them.
975 const DIExpression *DIExpr = Begin->getDebugExpression();
976 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
977 return fragmentsOverlap(DIExpr, R.getExpression());
979 OpenRanges.erase(Last, OpenRanges.end());
981 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
982 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
984 const MCSymbol *EndLabel;
986 EndLabel = getLabelAfterInsn(End);
987 else if (std::next(I) == Ranges.end())
988 EndLabel = Asm->getFunctionEnd();
990 EndLabel = getLabelBeforeInsn(std::next(I)->first);
991 assert(EndLabel && "Forgot label after instruction ending a range!");
993 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
995 auto Value = getDebugLocValue(Begin);
996 DebugLocEntry Loc(StartLabel, EndLabel, Value);
997 bool couldMerge = false;
999 // If this is a fragment, it may belong to the current DebugLocEntry.
1000 if (DIExpr->isFragment()) {
1001 // Add this value to the list of open ranges.
1002 OpenRanges.push_back(Value);
1004 // Attempt to add the fragment to the last entry.
1005 if (!DebugLoc.empty())
1006 if (DebugLoc.back().MergeValues(Loc))
1011 // Need to add a new DebugLocEntry. Add all values from still
1012 // valid non-overlapping fragments.
1013 if (OpenRanges.size())
1014 Loc.addValues(OpenRanges);
1016 DebugLoc.push_back(std::move(Loc));
1019 // Attempt to coalesce the ranges of two otherwise identical
1021 auto CurEntry = DebugLoc.rbegin();
1023 dbgs() << CurEntry->getValues().size() << " Values:\n";
1024 for (auto &Value : CurEntry->getValues())
1026 dbgs() << "-----\n";
1029 auto PrevEntry = std::next(CurEntry);
1030 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1031 DebugLoc.pop_back();
1035 DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU,
1036 LexicalScope &Scope,
1037 InlinedVariable IV) {
1038 ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode());
1039 ConcreteVariables.push_back(
1040 llvm::make_unique<DbgVariable>(IV.first, IV.second));
1041 InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
1042 return ConcreteVariables.back().get();
1045 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1046 /// enclosing lexical scope. The check ensures there are no other instructions
1047 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1048 /// either open or otherwise rolls off the end of the scope.
1049 static bool validThroughout(LexicalScopes &LScopes,
1050 const MachineInstr *DbgValue,
1051 const MachineInstr *RangeEnd) {
1052 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1053 auto MBB = DbgValue->getParent();
1054 auto DL = DbgValue->getDebugLoc();
1055 auto *LScope = LScopes.findLexicalScope(DL);
1056 // Scope doesn't exist; this is a dead DBG_VALUE.
1059 auto &LSRange = LScope->getRanges();
1060 if (LSRange.size() == 0)
1063 // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1064 const MachineInstr *LScopeBegin = LSRange.front().first;
1065 // Early exit if the lexical scope begins outside of the current block.
1066 if (LScopeBegin->getParent() != MBB)
1068 MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1069 for (++Pred; Pred != MBB->rend(); ++Pred) {
1070 if (Pred->getFlag(MachineInstr::FrameSetup))
1072 auto PredDL = Pred->getDebugLoc();
1073 if (!PredDL || Pred->isMetaInstruction())
1075 // Check whether the instruction preceding the DBG_VALUE is in the same
1076 // (sub)scope as the DBG_VALUE.
1077 if (DL->getScope() == PredDL->getScope())
1079 auto *PredScope = LScopes.findLexicalScope(PredDL);
1080 if (!PredScope || LScope->dominates(PredScope))
1084 // If the range of the DBG_VALUE is open-ended, report success.
1088 // Fail if there are instructions belonging to our scope in another block.
1089 const MachineInstr *LScopeEnd = LSRange.back().second;
1090 if (LScopeEnd->getParent() != MBB)
1093 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1094 // throughout the function. This is a hack, presumably for DWARF v2 and not
1095 // necessarily correct. It would be much better to use a dbg.declare instead
1096 // if we know the constant is live throughout the scope.
1097 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1103 // Find variables for each lexical scope.
1104 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
1105 const DISubprogram *SP,
1106 DenseSet<InlinedVariable> &Processed) {
1107 // Grab the variable info that was squirreled away in the MMI side-table.
1108 collectVariableInfoFromMFTable(TheCU, Processed);
1110 for (const auto &I : DbgValues) {
1111 InlinedVariable IV = I.first;
1112 if (Processed.count(IV))
1115 // Instruction ranges, specifying where IV is accessible.
1116 const auto &Ranges = I.second;
1120 LexicalScope *Scope = nullptr;
1121 if (const DILocation *IA = IV.second)
1122 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
1124 Scope = LScopes.findLexicalScope(IV.first->getScope());
1125 // If variable scope is not found then skip this variable.
1129 Processed.insert(IV);
1130 DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV);
1132 const MachineInstr *MInsn = Ranges.front().first;
1133 assert(MInsn->isDebugValue() && "History must begin with debug value");
1135 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1136 if (Ranges.size() == 1 &&
1137 validThroughout(LScopes, MInsn, Ranges.front().second)) {
1138 RegVar->initializeDbgValue(MInsn);
1142 // Handle multiple DBG_VALUE instructions describing one variable.
1143 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1145 // Build the location list for this variable.
1146 SmallVector<DebugLocEntry, 8> Entries;
1147 buildLocationList(Entries, Ranges);
1149 // If the variable has a DIBasicType, extract it. Basic types cannot have
1150 // unique identifiers, so don't bother resolving the type with the
1152 const DIBasicType *BT = dyn_cast<DIBasicType>(
1153 static_cast<const Metadata *>(IV.first->getType()));
1155 // Finalize the entry by lowering it into a DWARF bytestream.
1156 for (auto &Entry : Entries)
1157 Entry.finalize(*Asm, List, BT);
1160 // Collect info for variables that were optimized out.
1161 for (const DILocalVariable *DV : SP->getVariables()) {
1162 if (Processed.insert(InlinedVariable(DV, nullptr)).second)
1163 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
1164 createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr));
1168 // Process beginning of an instruction.
1169 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1170 DebugHandlerBase::beginInstruction(MI);
1173 const auto *SP = MI->getMF()->getFunction().getSubprogram();
1174 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1177 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1178 // If the instruction is part of the function frame setup code, do not emit
1179 // any line record, as there is no correspondence with any user code.
1180 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1182 const DebugLoc &DL = MI->getDebugLoc();
1183 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1184 // the last line number actually emitted, to see if it was line 0.
1185 unsigned LastAsmLine =
1186 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1188 if (DL == PrevInstLoc) {
1189 // If we have an ongoing unspecified location, nothing to do here.
1192 // We have an explicit location, same as the previous location.
1193 // But we might be coming back to it after a line 0 record.
1194 if (LastAsmLine == 0 && DL.getLine() != 0) {
1195 // Reinstate the source location but not marked as a statement.
1196 const MDNode *Scope = DL.getScope();
1197 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1203 // We have an unspecified location, which might want to be line 0.
1204 // If we have already emitted a line-0 record, don't repeat it.
1205 if (LastAsmLine == 0)
1207 // If user said Don't Do That, don't do that.
1208 if (UnknownLocations == Disable)
1210 // See if we have a reason to emit a line-0 record now.
1211 // Reasons to emit a line-0 record include:
1212 // - User asked for it (UnknownLocations).
1213 // - Instruction has a label, so it's referenced from somewhere else,
1214 // possibly debug information; we want it to have a source location.
1215 // - Instruction is at the top of a block; we don't want to inherit the
1216 // location from the physically previous (maybe unrelated) block.
1217 if (UnknownLocations == Enable || PrevLabel ||
1218 (PrevInstBB && PrevInstBB != MI->getParent())) {
1219 // Preserve the file and column numbers, if we can, to save space in
1220 // the encoded line table.
1221 // Do not update PrevInstLoc, it remembers the last non-0 line.
1222 const MDNode *Scope = nullptr;
1223 unsigned Column = 0;
1225 Scope = PrevInstLoc.getScope();
1226 Column = PrevInstLoc.getCol();
1228 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1233 // We have an explicit location, different from the previous location.
1234 // Don't repeat a line-0 record, but otherwise emit the new location.
1235 // (The new location might be an explicit line 0, which we do emit.)
1236 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
1239 if (DL == PrologEndLoc) {
1240 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1241 PrologEndLoc = DebugLoc();
1243 // If the line changed, we call that a new statement; unless we went to
1244 // line 0 and came back, in which case it is not a new statement.
1245 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1246 if (DL.getLine() && DL.getLine() != OldLine)
1247 Flags |= DWARF2_FLAG_IS_STMT;
1249 const MDNode *Scope = DL.getScope();
1250 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1252 // If we're not at line 0, remember this location.
1257 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1258 // First known non-DBG_VALUE and non-frame setup location marks
1259 // the beginning of the function body.
1260 for (const auto &MBB : *MF)
1261 for (const auto &MI : MBB)
1262 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1264 return MI.getDebugLoc();
1268 // Gather pre-function debug information. Assumes being called immediately
1269 // after the function entry point has been emitted.
1270 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1273 auto *SP = MF->getFunction().getSubprogram();
1274 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1275 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1278 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1280 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1281 // belongs to so that we add to the correct per-cu line table in the
1283 if (Asm->OutStreamer->hasRawTextSupport())
1284 // Use a single line table if we are generating assembly.
1285 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1287 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1289 // Record beginning of function.
1290 PrologEndLoc = findPrologueEndLoc(MF);
1292 // We'd like to list the prologue as "not statements" but GDB behaves
1293 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1294 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1295 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1299 void DwarfDebug::skippedNonDebugFunction() {
1300 // If we don't have a subprogram for this function then there will be a hole
1301 // in the range information. Keep note of this by setting the previously used
1302 // section to nullptr.
1307 // Gather and emit post-function debug information.
1308 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1309 const DISubprogram *SP = MF->getFunction().getSubprogram();
1311 assert(CurFn == MF &&
1312 "endFunction should be called with the same function as beginFunction");
1314 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1315 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1317 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1318 assert(!FnScope || SP == FnScope->getScopeNode());
1319 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1321 DenseSet<InlinedVariable> ProcessedVars;
1322 collectVariableInfo(TheCU, SP, ProcessedVars);
1324 // Add the range of this function to the list of ranges for the CU.
1325 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1327 // Under -gmlt, skip building the subprogram if there are no inlined
1328 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1329 // is still needed as we need its source location.
1330 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1331 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1332 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1333 assert(InfoHolder.getScopeVariables().empty());
1334 PrevLabel = nullptr;
1340 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1342 // Construct abstract scopes.
1343 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1344 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1345 // Collect info for variables that were optimized out.
1346 for (const DILocalVariable *DV : SP->getVariables()) {
1347 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1349 ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr),
1351 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1352 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1354 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1357 ProcessedSPNodes.insert(SP);
1358 TheCU.constructSubprogramScopeDIE(SP, FnScope);
1359 if (auto *SkelCU = TheCU.getSkeleton())
1360 if (!LScopes.getAbstractScopesList().empty() &&
1361 TheCU.getCUNode()->getSplitDebugInlining())
1362 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1365 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1366 // DbgVariables except those that are also in AbstractVariables (since they
1367 // can be used cross-function)
1368 InfoHolder.getScopeVariables().clear();
1369 PrevLabel = nullptr;
1373 // Register a source line with debug info. Returns the unique label that was
1374 // emitted and which provides correspondence to the source line list.
1375 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1379 unsigned Discriminator = 0;
1380 if (auto *Scope = cast_or_null<DIScope>(S)) {
1381 Fn = Scope->getFilename();
1382 if (Line != 0 && getDwarfVersion() >= 4)
1383 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1384 Discriminator = LBF->getDiscriminator();
1386 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1387 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1388 .getOrCreateSourceID(Scope->getFile());
1390 Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1394 //===----------------------------------------------------------------------===//
1396 //===----------------------------------------------------------------------===//
1398 // Emit the debug info section.
1399 void DwarfDebug::emitDebugInfo() {
1400 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1401 Holder.emitUnits(/* UseOffsets */ false);
1404 // Emit the abbreviation section.
1405 void DwarfDebug::emitAbbreviations() {
1406 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1408 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1411 void DwarfDebug::emitStringOffsetsTableHeader() {
1412 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1413 Holder.emitStringOffsetsTableHeader(
1414 Asm->getObjFileLowering().getDwarfStrOffSection());
1417 template <typename AccelTableT>
1418 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1419 StringRef TableName) {
1420 Asm->OutStreamer->SwitchSection(Section);
1422 // Emit the full data.
1423 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1426 // Emit visible names into a hashed accelerator table section.
1427 void DwarfDebug::emitAccelNames() {
1428 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1432 // Emit objective C classes and categories into a hashed accelerator table
1434 void DwarfDebug::emitAccelObjC() {
1435 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1439 // Emit namespace dies into a hashed accelerator table.
1440 void DwarfDebug::emitAccelNamespaces() {
1441 emitAccel(AccelNamespace,
1442 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1446 // Emit type dies into a hashed accelerator table.
1447 void DwarfDebug::emitAccelTypes() {
1448 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1452 // Public name handling.
1453 // The format for the various pubnames:
1455 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1456 // for the DIE that is named.
1458 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1459 // into the CU and the index value is computed according to the type of value
1460 // for the DIE that is named.
1462 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1463 // it's the offset within the debug_info/debug_types dwo section, however, the
1464 // reference in the pubname header doesn't change.
1466 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1467 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1469 // Entities that ended up only in a Type Unit reference the CU instead (since
1470 // the pub entry has offsets within the CU there's no real offset that can be
1471 // provided anyway). As it happens all such entities (namespaces and types,
1472 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1473 // not to be true it would be necessary to persist this information from the
1474 // point at which the entry is added to the index data structure - since by
1475 // the time the index is built from that, the original type/namespace DIE in a
1476 // type unit has already been destroyed so it can't be queried for properties
1478 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1479 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1480 dwarf::GIEL_EXTERNAL);
1481 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1483 // We could have a specification DIE that has our most of our knowledge,
1484 // look for that now.
1485 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1486 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1487 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1488 Linkage = dwarf::GIEL_EXTERNAL;
1489 } else if (Die->findAttribute(dwarf::DW_AT_external))
1490 Linkage = dwarf::GIEL_EXTERNAL;
1492 switch (Die->getTag()) {
1493 case dwarf::DW_TAG_class_type:
1494 case dwarf::DW_TAG_structure_type:
1495 case dwarf::DW_TAG_union_type:
1496 case dwarf::DW_TAG_enumeration_type:
1497 return dwarf::PubIndexEntryDescriptor(
1498 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1499 ? dwarf::GIEL_STATIC
1500 : dwarf::GIEL_EXTERNAL);
1501 case dwarf::DW_TAG_typedef:
1502 case dwarf::DW_TAG_base_type:
1503 case dwarf::DW_TAG_subrange_type:
1504 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1505 case dwarf::DW_TAG_namespace:
1506 return dwarf::GIEK_TYPE;
1507 case dwarf::DW_TAG_subprogram:
1508 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1509 case dwarf::DW_TAG_variable:
1510 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1511 case dwarf::DW_TAG_enumerator:
1512 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1513 dwarf::GIEL_STATIC);
1515 return dwarf::GIEK_NONE;
1519 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
1520 /// pubtypes sections.
1521 void DwarfDebug::emitDebugPubSections() {
1522 for (const auto &NU : CUMap) {
1523 DwarfCompileUnit *TheU = NU.second;
1524 if (!TheU->hasDwarfPubSections())
1527 bool GnuStyle = TheU->getCUNode()->getGnuPubnames();
1529 Asm->OutStreamer->SwitchSection(
1530 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1531 : Asm->getObjFileLowering().getDwarfPubNamesSection());
1532 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
1534 Asm->OutStreamer->SwitchSection(
1535 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1536 : Asm->getObjFileLowering().getDwarfPubTypesSection());
1537 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
1541 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1542 DwarfCompileUnit *TheU,
1543 const StringMap<const DIE *> &Globals) {
1544 if (auto *Skeleton = TheU->getSkeleton())
1548 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1549 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1550 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1551 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1553 Asm->OutStreamer->EmitLabel(BeginLabel);
1555 Asm->OutStreamer->AddComment("DWARF Version");
1556 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1558 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1559 Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
1561 Asm->OutStreamer->AddComment("Compilation Unit Length");
1562 Asm->EmitInt32(TheU->getLength());
1564 // Emit the pubnames for this compilation unit.
1565 for (const auto &GI : Globals) {
1566 const char *Name = GI.getKeyData();
1567 const DIE *Entity = GI.second;
1569 Asm->OutStreamer->AddComment("DIE offset");
1570 Asm->EmitInt32(Entity->getOffset());
1573 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1574 Asm->OutStreamer->AddComment(
1575 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1576 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1577 Asm->EmitInt8(Desc.toBits());
1580 Asm->OutStreamer->AddComment("External Name");
1581 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1584 Asm->OutStreamer->AddComment("End Mark");
1586 Asm->OutStreamer->EmitLabel(EndLabel);
1589 /// Emit null-terminated strings into a debug str section.
1590 void DwarfDebug::emitDebugStr() {
1591 MCSection *StringOffsetsSection = nullptr;
1592 if (useSegmentedStringOffsetsTable()) {
1593 emitStringOffsetsTableHeader();
1594 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1596 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1597 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
1598 StringOffsetsSection, /* UseRelativeOffsets = */ true);
1601 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1602 const DebugLocStream::Entry &Entry) {
1603 auto &&Comments = DebugLocs.getComments(Entry);
1604 auto Comment = Comments.begin();
1605 auto End = Comments.end();
1606 for (uint8_t Byte : DebugLocs.getBytes(Entry))
1607 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1610 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1611 ByteStreamer &Streamer,
1612 const DebugLocEntry::Value &Value,
1613 DwarfExpression &DwarfExpr) {
1614 auto *DIExpr = Value.getExpression();
1615 DIExpressionCursor ExprCursor(DIExpr);
1616 DwarfExpr.addFragmentOffset(DIExpr);
1618 if (Value.isInt()) {
1619 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1620 BT->getEncoding() == dwarf::DW_ATE_signed_char))
1621 DwarfExpr.addSignedConstant(Value.getInt());
1623 DwarfExpr.addUnsignedConstant(Value.getInt());
1624 } else if (Value.isLocation()) {
1625 MachineLocation Location = Value.getLoc();
1626 if (Location.isIndirect())
1627 DwarfExpr.setMemoryLocationKind();
1628 DIExpressionCursor Cursor(DIExpr);
1629 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1630 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1632 return DwarfExpr.addExpression(std::move(Cursor));
1633 } else if (Value.isConstantFP()) {
1634 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1635 DwarfExpr.addUnsignedConstant(RawBytes);
1637 DwarfExpr.addExpression(std::move(ExprCursor));
1640 void DebugLocEntry::finalize(const AsmPrinter &AP,
1641 DebugLocStream::ListBuilder &List,
1642 const DIBasicType *BT) {
1643 DebugLocStream::EntryBuilder Entry(List, Begin, End);
1644 BufferByteStreamer Streamer = Entry.getStreamer();
1645 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
1646 const DebugLocEntry::Value &Value = Values[0];
1647 if (Value.isFragment()) {
1648 // Emit all fragments that belong to the same variable and range.
1649 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
1650 return P.isFragment();
1651 }) && "all values are expected to be fragments");
1652 assert(std::is_sorted(Values.begin(), Values.end()) &&
1653 "fragments are expected to be sorted");
1655 for (auto Fragment : Values)
1656 emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr);
1659 assert(Values.size() == 1 && "only fragments may have >1 value");
1660 emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr);
1662 DwarfExpr.finalize();
1665 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1667 Asm->OutStreamer->AddComment("Loc expr size");
1668 Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1671 APByteStreamer Streamer(*Asm);
1672 emitDebugLocEntry(Streamer, Entry);
1675 // Emit locations into the debug loc section.
1676 void DwarfDebug::emitDebugLoc() {
1677 if (DebugLocs.getLists().empty())
1680 // Start the dwarf loc section.
1681 Asm->OutStreamer->SwitchSection(
1682 Asm->getObjFileLowering().getDwarfLocSection());
1683 unsigned char Size = Asm->MAI->getCodePointerSize();
1684 for (const auto &List : DebugLocs.getLists()) {
1685 Asm->OutStreamer->EmitLabel(List.Label);
1686 const DwarfCompileUnit *CU = List.CU;
1687 for (const auto &Entry : DebugLocs.getEntries(List)) {
1688 // Set up the range. This range is relative to the entry point of the
1689 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1690 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1691 if (auto *Base = CU->getBaseAddress()) {
1692 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1693 Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1695 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1696 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1699 emitDebugLocEntryLocation(Entry);
1701 Asm->OutStreamer->EmitIntValue(0, Size);
1702 Asm->OutStreamer->EmitIntValue(0, Size);
1706 void DwarfDebug::emitDebugLocDWO() {
1707 Asm->OutStreamer->SwitchSection(
1708 Asm->getObjFileLowering().getDwarfLocDWOSection());
1709 for (const auto &List : DebugLocs.getLists()) {
1710 Asm->OutStreamer->EmitLabel(List.Label);
1711 for (const auto &Entry : DebugLocs.getEntries(List)) {
1712 // Just always use start_length for now - at least that's one address
1713 // rather than two. We could get fancier and try to, say, reuse an
1714 // address we know we've emitted elsewhere (the start of the function?
1715 // The start of the CU or CU subrange that encloses this range?)
1716 Asm->EmitInt8(dwarf::DW_LLE_startx_length);
1717 unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1718 Asm->EmitULEB128(idx);
1719 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1721 emitDebugLocEntryLocation(Entry);
1723 Asm->EmitInt8(dwarf::DW_LLE_end_of_list);
1728 const MCSymbol *Start, *End;
1731 // Emit a debug aranges section, containing a CU lookup for any
1732 // address we can tie back to a CU.
1733 void DwarfDebug::emitDebugARanges() {
1734 // Provides a unique id per text section.
1735 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1737 // Filter labels by section.
1738 for (const SymbolCU &SCU : ArangeLabels) {
1739 if (SCU.Sym->isInSection()) {
1740 // Make a note of this symbol and it's section.
1741 MCSection *Section = &SCU.Sym->getSection();
1742 if (!Section->getKind().isMetadata())
1743 SectionMap[Section].push_back(SCU);
1745 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1746 // appear in the output. This sucks as we rely on sections to build
1747 // arange spans. We can do it without, but it's icky.
1748 SectionMap[nullptr].push_back(SCU);
1752 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1754 for (auto &I : SectionMap) {
1755 MCSection *Section = I.first;
1756 SmallVector<SymbolCU, 8> &List = I.second;
1757 if (List.size() < 1)
1760 // If we have no section (e.g. common), just write out
1761 // individual spans for each symbol.
1763 for (const SymbolCU &Cur : List) {
1765 Span.Start = Cur.Sym;
1768 Spans[Cur.CU].push_back(Span);
1773 // Sort the symbols by offset within the section.
1775 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
1776 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1777 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1779 // Symbols with no order assigned should be placed at the end.
1780 // (e.g. section end labels)
1788 // Insert a final terminator.
1789 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
1791 // Build spans between each label.
1792 const MCSymbol *StartSym = List[0].Sym;
1793 for (size_t n = 1, e = List.size(); n < e; n++) {
1794 const SymbolCU &Prev = List[n - 1];
1795 const SymbolCU &Cur = List[n];
1797 // Try and build the longest span we can within the same CU.
1798 if (Cur.CU != Prev.CU) {
1800 Span.Start = StartSym;
1803 Spans[Prev.CU].push_back(Span);
1809 // Start the dwarf aranges section.
1810 Asm->OutStreamer->SwitchSection(
1811 Asm->getObjFileLowering().getDwarfARangesSection());
1813 unsigned PtrSize = Asm->MAI->getCodePointerSize();
1815 // Build a list of CUs used.
1816 std::vector<DwarfCompileUnit *> CUs;
1817 for (const auto &it : Spans) {
1818 DwarfCompileUnit *CU = it.first;
1822 // Sort the CU list (again, to ensure consistent output order).
1823 std::sort(CUs.begin(), CUs.end(),
1824 [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
1825 return A->getUniqueID() < B->getUniqueID();
1828 // Emit an arange table for each CU we used.
1829 for (DwarfCompileUnit *CU : CUs) {
1830 std::vector<ArangeSpan> &List = Spans[CU];
1832 // Describe the skeleton CU's offset and length, not the dwo file's.
1833 if (auto *Skel = CU->getSkeleton())
1836 // Emit size of content not including length itself.
1837 unsigned ContentSize =
1838 sizeof(int16_t) + // DWARF ARange version number
1839 sizeof(int32_t) + // Offset of CU in the .debug_info section
1840 sizeof(int8_t) + // Pointer Size (in bytes)
1841 sizeof(int8_t); // Segment Size (in bytes)
1843 unsigned TupleSize = PtrSize * 2;
1845 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1847 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1849 ContentSize += Padding;
1850 ContentSize += (List.size() + 1) * TupleSize;
1852 // For each compile unit, write the list of spans it covers.
1853 Asm->OutStreamer->AddComment("Length of ARange Set");
1854 Asm->EmitInt32(ContentSize);
1855 Asm->OutStreamer->AddComment("DWARF Arange version number");
1856 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1857 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1858 Asm->emitDwarfSymbolReference(CU->getLabelBegin());
1859 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1860 Asm->EmitInt8(PtrSize);
1861 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1864 Asm->OutStreamer->emitFill(Padding, 0xff);
1866 for (const ArangeSpan &Span : List) {
1867 Asm->EmitLabelReference(Span.Start, PtrSize);
1869 // Calculate the size as being from the span start to it's end.
1871 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1873 // For symbols without an end marker (e.g. common), we
1874 // write a single arange entry containing just that one symbol.
1875 uint64_t Size = SymSize[Span.Start];
1879 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1883 Asm->OutStreamer->AddComment("ARange terminator");
1884 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1885 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1889 /// Emit address ranges into a debug ranges section.
1890 void DwarfDebug::emitDebugRanges() {
1894 // Start the dwarf ranges section.
1895 Asm->OutStreamer->SwitchSection(
1896 Asm->getObjFileLowering().getDwarfRangesSection());
1898 // Size for our labels.
1899 unsigned char Size = Asm->MAI->getCodePointerSize();
1901 // Grab the specific ranges for the compile units in the module.
1902 for (const auto &I : CUMap) {
1903 DwarfCompileUnit *TheCU = I.second;
1905 if (auto *Skel = TheCU->getSkeleton())
1908 // Iterate over the misc ranges for the compile units in the module.
1909 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1910 // Emit our symbol so we can find the beginning of the range.
1911 Asm->OutStreamer->EmitLabel(List.getSym());
1913 // Gather all the ranges that apply to the same section so they can share
1914 // a base address entry.
1915 MapVector<const MCSection *, std::vector<const RangeSpan *>> MV;
1916 for (const RangeSpan &Range : List.getRanges()) {
1917 MV[&Range.getStart()->getSection()].push_back(&Range);
1920 auto *CUBase = TheCU->getBaseAddress();
1921 bool BaseIsSet = false;
1922 for (const auto &P : MV) {
1923 // Don't bother with a base address entry if there's only one range in
1924 // this section in this range list - for example ranges for a CU will
1925 // usually consist of single regions from each of many sections
1926 // (-ffunction-sections, or just C++ inline functions) except under LTO
1927 // or optnone where there may be holes in a single CU's section
1929 auto *Base = CUBase;
1930 if (!Base && P.second.size() > 1 &&
1931 UseDwarfRangesBaseAddressSpecifier) {
1933 // FIXME/use care: This may not be a useful base address if it's not
1934 // the lowest address/range in this object.
1935 Base = P.second.front()->getStart();
1936 Asm->OutStreamer->EmitIntValue(-1, Size);
1937 Asm->OutStreamer->EmitSymbolValue(Base, Size);
1938 } else if (BaseIsSet) {
1940 Asm->OutStreamer->EmitIntValue(-1, Size);
1941 Asm->OutStreamer->EmitIntValue(0, Size);
1944 for (const auto *RS : P.second) {
1945 const MCSymbol *Begin = RS->getStart();
1946 const MCSymbol *End = RS->getEnd();
1947 assert(Begin && "Range without a begin symbol?");
1948 assert(End && "Range without an end symbol?");
1950 Asm->EmitLabelDifference(Begin, Base, Size);
1951 Asm->EmitLabelDifference(End, Base, Size);
1953 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
1954 Asm->OutStreamer->EmitSymbolValue(End, Size);
1959 // And terminate the list with two 0 values.
1960 Asm->OutStreamer->EmitIntValue(0, Size);
1961 Asm->OutStreamer->EmitIntValue(0, Size);
1966 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
1967 for (auto *MN : Nodes) {
1968 if (auto *M = dyn_cast<DIMacro>(MN))
1970 else if (auto *F = dyn_cast<DIMacroFile>(MN))
1971 emitMacroFile(*F, U);
1973 llvm_unreachable("Unexpected DI type!");
1977 void DwarfDebug::emitMacro(DIMacro &M) {
1978 Asm->EmitULEB128(M.getMacinfoType());
1979 Asm->EmitULEB128(M.getLine());
1980 StringRef Name = M.getName();
1981 StringRef Value = M.getValue();
1982 Asm->OutStreamer->EmitBytes(Name);
1983 if (!Value.empty()) {
1984 // There should be one space between macro name and macro value.
1986 Asm->OutStreamer->EmitBytes(Value);
1988 Asm->EmitInt8('\0');
1991 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
1992 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
1993 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
1994 Asm->EmitULEB128(F.getLine());
1995 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
1996 handleMacroNodes(F.getElements(), U);
1997 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2000 /// Emit macros into a debug macinfo section.
2001 void DwarfDebug::emitDebugMacinfo() {
2005 // Start the dwarf macinfo section.
2006 Asm->OutStreamer->SwitchSection(
2007 Asm->getObjFileLowering().getDwarfMacinfoSection());
2009 for (const auto &P : CUMap) {
2010 auto &TheCU = *P.second;
2011 auto *SkCU = TheCU.getSkeleton();
2012 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2013 auto *CUNode = cast<DICompileUnit>(P.first);
2014 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2015 handleMacroNodes(CUNode->getMacros(), U);
2017 Asm->OutStreamer->AddComment("End Of Macro List Mark");
2021 // DWARF5 Experimental Separate Dwarf emitters.
2023 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2024 std::unique_ptr<DwarfCompileUnit> NewU) {
2025 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2026 Asm->TM.Options.MCOptions.SplitDwarfFile);
2028 if (!CompilationDir.empty())
2029 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2031 addGnuPubAttributes(*NewU, Die);
2033 SkeletonHolder.addUnit(std::move(NewU));
2036 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2037 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2038 // DW_AT_addr_base, DW_AT_ranges_base.
2039 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2041 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
2042 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2043 DwarfCompileUnit &NewCU = *OwnedUnit;
2044 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2046 NewCU.initStmtList();
2048 if (useSegmentedStringOffsetsTable())
2049 NewCU.addStringOffsetsStart();
2051 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2056 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2057 // compile units that would normally be in debug_info.
2058 void DwarfDebug::emitDebugInfoDWO() {
2059 assert(useSplitDwarf() && "No split dwarf debug info?");
2060 // Don't emit relocations into the dwo file.
2061 InfoHolder.emitUnits(/* UseOffsets */ true);
2064 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2065 // abbreviations for the .debug_info.dwo section.
2066 void DwarfDebug::emitDebugAbbrevDWO() {
2067 assert(useSplitDwarf() && "No split dwarf?");
2068 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2071 void DwarfDebug::emitDebugLineDWO() {
2072 assert(useSplitDwarf() && "No split dwarf?");
2073 Asm->OutStreamer->SwitchSection(
2074 Asm->getObjFileLowering().getDwarfLineDWOSection());
2075 SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
2078 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2079 assert(useSplitDwarf() && "No split dwarf?");
2080 InfoHolder.emitStringOffsetsTableHeader(
2081 Asm->getObjFileLowering().getDwarfStrOffDWOSection());
2084 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2085 // string section and is identical in format to traditional .debug_str
2087 void DwarfDebug::emitDebugStrDWO() {
2088 if (useSegmentedStringOffsetsTable())
2089 emitStringOffsetsTableHeaderDWO();
2090 assert(useSplitDwarf() && "No split dwarf?");
2091 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2092 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2093 OffSec, /* UseRelativeOffsets = */ false);
2096 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2097 if (!useSplitDwarf())
2100 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
2101 return &SplitTypeUnitFileTable;
2104 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2106 Hash.update(Identifier);
2107 // ... take the least significant 8 bytes and return those. Our MD5
2108 // implementation always returns its results in little endian, so we actually
2109 // need the "high" word.
2110 MD5::MD5Result Result;
2112 return Result.high();
2115 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2116 StringRef Identifier, DIE &RefDie,
2117 const DICompositeType *CTy) {
2118 // Fast path if we're building some type units and one has already used the
2119 // address pool we know we're going to throw away all this work anyway, so
2120 // don't bother building dependent types.
2121 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2124 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2126 CU.addDIETypeSignature(RefDie, Ins.first->second);
2130 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2131 AddrPool.resetUsedFlag();
2133 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2134 getDwoLineTable(CU));
2135 DwarfTypeUnit &NewTU = *OwnedUnit;
2136 DIE &UnitDie = NewTU.getUnitDie();
2137 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2139 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2142 uint64_t Signature = makeTypeSignature(Identifier);
2143 NewTU.setTypeSignature(Signature);
2144 Ins.first->second = Signature;
2146 if (useSplitDwarf())
2147 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2149 CU.applyStmtList(UnitDie);
2150 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2153 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2155 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2156 NewTU.addStringOffsetsStart();
2158 NewTU.setType(NewTU.createTypeDIE(CTy));
2161 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2162 TypeUnitsUnderConstruction.clear();
2164 // Types referencing entries in the address table cannot be placed in type
2166 if (AddrPool.hasBeenUsed()) {
2168 // Remove all the types built while building this type.
2169 // This is pessimistic as some of these types might not be dependent on
2170 // the type that used an address.
2171 for (const auto &TU : TypeUnitsToAdd)
2172 TypeSignatures.erase(TU.second);
2174 // Construct this type in the CU directly.
2175 // This is inefficient because all the dependent types will be rebuilt
2176 // from scratch, including building them in type units, discovering that
2177 // they depend on addresses, throwing them out and rebuilding them.
2178 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2182 // If the type wasn't dependent on fission addresses, finish adding the type
2183 // and all its dependent types.
2184 for (auto &TU : TypeUnitsToAdd) {
2185 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2186 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2189 CU.addDIETypeSignature(RefDie, Signature);
2192 // Accelerator table mutators - add each name along with its companion
2193 // DIE to the proper table while ensuring that the name that we're going
2194 // to reference is in the string table. We do this since the names we
2195 // add may not only be identical to the names in the DIE.
2196 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2197 if (!useDwarfAccelTables())
2199 AccelNames.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2202 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2203 if (!useDwarfAccelTables())
2205 AccelObjC.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2208 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2209 if (!useDwarfAccelTables())
2211 AccelNamespace.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2214 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2215 if (!useDwarfAccelTables())
2217 AccelTypes.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2220 uint16_t DwarfDebug::getDwarfVersion() const {
2221 return Asm->OutStreamer->getContext().getDwarfVersion();