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 "DwarfCompileUnit.h"
18 #include "DwarfExpression.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/DIE.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
56 #define DEBUG_TYPE "dwarfdebug"
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60 cl::desc("Disable debug info printing"));
62 static cl::opt<bool> UnknownLocations(
63 "use-unknown-locations", cl::Hidden,
64 cl::desc("Make an absence of debug location information explicit."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113 return DD->resolve(Ref);
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type)
154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156 DIArray Elements = DICompositeType(subType).getElements();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172 : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
173 InfoHolder(A, *this, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, *this, "skel_string", DIEValueAllocator),
176 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = nullptr) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 static bool isObjCClass(StringRef Name) {
240 return Name.startswith("+") || Name.startswith("-");
243 static bool hasObjCCategory(StringRef Name) {
244 if (!isObjCClass(Name))
247 return Name.find(") ") != StringRef::npos;
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251 StringRef &Category) {
252 if (!hasObjCCategory(In)) {
253 Class = In.slice(In.find('[') + 1, In.find(' '));
258 Class = In.slice(In.find('[') + 1, In.find('('));
259 Category = In.slice(In.find('[') + 1, In.find(' '));
263 static StringRef getObjCMethodName(StringRef In) {
264 return In.slice(In.find(' ') + 1, In.find(']'));
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269 std::string LA = (A ? A->getLabelBeginName() : "");
270 std::string LB = (B ? B->getLabelBeginName() : "");
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279 if (!SP.isDefinition())
281 addAccelName(SP.getName(), Die);
283 // If the linkage name is different than the name, go ahead and output
284 // that as well into the name table.
285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286 addAccelName(SP.getLinkageName(), Die);
288 // If this is an Objective-C selector name add it to the ObjC accelerator
290 if (isObjCClass(SP.getName())) {
291 StringRef Class, Category;
292 getObjCClassCategory(SP.getName(), Class, Category);
293 addAccelObjC(Class, Die);
295 addAccelObjC(Category, Die);
296 // Also add the base method name to the name table.
297 addAccelName(getObjCMethodName(SP.getName()), Die);
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
306 DIDescriptor D(Context);
307 if (D.isSubprogram())
310 return isSubprogramContext(resolve(DIType(Context).getContext()));
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
325 if (Ranges.size() > 1)
328 // We don't create a DIE if we have a single Range and the end label
330 return !getLabelAfterInsn(Ranges.front().second);
333 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
335 if (auto *SkelCU = CU.getSkeleton())
339 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
340 assert(Scope && Scope->getScopeNode());
341 assert(Scope->isAbstractScope());
342 assert(!Scope->getInlinedAt());
344 const MDNode *SP = Scope->getScopeNode();
346 ProcessedSPNodes.insert(SP);
348 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
349 // was inlined from another compile unit.
350 auto &CU = SPMap[SP];
351 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
352 CU.constructAbstractSubprogramScopeDIE(Scope);
356 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
357 if (!GenerateGnuPubSections)
360 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
363 // Create new DwarfCompileUnit for the given metadata node with tag
364 // DW_TAG_compile_unit.
365 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
366 StringRef FN = DIUnit.getFilename();
367 CompilationDir = DIUnit.getDirectory();
369 auto OwnedUnit = make_unique<DwarfCompileUnit>(
370 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
371 DwarfCompileUnit &NewCU = *OwnedUnit;
372 DIE &Die = NewCU.getUnitDie();
373 InfoHolder.addUnit(std::move(OwnedUnit));
375 NewCU.setSkeleton(constructSkeletonCU(NewCU));
377 // LTO with assembly output shares a single line table amongst multiple CUs.
378 // To avoid the compilation directory being ambiguous, let the line table
379 // explicitly describe the directory of all files, never relying on the
380 // compilation directory.
381 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
382 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
383 NewCU.getUniqueID(), CompilationDir);
385 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
386 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
387 DIUnit.getLanguage());
388 NewCU.addString(Die, dwarf::DW_AT_name, FN);
390 if (!useSplitDwarf()) {
391 NewCU.initStmtList(DwarfLineSectionSym);
393 // If we're using split dwarf the compilation dir is going to be in the
394 // skeleton CU and so we don't need to duplicate it here.
395 if (!CompilationDir.empty())
396 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
398 addGnuPubAttributes(NewCU, Die);
401 if (DIUnit.isOptimized())
402 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
404 StringRef Flags = DIUnit.getFlags();
406 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
408 if (unsigned RVer = DIUnit.getRunTimeVersion())
409 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
410 dwarf::DW_FORM_data1, RVer);
413 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
414 DwarfInfoDWOSectionSym);
416 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
417 DwarfInfoSectionSym);
419 CUMap.insert(std::make_pair(DIUnit, &NewCU));
420 CUDieMap.insert(std::make_pair(&Die, &NewCU));
424 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
426 DIImportedEntity Module(N);
427 assert(Module.Verify());
428 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
429 D->addChild(TheCU.constructImportedEntityDIE(Module));
432 // Emit all Dwarf sections that should come prior to the content. Create
433 // global DIEs and emit initial debug info sections. This is invoked by
434 // the target AsmPrinter.
435 void DwarfDebug::beginModule() {
436 if (DisableDebugInfoPrinting)
439 const Module *M = MMI->getModule();
441 FunctionDIs = makeSubprogramMap(*M);
443 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
446 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
448 // Emit initial sections so we can reference labels later.
451 SingleCU = CU_Nodes->getNumOperands() == 1;
453 for (MDNode *N : CU_Nodes->operands()) {
454 DICompileUnit CUNode(N);
455 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
456 DIArray ImportedEntities = CUNode.getImportedEntities();
457 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
458 ScopesWithImportedEntities.push_back(std::make_pair(
459 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
460 ImportedEntities.getElement(i)));
461 std::sort(ScopesWithImportedEntities.begin(),
462 ScopesWithImportedEntities.end(), less_first());
463 DIArray GVs = CUNode.getGlobalVariables();
464 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
465 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
466 DIArray SPs = CUNode.getSubprograms();
467 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
468 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
469 DIArray EnumTypes = CUNode.getEnumTypes();
470 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
471 DIType Ty(EnumTypes.getElement(i));
472 // The enum types array by design contains pointers to
473 // MDNodes rather than DIRefs. Unique them here.
474 DIType UniqueTy(resolve(Ty.getRef()));
475 CU.getOrCreateTypeDIE(UniqueTy);
477 DIArray RetainedTypes = CUNode.getRetainedTypes();
478 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
479 DIType Ty(RetainedTypes.getElement(i));
480 // The retained types array by design contains pointers to
481 // MDNodes rather than DIRefs. Unique them here.
482 DIType UniqueTy(resolve(Ty.getRef()));
483 CU.getOrCreateTypeDIE(UniqueTy);
485 // Emit imported_modules last so that the relevant context is already
487 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
488 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
491 // Tell MMI that we have debug info.
492 MMI->setDebugInfoAvailability(true);
495 void DwarfDebug::finishVariableDefinitions() {
496 for (const auto &Var : ConcreteVariables) {
497 DIE *VariableDie = Var->getDIE();
499 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
500 // in the ConcreteVariables list, rather than looking it up again here.
501 // DIE::getUnit isn't simple - it walks parent pointers, etc.
502 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
504 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
505 if (AbsVar && AbsVar->getDIE()) {
506 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
509 Unit->applyVariableAttributes(*Var, *VariableDie);
513 void DwarfDebug::finishSubprogramDefinitions() {
514 for (const auto &P : SPMap)
515 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
516 CU.finishSubprogramDefinition(DISubprogram(P.first));
521 // Collect info for variables that were optimized out.
522 void DwarfDebug::collectDeadVariables() {
523 const Module *M = MMI->getModule();
525 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
526 for (MDNode *N : CU_Nodes->operands()) {
527 DICompileUnit TheCU(N);
528 // Construct subprogram DIE and add variables DIEs.
529 DwarfCompileUnit *SPCU =
530 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
531 assert(SPCU && "Unable to find Compile Unit!");
532 DIArray Subprograms = TheCU.getSubprograms();
533 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
534 DISubprogram SP(Subprograms.getElement(i));
535 if (ProcessedSPNodes.count(SP) != 0)
537 SPCU->collectDeadVariables(SP);
543 void DwarfDebug::finalizeModuleInfo() {
544 finishSubprogramDefinitions();
546 finishVariableDefinitions();
548 // Collect info for variables that were optimized out.
549 collectDeadVariables();
551 // Handle anything that needs to be done on a per-unit basis after
552 // all other generation.
553 for (const auto &P : CUMap) {
554 auto &TheCU = *P.second;
555 // Emit DW_AT_containing_type attribute to connect types with their
556 // vtable holding type.
557 TheCU.constructContainingTypeDIEs();
559 // Add CU specific attributes if we need to add any.
560 // If we're splitting the dwarf out now that we've got the entire
561 // CU then add the dwo id to it.
562 auto *SkCU = TheCU.getSkeleton();
563 if (useSplitDwarf()) {
564 // Emit a unique identifier for this CU.
565 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
566 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
567 dwarf::DW_FORM_data8, ID);
568 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
569 dwarf::DW_FORM_data8, ID);
571 // We don't keep track of which addresses are used in which CU so this
572 // is a bit pessimistic under LTO.
573 if (!AddrPool.isEmpty())
574 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
575 DwarfAddrSectionSym, DwarfAddrSectionSym);
576 if (!SkCU->getRangeLists().empty())
577 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
578 DwarfDebugRangeSectionSym,
579 DwarfDebugRangeSectionSym);
582 // If we have code split among multiple sections or non-contiguous
583 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
584 // remain in the .o file, otherwise add a DW_AT_low_pc.
585 // FIXME: We should use ranges allow reordering of code ala
586 // .subsections_via_symbols in mach-o. This would mean turning on
587 // ranges for all subprogram DIEs for mach-o.
588 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
589 if (unsigned NumRanges = TheCU.getRanges().size()) {
591 // A DW_AT_low_pc attribute may also be specified in combination with
592 // DW_AT_ranges to specify the default base address for use in
593 // location lists (see Section 2.6.2) and range lists (see Section
595 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
597 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
598 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
602 // Compute DIE offsets and sizes.
603 InfoHolder.computeSizeAndOffsets();
605 SkeletonHolder.computeSizeAndOffsets();
608 // Emit all Dwarf sections that should come after the content.
609 void DwarfDebug::endModule() {
610 assert(CurFn == nullptr);
611 assert(CurMI == nullptr);
613 // If we aren't actually generating debug info (check beginModule -
614 // conditionalized on !DisableDebugInfoPrinting and the presence of the
615 // llvm.dbg.cu metadata node)
616 if (!DwarfInfoSectionSym)
619 // Finalize the debug info for the module.
620 finalizeModuleInfo();
624 // Emit all the DIEs into a debug info section.
627 // Corresponding abbreviations into a abbrev section.
630 // Emit info into a debug aranges section.
631 if (GenerateARangeSection)
634 // Emit info into a debug ranges section.
637 if (useSplitDwarf()) {
640 emitDebugAbbrevDWO();
643 // Emit DWO addresses.
644 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
646 // Emit info into a debug loc section.
649 // Emit info into the dwarf accelerator table sections.
650 if (useDwarfAccelTables()) {
653 emitAccelNamespaces();
657 // Emit the pubnames and pubtypes sections if requested.
658 if (HasDwarfPubSections) {
659 emitDebugPubNames(GenerateGnuPubSections);
660 emitDebugPubTypes(GenerateGnuPubSections);
665 AbstractVariables.clear();
668 // Find abstract variable, if any, associated with Var.
669 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
670 DIVariable &Cleansed) {
671 LLVMContext &Ctx = DV->getContext();
672 // More then one inlined variable corresponds to one abstract variable.
673 // FIXME: This duplication of variables when inlining should probably be
674 // removed. It's done to allow each DIVariable to describe its location
675 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
676 // make it accurate then remove this duplication/cleansing stuff.
677 Cleansed = cleanseInlinedVariable(DV, Ctx);
678 auto I = AbstractVariables.find(Cleansed);
679 if (I != AbstractVariables.end())
680 return I->second.get();
684 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
686 return getExistingAbstractVariable(DV, Cleansed);
689 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
690 LexicalScope *Scope) {
691 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
692 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
693 AbstractVariables[Var] = std::move(AbsDbgVariable);
696 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
697 const MDNode *ScopeNode) {
698 DIVariable Cleansed = DV;
699 if (getExistingAbstractVariable(DV, Cleansed))
702 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
706 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
707 const MDNode *ScopeNode) {
708 DIVariable Cleansed = DV;
709 if (getExistingAbstractVariable(DV, Cleansed))
712 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
713 createAbstractVariable(Cleansed, Scope);
716 // Collect variable information from side table maintained by MMI.
717 void DwarfDebug::collectVariableInfoFromMMITable(
718 SmallPtrSetImpl<const MDNode *> &Processed) {
719 for (const auto &VI : MMI->getVariableDbgInfo()) {
722 Processed.insert(VI.Var);
723 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
725 // If variable scope is not found then skip this variable.
729 DIVariable DV(VI.Var);
730 DIExpression Expr(VI.Expr);
731 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
732 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
733 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
734 ConcreteVariables.push_back(std::move(RegVar));
738 // Get .debug_loc entry for the instruction range starting at MI.
739 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
740 const MDNode *Expr = MI->getDebugExpression();
741 const MDNode *Var = MI->getDebugVariable();
743 assert(MI->getNumOperands() == 4);
744 if (MI->getOperand(0).isReg()) {
745 MachineLocation MLoc;
746 // If the second operand is an immediate, this is a
747 // register-indirect address.
748 if (!MI->getOperand(1).isImm())
749 MLoc.set(MI->getOperand(0).getReg());
751 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
752 return DebugLocEntry::Value(Var, Expr, MLoc);
754 if (MI->getOperand(0).isImm())
755 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
756 if (MI->getOperand(0).isFPImm())
757 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
758 if (MI->getOperand(0).isCImm())
759 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
761 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
764 /// Determine whether two variable pieces overlap.
765 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
766 if (!P1.isBitPiece() || !P2.isBitPiece())
768 unsigned l1 = P1.getBitPieceOffset();
769 unsigned l2 = P2.getBitPieceOffset();
770 unsigned r1 = l1 + P1.getBitPieceSize();
771 unsigned r2 = l2 + P2.getBitPieceSize();
772 // True where [l1,r1[ and [r1,r2[ overlap.
773 return (l1 < r2) && (l2 < r1);
776 /// Build the location list for all DBG_VALUEs in the function that
777 /// describe the same variable. If the ranges of several independent
778 /// pieces of the same variable overlap partially, split them up and
779 /// combine the ranges. The resulting DebugLocEntries are will have
780 /// strict monotonically increasing begin addresses and will never
785 // Ranges History [var, loc, piece ofs size]
786 // 0 | [x, (reg0, piece 0, 32)]
787 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
789 // 3 | [clobber reg0]
790 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
795 // [0-1] [x, (reg0, piece 0, 32)]
796 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
797 // [3-4] [x, (reg1, piece 32, 32)]
798 // [4- ] [x, (mem, piece 0, 64)]
800 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
801 const DbgValueHistoryMap::InstrRanges &Ranges) {
802 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
804 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
805 const MachineInstr *Begin = I->first;
806 const MachineInstr *End = I->second;
807 assert(Begin->isDebugValue() && "Invalid History entry");
809 // Check if a variable is inaccessible in this range.
810 if (Begin->getNumOperands() > 1 &&
811 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
816 // If this piece overlaps with any open ranges, truncate them.
817 DIExpression DIExpr = Begin->getDebugExpression();
818 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
819 [&](DebugLocEntry::Value R) {
820 return piecesOverlap(DIExpr, R.getExpression());
822 OpenRanges.erase(Last, OpenRanges.end());
824 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
825 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
827 const MCSymbol *EndLabel;
829 EndLabel = getLabelAfterInsn(End);
830 else if (std::next(I) == Ranges.end())
831 EndLabel = FunctionEndSym;
833 EndLabel = getLabelBeforeInsn(std::next(I)->first);
834 assert(EndLabel && "Forgot label after instruction ending a range!");
836 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
838 auto Value = getDebugLocValue(Begin);
839 DebugLocEntry Loc(StartLabel, EndLabel, Value);
840 bool couldMerge = false;
842 // If this is a piece, it may belong to the current DebugLocEntry.
843 if (DIExpr.isBitPiece()) {
844 // Add this value to the list of open ranges.
845 OpenRanges.push_back(Value);
847 // Attempt to add the piece to the last entry.
848 if (!DebugLoc.empty())
849 if (DebugLoc.back().MergeValues(Loc))
854 // Need to add a new DebugLocEntry. Add all values from still
855 // valid non-overlapping pieces.
856 if (OpenRanges.size())
857 Loc.addValues(OpenRanges);
859 DebugLoc.push_back(std::move(Loc));
862 // Attempt to coalesce the ranges of two otherwise identical
864 auto CurEntry = DebugLoc.rbegin();
865 auto PrevEntry = std::next(CurEntry);
866 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
870 dbgs() << CurEntry->getValues().size() << " Values:\n";
871 for (auto Value : CurEntry->getValues()) {
872 Value.getVariable()->dump();
873 Value.getExpression()->dump();
881 // Find variables for each lexical scope.
883 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
884 SmallPtrSetImpl<const MDNode *> &Processed) {
885 // Grab the variable info that was squirreled away in the MMI side-table.
886 collectVariableInfoFromMMITable(Processed);
888 for (const auto &I : DbgValues) {
889 DIVariable DV(I.first);
890 if (Processed.count(DV))
893 // Instruction ranges, specifying where DV is accessible.
894 const auto &Ranges = I.second;
898 LexicalScope *Scope = nullptr;
899 if (MDNode *IA = DV.getInlinedAt())
900 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
902 Scope = LScopes.findLexicalScope(DV.getContext());
903 // If variable scope is not found then skip this variable.
907 Processed.insert(DV);
908 const MachineInstr *MInsn = Ranges.front().first;
909 assert(MInsn->isDebugValue() && "History must begin with debug value");
910 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
911 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
912 DbgVariable *RegVar = ConcreteVariables.back().get();
913 InfoHolder.addScopeVariable(Scope, RegVar);
915 // Check if the first DBG_VALUE is valid for the rest of the function.
916 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
919 // Handle multiple DBG_VALUE instructions describing one variable.
920 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
922 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
923 DebugLocList &LocList = DotDebugLocEntries.back();
926 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
928 // Build the location list for this variable.
929 buildLocationList(LocList.List, Ranges);
932 // Collect info for variables that were optimized out.
933 DIArray Variables = SP.getVariables();
934 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
935 DIVariable DV(Variables.getElement(i));
936 assert(DV.isVariable());
937 if (!Processed.insert(DV).second)
939 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
940 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
942 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
943 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
948 // Return Label preceding the instruction.
949 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
950 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
951 assert(Label && "Didn't insert label before instruction");
955 // Return Label immediately following the instruction.
956 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
957 return LabelsAfterInsn.lookup(MI);
960 // Process beginning of an instruction.
961 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
962 assert(CurMI == nullptr);
964 // Check if source location changes, but ignore DBG_VALUE locations.
965 if (!MI->isDebugValue()) {
966 DebugLoc DL = MI->getDebugLoc();
967 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
970 if (DL == PrologEndLoc) {
971 Flags |= DWARF2_FLAG_PROLOGUE_END;
972 PrologEndLoc = DebugLoc();
973 Flags |= DWARF2_FLAG_IS_STMT;
976 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
977 Flags |= DWARF2_FLAG_IS_STMT;
979 if (!DL.isUnknown()) {
980 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
981 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
983 recordSourceLine(0, 0, nullptr, 0);
987 // Insert labels where requested.
988 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
989 LabelsBeforeInsn.find(MI);
992 if (I == LabelsBeforeInsn.end())
995 // Label already assigned.
1000 PrevLabel = MMI->getContext().CreateTempSymbol();
1001 Asm->OutStreamer.EmitLabel(PrevLabel);
1003 I->second = PrevLabel;
1006 // Process end of an instruction.
1007 void DwarfDebug::endInstruction() {
1008 assert(CurMI != nullptr);
1009 // Don't create a new label after DBG_VALUE instructions.
1010 // They don't generate code.
1011 if (!CurMI->isDebugValue())
1012 PrevLabel = nullptr;
1014 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1015 LabelsAfterInsn.find(CurMI);
1019 if (I == LabelsAfterInsn.end())
1022 // Label already assigned.
1026 // We need a label after this instruction.
1028 PrevLabel = MMI->getContext().CreateTempSymbol();
1029 Asm->OutStreamer.EmitLabel(PrevLabel);
1031 I->second = PrevLabel;
1034 // Each LexicalScope has first instruction and last instruction to mark
1035 // beginning and end of a scope respectively. Create an inverse map that list
1036 // scopes starts (and ends) with an instruction. One instruction may start (or
1037 // end) multiple scopes. Ignore scopes that are not reachable.
1038 void DwarfDebug::identifyScopeMarkers() {
1039 SmallVector<LexicalScope *, 4> WorkList;
1040 WorkList.push_back(LScopes.getCurrentFunctionScope());
1041 while (!WorkList.empty()) {
1042 LexicalScope *S = WorkList.pop_back_val();
1044 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1045 if (!Children.empty())
1046 WorkList.append(Children.begin(), Children.end());
1048 if (S->isAbstractScope())
1051 for (const InsnRange &R : S->getRanges()) {
1052 assert(R.first && "InsnRange does not have first instruction!");
1053 assert(R.second && "InsnRange does not have second instruction!");
1054 requestLabelBeforeInsn(R.first);
1055 requestLabelAfterInsn(R.second);
1060 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1061 // First known non-DBG_VALUE and non-frame setup location marks
1062 // the beginning of the function body.
1063 for (const auto &MBB : *MF)
1064 for (const auto &MI : MBB)
1065 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1066 !MI.getDebugLoc().isUnknown()) {
1067 // Did the target forget to set the FrameSetup flag for CFI insns?
1068 assert(!MI.isCFIInstruction() &&
1069 "First non-frame-setup instruction is a CFI instruction.");
1070 return MI.getDebugLoc();
1075 // Gather pre-function debug information. Assumes being called immediately
1076 // after the function entry point has been emitted.
1077 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1080 // If there's no debug info for the function we're not going to do anything.
1081 if (!MMI->hasDebugInfo())
1084 auto DI = FunctionDIs.find(MF->getFunction());
1085 if (DI == FunctionDIs.end())
1088 // Grab the lexical scopes for the function, if we don't have any of those
1089 // then we're not going to be able to do anything.
1090 LScopes.initialize(*MF);
1091 if (LScopes.empty())
1094 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1096 // Make sure that each lexical scope will have a begin/end label.
1097 identifyScopeMarkers();
1099 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1100 // belongs to so that we add to the correct per-cu line table in the
1102 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1103 // FnScope->getScopeNode() and DI->second should represent the same function,
1104 // though they may not be the same MDNode due to inline functions merged in
1105 // LTO where the debug info metadata still differs (either due to distinct
1106 // written differences - two versions of a linkonce_odr function
1107 // written/copied into two separate files, or some sub-optimal metadata that
1108 // isn't structurally identical (see: file path/name info from clang, which
1109 // includes the directory of the cpp file being built, even when the file name
1110 // is absolute (such as an <> lookup header)))
1111 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1112 assert(TheCU && "Unable to find compile unit!");
1113 if (Asm->OutStreamer.hasRawTextSupport())
1114 // Use a single line table if we are generating assembly.
1115 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1117 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1119 // Emit a label for the function so that we have a beginning address.
1120 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1121 // Assumes in correct section after the entry point.
1122 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1124 // Calculate history for local variables.
1125 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1128 // Request labels for the full history.
1129 for (const auto &I : DbgValues) {
1130 const auto &Ranges = I.second;
1134 // The first mention of a function argument gets the FunctionBeginSym
1135 // label, so arguments are visible when breaking at function entry.
1136 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1137 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1138 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1139 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1140 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1141 // Mark all non-overlapping initial pieces.
1142 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1143 DIExpression Piece = I->first->getDebugExpression();
1144 if (std::all_of(Ranges.begin(), I,
1145 [&](DbgValueHistoryMap::InstrRange Pred) {
1146 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1148 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1155 for (const auto &Range : Ranges) {
1156 requestLabelBeforeInsn(Range.first);
1158 requestLabelAfterInsn(Range.second);
1162 PrevInstLoc = DebugLoc();
1163 PrevLabel = FunctionBeginSym;
1165 // Record beginning of function.
1166 PrologEndLoc = findPrologueEndLoc(MF);
1167 if (!PrologEndLoc.isUnknown()) {
1168 DebugLoc FnStartDL =
1169 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1171 // We'd like to list the prologue as "not statements" but GDB behaves
1172 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1173 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1174 FnStartDL.getScope(MF->getFunction()->getContext()),
1175 DWARF2_FLAG_IS_STMT);
1179 // Gather and emit post-function debug information.
1180 void DwarfDebug::endFunction(const MachineFunction *MF) {
1181 assert(CurFn == MF &&
1182 "endFunction should be called with the same function as beginFunction");
1184 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1185 !FunctionDIs.count(MF->getFunction())) {
1186 // If we don't have a lexical scope for this function then there will
1187 // be a hole in the range information. Keep note of this by setting the
1188 // previously used section to nullptr.
1194 // Define end label for subprogram.
1195 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1196 // Assumes in correct section after the entry point.
1197 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1199 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1200 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1202 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1203 DISubprogram SP(FnScope->getScopeNode());
1204 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1206 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1207 collectVariableInfo(TheCU, SP, ProcessedVars);
1209 // Add the range of this function to the list of ranges for the CU.
1210 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1212 // Under -gmlt, skip building the subprogram if there are no inlined
1213 // subroutines inside it.
1214 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1215 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1216 assert(InfoHolder.getScopeVariables().empty());
1217 assert(DbgValues.empty());
1218 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1219 // by a -gmlt CU. Add a test and remove this assertion.
1220 assert(AbstractVariables.empty());
1221 LabelsBeforeInsn.clear();
1222 LabelsAfterInsn.clear();
1223 PrevLabel = nullptr;
1229 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1231 // Construct abstract scopes.
1232 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1233 DISubprogram SP(AScope->getScopeNode());
1234 assert(SP.isSubprogram());
1235 // Collect info for variables that were optimized out.
1236 DIArray Variables = SP.getVariables();
1237 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1238 DIVariable DV(Variables.getElement(i));
1239 assert(DV && DV.isVariable());
1240 if (!ProcessedVars.insert(DV).second)
1242 ensureAbstractVariableIsCreated(DV, DV.getContext());
1243 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1244 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1246 constructAbstractSubprogramScopeDIE(AScope);
1249 TheCU.constructSubprogramScopeDIE(FnScope);
1250 if (auto *SkelCU = TheCU.getSkeleton())
1251 if (!LScopes.getAbstractScopesList().empty())
1252 SkelCU->constructSubprogramScopeDIE(FnScope);
1255 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1256 // DbgVariables except those that are also in AbstractVariables (since they
1257 // can be used cross-function)
1258 InfoHolder.getScopeVariables().clear();
1260 LabelsBeforeInsn.clear();
1261 LabelsAfterInsn.clear();
1262 PrevLabel = nullptr;
1266 // Register a source line with debug info. Returns the unique label that was
1267 // emitted and which provides correspondence to the source line list.
1268 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1273 unsigned Discriminator = 0;
1274 if (DIScope Scope = DIScope(S)) {
1275 assert(Scope.isScope());
1276 Fn = Scope.getFilename();
1277 Dir = Scope.getDirectory();
1278 if (Scope.isLexicalBlockFile())
1279 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1281 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1282 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1283 .getOrCreateSourceID(Fn, Dir);
1285 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1289 //===----------------------------------------------------------------------===//
1291 //===----------------------------------------------------------------------===//
1293 // Emit initial Dwarf sections with a label at the start of each one.
1294 void DwarfDebug::emitSectionLabels() {
1295 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1297 // Dwarf sections base addresses.
1298 DwarfInfoSectionSym =
1299 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1300 if (useSplitDwarf()) {
1301 DwarfInfoDWOSectionSym =
1302 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1303 DwarfTypesDWOSectionSym = emitSectionSym(
1304 Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1306 DwarfAbbrevSectionSym =
1307 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1308 if (useSplitDwarf())
1309 DwarfAbbrevDWOSectionSym = emitSectionSym(
1310 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1311 if (GenerateARangeSection)
1312 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1314 DwarfLineSectionSym =
1315 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1316 if (GenerateGnuPubSections) {
1317 DwarfGnuPubNamesSectionSym =
1318 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1319 DwarfGnuPubTypesSectionSym =
1320 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1321 } else if (HasDwarfPubSections) {
1322 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1323 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1326 DwarfStrSectionSym =
1327 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1328 if (useSplitDwarf()) {
1329 DwarfStrDWOSectionSym =
1330 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1331 DwarfAddrSectionSym =
1332 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1333 DwarfDebugLocSectionSym =
1334 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1336 DwarfDebugLocSectionSym =
1337 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1338 DwarfDebugRangeSectionSym =
1339 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1342 // Recursively emits a debug information entry.
1343 void DwarfDebug::emitDIE(DIE &Die) {
1344 // Get the abbreviation for this DIE.
1345 const DIEAbbrev &Abbrev = Die.getAbbrev();
1347 // Emit the code (index) for the abbreviation.
1348 if (Asm->isVerbose())
1349 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1350 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1351 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1352 dwarf::TagString(Abbrev.getTag()));
1353 Asm->EmitULEB128(Abbrev.getNumber());
1355 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1356 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1358 // Emit the DIE attribute values.
1359 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1360 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1361 dwarf::Form Form = AbbrevData[i].getForm();
1362 assert(Form && "Too many attributes for DIE (check abbreviation)");
1364 if (Asm->isVerbose()) {
1365 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1366 if (Attr == dwarf::DW_AT_accessibility)
1367 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1368 cast<DIEInteger>(Values[i])->getValue()));
1371 // Emit an attribute using the defined form.
1372 Values[i]->EmitValue(Asm, Form);
1375 // Emit the DIE children if any.
1376 if (Abbrev.hasChildren()) {
1377 for (auto &Child : Die.getChildren())
1380 Asm->OutStreamer.AddComment("End Of Children Mark");
1385 // Emit the debug info section.
1386 void DwarfDebug::emitDebugInfo() {
1387 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1389 Holder.emitUnits(DwarfAbbrevSectionSym);
1392 // Emit the abbreviation section.
1393 void DwarfDebug::emitAbbreviations() {
1394 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1396 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1399 // Emit the last address of the section and the end of the line matrix.
1400 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1401 // Define last address of section.
1402 Asm->OutStreamer.AddComment("Extended Op");
1405 Asm->OutStreamer.AddComment("Op size");
1406 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1407 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1408 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1410 Asm->OutStreamer.AddComment("Section end label");
1412 Asm->OutStreamer.EmitSymbolValue(
1413 Asm->GetTempSymbol("section_end", SectionEnd),
1414 Asm->getDataLayout().getPointerSize());
1416 // Mark end of matrix.
1417 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1423 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1424 StringRef TableName, StringRef SymName) {
1425 Accel.FinalizeTable(Asm, TableName);
1426 Asm->OutStreamer.SwitchSection(Section);
1427 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1428 Asm->OutStreamer.EmitLabel(SectionBegin);
1430 // Emit the full data.
1431 Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1434 // Emit visible names into a hashed accelerator table section.
1435 void DwarfDebug::emitAccelNames() {
1436 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1437 "Names", "names_begin");
1440 // Emit objective C classes and categories into a hashed accelerator table
1442 void DwarfDebug::emitAccelObjC() {
1443 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1444 "ObjC", "objc_begin");
1447 // Emit namespace dies into a hashed accelerator table.
1448 void DwarfDebug::emitAccelNamespaces() {
1449 emitAccel(AccelNamespace,
1450 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1451 "namespac", "namespac_begin");
1454 // Emit type dies into a hashed accelerator table.
1455 void DwarfDebug::emitAccelTypes() {
1456 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1457 "types", "types_begin");
1460 // Public name handling.
1461 // The format for the various pubnames:
1463 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1464 // for the DIE that is named.
1466 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1467 // into the CU and the index value is computed according to the type of value
1468 // for the DIE that is named.
1470 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1471 // it's the offset within the debug_info/debug_types dwo section, however, the
1472 // reference in the pubname header doesn't change.
1474 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1475 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1477 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1479 // We could have a specification DIE that has our most of our knowledge,
1480 // look for that now.
1481 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1483 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1484 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1485 Linkage = dwarf::GIEL_EXTERNAL;
1486 } else if (Die->findAttribute(dwarf::DW_AT_external))
1487 Linkage = dwarf::GIEL_EXTERNAL;
1489 switch (Die->getTag()) {
1490 case dwarf::DW_TAG_class_type:
1491 case dwarf::DW_TAG_structure_type:
1492 case dwarf::DW_TAG_union_type:
1493 case dwarf::DW_TAG_enumeration_type:
1494 return dwarf::PubIndexEntryDescriptor(
1495 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1496 ? dwarf::GIEL_STATIC
1497 : dwarf::GIEL_EXTERNAL);
1498 case dwarf::DW_TAG_typedef:
1499 case dwarf::DW_TAG_base_type:
1500 case dwarf::DW_TAG_subrange_type:
1501 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1502 case dwarf::DW_TAG_namespace:
1503 return dwarf::GIEK_TYPE;
1504 case dwarf::DW_TAG_subprogram:
1505 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1506 case dwarf::DW_TAG_variable:
1507 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1508 case dwarf::DW_TAG_enumerator:
1509 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1510 dwarf::GIEL_STATIC);
1512 return dwarf::GIEK_NONE;
1516 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1518 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1519 const MCSection *PSec =
1520 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1521 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1523 emitDebugPubSection(GnuStyle, PSec, "Names",
1524 &DwarfCompileUnit::getGlobalNames);
1527 void DwarfDebug::emitDebugPubSection(
1528 bool GnuStyle, const MCSection *PSec, StringRef Name,
1529 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1530 for (const auto &NU : CUMap) {
1531 DwarfCompileUnit *TheU = NU.second;
1533 const auto &Globals = (TheU->*Accessor)();
1535 if (Globals.empty())
1538 if (auto *Skeleton = TheU->getSkeleton())
1540 unsigned ID = TheU->getUniqueID();
1542 // Start the dwarf pubnames section.
1543 Asm->OutStreamer.SwitchSection(PSec);
1546 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1547 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1548 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1549 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1551 Asm->OutStreamer.EmitLabel(BeginLabel);
1553 Asm->OutStreamer.AddComment("DWARF Version");
1554 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1556 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1557 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1559 Asm->OutStreamer.AddComment("Compilation Unit Length");
1560 Asm->EmitInt32(TheU->getLength());
1562 // Emit the pubnames for this compilation unit.
1563 for (const auto &GI : Globals) {
1564 const char *Name = GI.getKeyData();
1565 const DIE *Entity = GI.second;
1567 Asm->OutStreamer.AddComment("DIE offset");
1568 Asm->EmitInt32(Entity->getOffset());
1571 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1572 Asm->OutStreamer.AddComment(
1573 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1574 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1575 Asm->EmitInt8(Desc.toBits());
1578 Asm->OutStreamer.AddComment("External Name");
1579 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1582 Asm->OutStreamer.AddComment("End Mark");
1584 Asm->OutStreamer.EmitLabel(EndLabel);
1588 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1589 const MCSection *PSec =
1590 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1591 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1593 emitDebugPubSection(GnuStyle, PSec, "Types",
1594 &DwarfCompileUnit::getGlobalTypes);
1597 // Emit visible names into a debug str section.
1598 void DwarfDebug::emitDebugStr() {
1599 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1600 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1603 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1604 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1605 const DITypeIdentifierMap &Map,
1606 ArrayRef<DebugLocEntry::Value> Values) {
1607 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1608 return P.isBitPiece();
1609 }) && "all values are expected to be pieces");
1610 assert(std::is_sorted(Values.begin(), Values.end()) &&
1611 "pieces are expected to be sorted");
1613 unsigned Offset = 0;
1614 for (auto Piece : Values) {
1615 DIExpression Expr = Piece.getExpression();
1616 unsigned PieceOffset = Expr.getBitPieceOffset();
1617 unsigned PieceSize = Expr.getBitPieceSize();
1618 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1619 if (Offset < PieceOffset) {
1620 // The DWARF spec seriously mandates pieces with no locations for gaps.
1621 Asm->EmitDwarfOpPiece(Streamer, PieceOffset-Offset);
1622 Offset += PieceOffset-Offset;
1624 Offset += PieceSize;
1627 DIVariable Var = Piece.getVariable();
1628 unsigned VarSize = Var.getSizeInBits(Map);
1629 assert(PieceSize+PieceOffset <= VarSize
1630 && "piece is larger than or outside of variable");
1631 assert(PieceSize != VarSize
1632 && "piece covers entire variable");
1634 emitDebugLocValue(Streamer, Piece, PieceOffset);
1639 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1640 const DebugLocEntry &Entry) {
1641 const DebugLocEntry::Value Value = Entry.getValues()[0];
1642 if (Value.isBitPiece())
1643 // Emit all pieces that belong to the same variable and range.
1644 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1646 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1647 emitDebugLocValue(Streamer, Value);
1650 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1651 const DebugLocEntry::Value &Value,
1652 unsigned PieceOffsetInBits) {
1653 DIVariable DV = Value.getVariable();
1654 DebugLocDwarfExpression DwarfExpr(*Asm, Streamer);
1657 if (Value.isInt()) {
1658 DIBasicType BTy(resolve(DV.getType()));
1659 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1660 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1661 DwarfExpr.AddSignedConstant(Value.getInt());
1663 DwarfExpr.AddUnsignedConstant(Value.getInt());
1664 } else if (Value.isLocation()) {
1665 MachineLocation Loc = Value.getLoc();
1666 DIExpression Expr = Value.getExpression();
1667 if (!Expr || (Expr.getNumElements() == 0))
1669 Asm->EmitDwarfRegOp(Streamer, Loc);
1671 // Complex address entry.
1672 if (Loc.getOffset()) {
1673 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1674 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1676 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1680 // else ... ignore constant fp. There is not any good way to
1681 // to represent them here in dwarf.
1685 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1686 Asm->OutStreamer.AddComment("Loc expr size");
1687 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1688 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1689 Asm->EmitLabelDifference(end, begin, 2);
1690 Asm->OutStreamer.EmitLabel(begin);
1692 APByteStreamer Streamer(*Asm);
1693 emitDebugLocEntry(Streamer, Entry);
1695 Asm->OutStreamer.EmitLabel(end);
1698 // Emit locations into the debug loc section.
1699 void DwarfDebug::emitDebugLoc() {
1700 // Start the dwarf loc section.
1701 Asm->OutStreamer.SwitchSection(
1702 Asm->getObjFileLowering().getDwarfLocSection());
1703 unsigned char Size = Asm->getDataLayout().getPointerSize();
1704 for (const auto &DebugLoc : DotDebugLocEntries) {
1705 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1706 const DwarfCompileUnit *CU = DebugLoc.CU;
1707 for (const auto &Entry : DebugLoc.List) {
1708 // Set up the range. This range is relative to the entry point of the
1709 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1710 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1711 if (auto *Base = CU->getBaseAddress()) {
1712 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1713 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1715 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1716 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1719 emitDebugLocEntryLocation(Entry);
1721 Asm->OutStreamer.EmitIntValue(0, Size);
1722 Asm->OutStreamer.EmitIntValue(0, Size);
1726 void DwarfDebug::emitDebugLocDWO() {
1727 Asm->OutStreamer.SwitchSection(
1728 Asm->getObjFileLowering().getDwarfLocDWOSection());
1729 for (const auto &DebugLoc : DotDebugLocEntries) {
1730 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1731 for (const auto &Entry : DebugLoc.List) {
1732 // Just always use start_length for now - at least that's one address
1733 // rather than two. We could get fancier and try to, say, reuse an
1734 // address we know we've emitted elsewhere (the start of the function?
1735 // The start of the CU or CU subrange that encloses this range?)
1736 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1737 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1738 Asm->EmitULEB128(idx);
1739 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1741 emitDebugLocEntryLocation(Entry);
1743 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1748 const MCSymbol *Start, *End;
1751 // Emit a debug aranges section, containing a CU lookup for any
1752 // address we can tie back to a CU.
1753 void DwarfDebug::emitDebugARanges() {
1754 // Provides a unique id per text section.
1755 DenseMap<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1757 // Prime section data.
1758 SectionMap[Asm->getObjFileLowering().getTextSection()];
1760 // Filter labels by section.
1761 for (const SymbolCU &SCU : ArangeLabels) {
1762 if (SCU.Sym->isInSection()) {
1763 // Make a note of this symbol and it's section.
1764 const MCSection *Section = &SCU.Sym->getSection();
1765 if (!Section->getKind().isMetadata())
1766 SectionMap[Section].push_back(SCU);
1768 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1769 // appear in the output. This sucks as we rely on sections to build
1770 // arange spans. We can do it without, but it's icky.
1771 SectionMap[nullptr].push_back(SCU);
1775 // Build a list of sections used.
1776 std::vector<const MCSection *> Sections;
1777 for (const auto &it : SectionMap) {
1778 const MCSection *Section = it.first;
1779 Sections.push_back(Section);
1782 // Sort the sections into order.
1783 // This is only done to ensure consistent output order across different runs.
1784 std::sort(Sections.begin(), Sections.end(), SectionSort);
1786 // Add terminating symbols for each section.
1787 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1788 const MCSection *Section = Sections[ID];
1789 MCSymbol *Sym = nullptr;
1792 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1793 // if we know the section name up-front. For user-created sections, the
1794 // resulting label may not be valid to use as a label. (section names can
1795 // use a greater set of characters on some systems)
1796 Sym = Asm->GetTempSymbol("debug_end", ID);
1797 Asm->OutStreamer.SwitchSection(Section);
1798 Asm->OutStreamer.EmitLabel(Sym);
1801 // Insert a final terminator.
1802 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1805 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1807 for (const MCSection *Section : Sections) {
1808 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1809 if (List.size() < 2)
1812 // If we have no section (e.g. common), just write out
1813 // individual spans for each symbol.
1815 for (const SymbolCU &Cur : List) {
1817 Span.Start = Cur.Sym;
1820 Spans[Cur.CU].push_back(Span);
1825 // Sort the symbols by offset within the section.
1826 std::sort(List.begin(), List.end(),
1827 [&](const SymbolCU &A, const SymbolCU &B) {
1828 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1829 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1831 // Symbols with no order assigned should be placed at the end.
1832 // (e.g. section end labels)
1840 // Build spans between each label.
1841 const MCSymbol *StartSym = List[0].Sym;
1842 for (size_t n = 1, e = List.size(); n < e; n++) {
1843 const SymbolCU &Prev = List[n - 1];
1844 const SymbolCU &Cur = List[n];
1846 // Try and build the longest span we can within the same CU.
1847 if (Cur.CU != Prev.CU) {
1849 Span.Start = StartSym;
1851 Spans[Prev.CU].push_back(Span);
1857 // Start the dwarf aranges section.
1858 Asm->OutStreamer.SwitchSection(
1859 Asm->getObjFileLowering().getDwarfARangesSection());
1861 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1863 // Build a list of CUs used.
1864 std::vector<DwarfCompileUnit *> CUs;
1865 for (const auto &it : Spans) {
1866 DwarfCompileUnit *CU = it.first;
1870 // Sort the CU list (again, to ensure consistent output order).
1871 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1872 return A->getUniqueID() < B->getUniqueID();
1875 // Emit an arange table for each CU we used.
1876 for (DwarfCompileUnit *CU : CUs) {
1877 std::vector<ArangeSpan> &List = Spans[CU];
1879 // Describe the skeleton CU's offset and length, not the dwo file's.
1880 if (auto *Skel = CU->getSkeleton())
1883 // Emit size of content not including length itself.
1884 unsigned ContentSize =
1885 sizeof(int16_t) + // DWARF ARange version number
1886 sizeof(int32_t) + // Offset of CU in the .debug_info section
1887 sizeof(int8_t) + // Pointer Size (in bytes)
1888 sizeof(int8_t); // Segment Size (in bytes)
1890 unsigned TupleSize = PtrSize * 2;
1892 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1894 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1896 ContentSize += Padding;
1897 ContentSize += (List.size() + 1) * TupleSize;
1899 // For each compile unit, write the list of spans it covers.
1900 Asm->OutStreamer.AddComment("Length of ARange Set");
1901 Asm->EmitInt32(ContentSize);
1902 Asm->OutStreamer.AddComment("DWARF Arange version number");
1903 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1904 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1905 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1906 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1907 Asm->EmitInt8(PtrSize);
1908 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1911 Asm->OutStreamer.EmitFill(Padding, 0xff);
1913 for (const ArangeSpan &Span : List) {
1914 Asm->EmitLabelReference(Span.Start, PtrSize);
1916 // Calculate the size as being from the span start to it's end.
1918 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1920 // For symbols without an end marker (e.g. common), we
1921 // write a single arange entry containing just that one symbol.
1922 uint64_t Size = SymSize[Span.Start];
1926 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1930 Asm->OutStreamer.AddComment("ARange terminator");
1931 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1932 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1936 // Emit visible names into a debug ranges section.
1937 void DwarfDebug::emitDebugRanges() {
1938 // Start the dwarf ranges section.
1939 Asm->OutStreamer.SwitchSection(
1940 Asm->getObjFileLowering().getDwarfRangesSection());
1942 // Size for our labels.
1943 unsigned char Size = Asm->getDataLayout().getPointerSize();
1945 // Grab the specific ranges for the compile units in the module.
1946 for (const auto &I : CUMap) {
1947 DwarfCompileUnit *TheCU = I.second;
1949 if (auto *Skel = TheCU->getSkeleton())
1952 // Iterate over the misc ranges for the compile units in the module.
1953 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1954 // Emit our symbol so we can find the beginning of the range.
1955 Asm->OutStreamer.EmitLabel(List.getSym());
1957 for (const RangeSpan &Range : List.getRanges()) {
1958 const MCSymbol *Begin = Range.getStart();
1959 const MCSymbol *End = Range.getEnd();
1960 assert(Begin && "Range without a begin symbol?");
1961 assert(End && "Range without an end symbol?");
1962 if (auto *Base = TheCU->getBaseAddress()) {
1963 Asm->EmitLabelDifference(Begin, Base, Size);
1964 Asm->EmitLabelDifference(End, Base, Size);
1966 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1967 Asm->OutStreamer.EmitSymbolValue(End, Size);
1971 // And terminate the list with two 0 values.
1972 Asm->OutStreamer.EmitIntValue(0, Size);
1973 Asm->OutStreamer.EmitIntValue(0, Size);
1978 // DWARF5 Experimental Separate Dwarf emitters.
1980 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1981 std::unique_ptr<DwarfUnit> NewU) {
1982 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1983 U.getCUNode().getSplitDebugFilename());
1985 if (!CompilationDir.empty())
1986 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1988 addGnuPubAttributes(*NewU, Die);
1990 SkeletonHolder.addUnit(std::move(NewU));
1993 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1994 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1995 // DW_AT_addr_base, DW_AT_ranges_base.
1996 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1998 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1999 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2000 DwarfCompileUnit &NewCU = *OwnedUnit;
2001 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2002 DwarfInfoSectionSym);
2004 NewCU.initStmtList(DwarfLineSectionSym);
2006 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2011 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2012 // compile units that would normally be in debug_info.
2013 void DwarfDebug::emitDebugInfoDWO() {
2014 assert(useSplitDwarf() && "No split dwarf debug info?");
2015 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2016 // emit relocations into the dwo file.
2017 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2020 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2021 // abbreviations for the .debug_info.dwo section.
2022 void DwarfDebug::emitDebugAbbrevDWO() {
2023 assert(useSplitDwarf() && "No split dwarf?");
2024 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2027 void DwarfDebug::emitDebugLineDWO() {
2028 assert(useSplitDwarf() && "No split dwarf?");
2029 Asm->OutStreamer.SwitchSection(
2030 Asm->getObjFileLowering().getDwarfLineDWOSection());
2031 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2034 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2035 // string section and is identical in format to traditional .debug_str
2037 void DwarfDebug::emitDebugStrDWO() {
2038 assert(useSplitDwarf() && "No split dwarf?");
2039 const MCSection *OffSec =
2040 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2041 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2045 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2046 if (!useSplitDwarf())
2049 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2050 return &SplitTypeUnitFileTable;
2053 static uint64_t makeTypeSignature(StringRef Identifier) {
2055 Hash.update(Identifier);
2056 // ... take the least significant 8 bytes and return those. Our MD5
2057 // implementation always returns its results in little endian, swap bytes
2059 MD5::MD5Result Result;
2061 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2064 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2065 StringRef Identifier, DIE &RefDie,
2066 DICompositeType CTy) {
2067 // Fast path if we're building some type units and one has already used the
2068 // address pool we know we're going to throw away all this work anyway, so
2069 // don't bother building dependent types.
2070 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2073 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2075 CU.addDIETypeSignature(RefDie, *TU);
2079 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2080 AddrPool.resetUsedFlag();
2082 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2083 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2084 this, &InfoHolder, getDwoLineTable(CU));
2085 DwarfTypeUnit &NewTU = *OwnedUnit;
2086 DIE &UnitDie = NewTU.getUnitDie();
2088 TypeUnitsUnderConstruction.push_back(
2089 std::make_pair(std::move(OwnedUnit), CTy));
2091 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2094 uint64_t Signature = makeTypeSignature(Identifier);
2095 NewTU.setTypeSignature(Signature);
2097 if (useSplitDwarf())
2098 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2100 CU.applyStmtList(UnitDie);
2102 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2105 NewTU.setType(NewTU.createTypeDIE(CTy));
2108 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2109 TypeUnitsUnderConstruction.clear();
2111 // Types referencing entries in the address table cannot be placed in type
2113 if (AddrPool.hasBeenUsed()) {
2115 // Remove all the types built while building this type.
2116 // This is pessimistic as some of these types might not be dependent on
2117 // the type that used an address.
2118 for (const auto &TU : TypeUnitsToAdd)
2119 DwarfTypeUnits.erase(TU.second);
2121 // Construct this type in the CU directly.
2122 // This is inefficient because all the dependent types will be rebuilt
2123 // from scratch, including building them in type units, discovering that
2124 // they depend on addresses, throwing them out and rebuilding them.
2125 CU.constructTypeDIE(RefDie, CTy);
2129 // If the type wasn't dependent on fission addresses, finish adding the type
2130 // and all its dependent types.
2131 for (auto &TU : TypeUnitsToAdd)
2132 InfoHolder.addUnit(std::move(TU.first));
2134 CU.addDIETypeSignature(RefDie, NewTU);
2137 // Accelerator table mutators - add each name along with its companion
2138 // DIE to the proper table while ensuring that the name that we're going
2139 // to reference is in the string table. We do this since the names we
2140 // add may not only be identical to the names in the DIE.
2141 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2142 if (!useDwarfAccelTables())
2144 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2148 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2149 if (!useDwarfAccelTables())
2151 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2155 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2156 if (!useDwarfAccelTables())
2158 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2162 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2163 if (!useDwarfAccelTables())
2165 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),