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 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
110 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
111 : dwarf::OperationEncodingString(Op));
114 void DebugLocDwarfExpression::EmitSigned(int Value) {
115 BS.EmitSLEB128(Value, Twine(Value));
118 void DebugLocDwarfExpression::EmitUnsigned(unsigned Value) {
119 BS.EmitULEB128(Value, Twine(Value));
122 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
123 // This information is not available while emitting .debug_loc entries.
127 //===----------------------------------------------------------------------===//
129 /// resolve - Look in the DwarfDebug map for the MDNode that
130 /// corresponds to the reference.
131 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
132 return DD->resolve(Ref);
135 bool DbgVariable::isBlockByrefVariable() const {
136 assert(Var.isVariable() && "Invalid complex DbgVariable!");
137 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
140 DIType DbgVariable::getType() const {
141 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
142 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
143 // addresses instead.
144 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
145 /* Byref variables, in Blocks, are declared by the programmer as
146 "SomeType VarName;", but the compiler creates a
147 __Block_byref_x_VarName struct, and gives the variable VarName
148 either the struct, or a pointer to the struct, as its type. This
149 is necessary for various behind-the-scenes things the compiler
150 needs to do with by-reference variables in blocks.
152 However, as far as the original *programmer* is concerned, the
153 variable should still have type 'SomeType', as originally declared.
155 The following function dives into the __Block_byref_x_VarName
156 struct to find the original type of the variable. This will be
157 passed back to the code generating the type for the Debug
158 Information Entry for the variable 'VarName'. 'VarName' will then
159 have the original type 'SomeType' in its debug information.
161 The original type 'SomeType' will be the type of the field named
162 'VarName' inside the __Block_byref_x_VarName struct.
164 NOTE: In order for this to not completely fail on the debugger
165 side, the Debug Information Entry for the variable VarName needs to
166 have a DW_AT_location that tells the debugger how to unwind through
167 the pointers and __Block_byref_x_VarName struct to find the actual
168 value of the variable. The function addBlockByrefType does this. */
170 uint16_t tag = Ty.getTag();
172 if (tag == dwarf::DW_TAG_pointer_type)
173 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
175 DIArray Elements = DICompositeType(subType).getElements();
176 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
177 DIDerivedType DT(Elements.getElement(i));
178 if (getName() == DT.getName())
179 return (resolve(DT.getTypeDerivedFrom()));
185 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
186 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
187 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
188 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
190 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
191 : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
192 InfoHolder(A, *this, "info_string", DIEValueAllocator),
193 UsedNonDefaultText(false),
194 SkeletonHolder(A, *this, "skel_string", DIEValueAllocator),
195 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
196 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
197 dwarf::DW_FORM_data4)),
198 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
199 dwarf::DW_FORM_data4)),
200 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
201 dwarf::DW_FORM_data4)),
202 AccelTypes(TypeAtoms) {
204 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
205 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
206 DwarfLineSectionSym = nullptr;
207 DwarfAddrSectionSym = nullptr;
208 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
209 FunctionBeginSym = FunctionEndSym = nullptr;
213 // Turn on accelerator tables for Darwin by default, pubnames by
214 // default for non-Darwin, and handle split dwarf.
215 if (DwarfAccelTables == Default)
216 HasDwarfAccelTables = IsDarwin;
218 HasDwarfAccelTables = DwarfAccelTables == Enable;
220 if (SplitDwarf == Default)
221 HasSplitDwarf = false;
223 HasSplitDwarf = SplitDwarf == Enable;
225 if (DwarfPubSections == Default)
226 HasDwarfPubSections = !IsDarwin;
228 HasDwarfPubSections = DwarfPubSections == Enable;
230 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
231 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
232 : MMI->getModule()->getDwarfVersion();
234 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
237 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
242 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
243 DwarfDebug::~DwarfDebug() { }
245 // Switch to the specified MCSection and emit an assembler
246 // temporary label to it if SymbolStem is specified.
247 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
248 const char *SymbolStem = nullptr) {
249 Asm->OutStreamer.SwitchSection(Section);
253 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
254 Asm->OutStreamer.EmitLabel(TmpSym);
258 static bool isObjCClass(StringRef Name) {
259 return Name.startswith("+") || Name.startswith("-");
262 static bool hasObjCCategory(StringRef Name) {
263 if (!isObjCClass(Name))
266 return Name.find(") ") != StringRef::npos;
269 static void getObjCClassCategory(StringRef In, StringRef &Class,
270 StringRef &Category) {
271 if (!hasObjCCategory(In)) {
272 Class = In.slice(In.find('[') + 1, In.find(' '));
277 Class = In.slice(In.find('[') + 1, In.find('('));
278 Category = In.slice(In.find('[') + 1, In.find(' '));
282 static StringRef getObjCMethodName(StringRef In) {
283 return In.slice(In.find(' ') + 1, In.find(']'));
286 // Helper for sorting sections into a stable output order.
287 static bool SectionSort(const MCSection *A, const MCSection *B) {
288 std::string LA = (A ? A->getLabelBeginName() : "");
289 std::string LB = (B ? B->getLabelBeginName() : "");
293 // Add the various names to the Dwarf accelerator table names.
294 // TODO: Determine whether or not we should add names for programs
295 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
296 // is only slightly different than the lookup of non-standard ObjC names.
297 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
298 if (!SP.isDefinition())
300 addAccelName(SP.getName(), Die);
302 // If the linkage name is different than the name, go ahead and output
303 // that as well into the name table.
304 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
305 addAccelName(SP.getLinkageName(), Die);
307 // If this is an Objective-C selector name add it to the ObjC accelerator
309 if (isObjCClass(SP.getName())) {
310 StringRef Class, Category;
311 getObjCClassCategory(SP.getName(), Class, Category);
312 addAccelObjC(Class, Die);
314 addAccelObjC(Category, Die);
315 // Also add the base method name to the name table.
316 addAccelName(getObjCMethodName(SP.getName()), Die);
320 /// isSubprogramContext - Return true if Context is either a subprogram
321 /// or another context nested inside a subprogram.
322 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
325 DIDescriptor D(Context);
326 if (D.isSubprogram())
329 return isSubprogramContext(resolve(DIType(Context).getContext()));
333 /// Check whether we should create a DIE for the given Scope, return true
334 /// if we don't create a DIE (the corresponding DIE is null).
335 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
336 if (Scope->isAbstractScope())
339 // We don't create a DIE if there is no Range.
340 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
344 if (Ranges.size() > 1)
347 // We don't create a DIE if we have a single Range and the end label
349 return !getLabelAfterInsn(Ranges.front().second);
352 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
354 if (auto *SkelCU = CU.getSkeleton())
358 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
359 assert(Scope && Scope->getScopeNode());
360 assert(Scope->isAbstractScope());
361 assert(!Scope->getInlinedAt());
363 const MDNode *SP = Scope->getScopeNode();
365 ProcessedSPNodes.insert(SP);
367 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
368 // was inlined from another compile unit.
369 auto &CU = SPMap[SP];
370 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
371 CU.constructAbstractSubprogramScopeDIE(Scope);
375 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
376 if (!GenerateGnuPubSections)
379 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
382 // Create new DwarfCompileUnit for the given metadata node with tag
383 // DW_TAG_compile_unit.
384 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
385 StringRef FN = DIUnit.getFilename();
386 CompilationDir = DIUnit.getDirectory();
388 auto OwnedUnit = make_unique<DwarfCompileUnit>(
389 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
390 DwarfCompileUnit &NewCU = *OwnedUnit;
391 DIE &Die = NewCU.getUnitDie();
392 InfoHolder.addUnit(std::move(OwnedUnit));
394 NewCU.setSkeleton(constructSkeletonCU(NewCU));
396 // LTO with assembly output shares a single line table amongst multiple CUs.
397 // To avoid the compilation directory being ambiguous, let the line table
398 // explicitly describe the directory of all files, never relying on the
399 // compilation directory.
400 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
401 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
402 NewCU.getUniqueID(), CompilationDir);
404 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
405 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
406 DIUnit.getLanguage());
407 NewCU.addString(Die, dwarf::DW_AT_name, FN);
409 if (!useSplitDwarf()) {
410 NewCU.initStmtList(DwarfLineSectionSym);
412 // If we're using split dwarf the compilation dir is going to be in the
413 // skeleton CU and so we don't need to duplicate it here.
414 if (!CompilationDir.empty())
415 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
417 addGnuPubAttributes(NewCU, Die);
420 if (DIUnit.isOptimized())
421 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
423 StringRef Flags = DIUnit.getFlags();
425 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
427 if (unsigned RVer = DIUnit.getRunTimeVersion())
428 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
429 dwarf::DW_FORM_data1, RVer);
432 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
433 DwarfInfoDWOSectionSym);
435 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
436 DwarfInfoSectionSym);
438 CUMap.insert(std::make_pair(DIUnit, &NewCU));
439 CUDieMap.insert(std::make_pair(&Die, &NewCU));
443 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
445 DIImportedEntity Module(N);
446 assert(Module.Verify());
447 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
448 D->addChild(TheCU.constructImportedEntityDIE(Module));
451 // Emit all Dwarf sections that should come prior to the content. Create
452 // global DIEs and emit initial debug info sections. This is invoked by
453 // the target AsmPrinter.
454 void DwarfDebug::beginModule() {
455 if (DisableDebugInfoPrinting)
458 const Module *M = MMI->getModule();
460 FunctionDIs = makeSubprogramMap(*M);
462 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
465 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
467 // Emit initial sections so we can reference labels later.
470 SingleCU = CU_Nodes->getNumOperands() == 1;
472 for (MDNode *N : CU_Nodes->operands()) {
473 DICompileUnit CUNode(N);
474 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
475 DIArray ImportedEntities = CUNode.getImportedEntities();
476 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
477 ScopesWithImportedEntities.push_back(std::make_pair(
478 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
479 ImportedEntities.getElement(i)));
480 // Stable sort to preserve the order of appearance of imported entities.
481 // This is to avoid out-of-order processing of interdependent declarations
482 // within the same scope, e.g. { namespace A = base; namespace B = A; }
483 std::stable_sort(ScopesWithImportedEntities.begin(),
484 ScopesWithImportedEntities.end(), less_first());
485 DIArray GVs = CUNode.getGlobalVariables();
486 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
487 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
488 DIArray SPs = CUNode.getSubprograms();
489 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
490 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
491 DIArray EnumTypes = CUNode.getEnumTypes();
492 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
493 DIType Ty(EnumTypes.getElement(i));
494 // The enum types array by design contains pointers to
495 // MDNodes rather than DIRefs. Unique them here.
496 DIType UniqueTy(resolve(Ty.getRef()));
497 CU.getOrCreateTypeDIE(UniqueTy);
499 DIArray RetainedTypes = CUNode.getRetainedTypes();
500 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
501 DIType Ty(RetainedTypes.getElement(i));
502 // The retained types array by design contains pointers to
503 // MDNodes rather than DIRefs. Unique them here.
504 DIType UniqueTy(resolve(Ty.getRef()));
505 CU.getOrCreateTypeDIE(UniqueTy);
507 // Emit imported_modules last so that the relevant context is already
509 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
510 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
513 // Tell MMI that we have debug info.
514 MMI->setDebugInfoAvailability(true);
517 void DwarfDebug::finishVariableDefinitions() {
518 for (const auto &Var : ConcreteVariables) {
519 DIE *VariableDie = Var->getDIE();
521 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
522 // in the ConcreteVariables list, rather than looking it up again here.
523 // DIE::getUnit isn't simple - it walks parent pointers, etc.
524 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
526 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
527 if (AbsVar && AbsVar->getDIE()) {
528 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
531 Unit->applyVariableAttributes(*Var, *VariableDie);
535 void DwarfDebug::finishSubprogramDefinitions() {
536 for (const auto &P : SPMap)
537 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
538 CU.finishSubprogramDefinition(DISubprogram(P.first));
543 // Collect info for variables that were optimized out.
544 void DwarfDebug::collectDeadVariables() {
545 const Module *M = MMI->getModule();
547 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
548 for (MDNode *N : CU_Nodes->operands()) {
549 DICompileUnit TheCU(N);
550 // Construct subprogram DIE and add variables DIEs.
551 DwarfCompileUnit *SPCU =
552 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
553 assert(SPCU && "Unable to find Compile Unit!");
554 DIArray Subprograms = TheCU.getSubprograms();
555 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
556 DISubprogram SP(Subprograms.getElement(i));
557 if (ProcessedSPNodes.count(SP) != 0)
559 SPCU->collectDeadVariables(SP);
565 void DwarfDebug::finalizeModuleInfo() {
566 finishSubprogramDefinitions();
568 finishVariableDefinitions();
570 // Collect info for variables that were optimized out.
571 collectDeadVariables();
573 // Handle anything that needs to be done on a per-unit basis after
574 // all other generation.
575 for (const auto &P : CUMap) {
576 auto &TheCU = *P.second;
577 // Emit DW_AT_containing_type attribute to connect types with their
578 // vtable holding type.
579 TheCU.constructContainingTypeDIEs();
581 // Add CU specific attributes if we need to add any.
582 // If we're splitting the dwarf out now that we've got the entire
583 // CU then add the dwo id to it.
584 auto *SkCU = TheCU.getSkeleton();
585 if (useSplitDwarf()) {
586 // Emit a unique identifier for this CU.
587 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
588 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
589 dwarf::DW_FORM_data8, ID);
590 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
591 dwarf::DW_FORM_data8, ID);
593 // We don't keep track of which addresses are used in which CU so this
594 // is a bit pessimistic under LTO.
595 if (!AddrPool.isEmpty())
596 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
597 DwarfAddrSectionSym, DwarfAddrSectionSym);
598 if (!SkCU->getRangeLists().empty())
599 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
600 DwarfDebugRangeSectionSym,
601 DwarfDebugRangeSectionSym);
604 // If we have code split among multiple sections or non-contiguous
605 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
606 // remain in the .o file, otherwise add a DW_AT_low_pc.
607 // FIXME: We should use ranges allow reordering of code ala
608 // .subsections_via_symbols in mach-o. This would mean turning on
609 // ranges for all subprogram DIEs for mach-o.
610 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
611 if (unsigned NumRanges = TheCU.getRanges().size()) {
613 // A DW_AT_low_pc attribute may also be specified in combination with
614 // DW_AT_ranges to specify the default base address for use in
615 // location lists (see Section 2.6.2) and range lists (see Section
617 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
619 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
620 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
624 // Compute DIE offsets and sizes.
625 InfoHolder.computeSizeAndOffsets();
627 SkeletonHolder.computeSizeAndOffsets();
630 // Emit all Dwarf sections that should come after the content.
631 void DwarfDebug::endModule() {
632 assert(CurFn == nullptr);
633 assert(CurMI == nullptr);
635 // If we aren't actually generating debug info (check beginModule -
636 // conditionalized on !DisableDebugInfoPrinting and the presence of the
637 // llvm.dbg.cu metadata node)
638 if (!DwarfInfoSectionSym)
641 // Finalize the debug info for the module.
642 finalizeModuleInfo();
646 // Emit all the DIEs into a debug info section.
649 // Corresponding abbreviations into a abbrev section.
652 // Emit info into a debug aranges section.
653 if (GenerateARangeSection)
656 // Emit info into a debug ranges section.
659 if (useSplitDwarf()) {
662 emitDebugAbbrevDWO();
665 // Emit DWO addresses.
666 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
668 // Emit info into a debug loc section.
671 // Emit info into the dwarf accelerator table sections.
672 if (useDwarfAccelTables()) {
675 emitAccelNamespaces();
679 // Emit the pubnames and pubtypes sections if requested.
680 if (HasDwarfPubSections) {
681 emitDebugPubNames(GenerateGnuPubSections);
682 emitDebugPubTypes(GenerateGnuPubSections);
687 AbstractVariables.clear();
690 // Find abstract variable, if any, associated with Var.
691 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
692 DIVariable &Cleansed) {
693 LLVMContext &Ctx = DV->getContext();
694 // More then one inlined variable corresponds to one abstract variable.
695 // FIXME: This duplication of variables when inlining should probably be
696 // removed. It's done to allow each DIVariable to describe its location
697 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
698 // make it accurate then remove this duplication/cleansing stuff.
699 Cleansed = cleanseInlinedVariable(DV, Ctx);
700 auto I = AbstractVariables.find(Cleansed);
701 if (I != AbstractVariables.end())
702 return I->second.get();
706 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
708 return getExistingAbstractVariable(DV, Cleansed);
711 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
712 LexicalScope *Scope) {
713 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
714 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
715 AbstractVariables[Var] = std::move(AbsDbgVariable);
718 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
719 const MDNode *ScopeNode) {
720 DIVariable Cleansed = DV;
721 if (getExistingAbstractVariable(DV, Cleansed))
724 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
728 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
729 const MDNode *ScopeNode) {
730 DIVariable Cleansed = DV;
731 if (getExistingAbstractVariable(DV, Cleansed))
734 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
735 createAbstractVariable(Cleansed, Scope);
738 // Collect variable information from side table maintained by MMI.
739 void DwarfDebug::collectVariableInfoFromMMITable(
740 SmallPtrSetImpl<const MDNode *> &Processed) {
741 for (const auto &VI : MMI->getVariableDbgInfo()) {
744 Processed.insert(VI.Var);
745 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
747 // If variable scope is not found then skip this variable.
751 DIVariable DV(VI.Var);
752 DIExpression Expr(VI.Expr);
753 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
754 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
755 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
756 ConcreteVariables.push_back(std::move(RegVar));
760 // Get .debug_loc entry for the instruction range starting at MI.
761 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
762 const MDNode *Expr = MI->getDebugExpression();
763 const MDNode *Var = MI->getDebugVariable();
765 assert(MI->getNumOperands() == 4);
766 if (MI->getOperand(0).isReg()) {
767 MachineLocation MLoc;
768 // If the second operand is an immediate, this is a
769 // register-indirect address.
770 if (!MI->getOperand(1).isImm())
771 MLoc.set(MI->getOperand(0).getReg());
773 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
774 return DebugLocEntry::Value(Var, Expr, MLoc);
776 if (MI->getOperand(0).isImm())
777 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
778 if (MI->getOperand(0).isFPImm())
779 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
780 if (MI->getOperand(0).isCImm())
781 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
783 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
786 /// Determine whether two variable pieces overlap.
787 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
788 if (!P1.isBitPiece() || !P2.isBitPiece())
790 unsigned l1 = P1.getBitPieceOffset();
791 unsigned l2 = P2.getBitPieceOffset();
792 unsigned r1 = l1 + P1.getBitPieceSize();
793 unsigned r2 = l2 + P2.getBitPieceSize();
794 // True where [l1,r1[ and [r1,r2[ overlap.
795 return (l1 < r2) && (l2 < r1);
798 /// Build the location list for all DBG_VALUEs in the function that
799 /// describe the same variable. If the ranges of several independent
800 /// pieces of the same variable overlap partially, split them up and
801 /// combine the ranges. The resulting DebugLocEntries are will have
802 /// strict monotonically increasing begin addresses and will never
807 // Ranges History [var, loc, piece ofs size]
808 // 0 | [x, (reg0, piece 0, 32)]
809 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
811 // 3 | [clobber reg0]
812 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
817 // [0-1] [x, (reg0, piece 0, 32)]
818 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
819 // [3-4] [x, (reg1, piece 32, 32)]
820 // [4- ] [x, (mem, piece 0, 64)]
822 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
823 const DbgValueHistoryMap::InstrRanges &Ranges) {
824 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
826 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
827 const MachineInstr *Begin = I->first;
828 const MachineInstr *End = I->second;
829 assert(Begin->isDebugValue() && "Invalid History entry");
831 // Check if a variable is inaccessible in this range.
832 if (Begin->getNumOperands() > 1 &&
833 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
838 // If this piece overlaps with any open ranges, truncate them.
839 DIExpression DIExpr = Begin->getDebugExpression();
840 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
841 [&](DebugLocEntry::Value R) {
842 return piecesOverlap(DIExpr, R.getExpression());
844 OpenRanges.erase(Last, OpenRanges.end());
846 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
847 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
849 const MCSymbol *EndLabel;
851 EndLabel = getLabelAfterInsn(End);
852 else if (std::next(I) == Ranges.end())
853 EndLabel = FunctionEndSym;
855 EndLabel = getLabelBeforeInsn(std::next(I)->first);
856 assert(EndLabel && "Forgot label after instruction ending a range!");
858 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
860 auto Value = getDebugLocValue(Begin);
861 DebugLocEntry Loc(StartLabel, EndLabel, Value);
862 bool couldMerge = false;
864 // If this is a piece, it may belong to the current DebugLocEntry.
865 if (DIExpr.isBitPiece()) {
866 // Add this value to the list of open ranges.
867 OpenRanges.push_back(Value);
869 // Attempt to add the piece to the last entry.
870 if (!DebugLoc.empty())
871 if (DebugLoc.back().MergeValues(Loc))
876 // Need to add a new DebugLocEntry. Add all values from still
877 // valid non-overlapping pieces.
878 if (OpenRanges.size())
879 Loc.addValues(OpenRanges);
881 DebugLoc.push_back(std::move(Loc));
884 // Attempt to coalesce the ranges of two otherwise identical
886 auto CurEntry = DebugLoc.rbegin();
887 auto PrevEntry = std::next(CurEntry);
888 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
892 dbgs() << CurEntry->getValues().size() << " Values:\n";
893 for (auto Value : CurEntry->getValues()) {
894 Value.getVariable()->dump();
895 Value.getExpression()->dump();
903 // Find variables for each lexical scope.
905 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
906 SmallPtrSetImpl<const MDNode *> &Processed) {
907 // Grab the variable info that was squirreled away in the MMI side-table.
908 collectVariableInfoFromMMITable(Processed);
910 for (const auto &I : DbgValues) {
911 DIVariable DV(I.first);
912 if (Processed.count(DV))
915 // Instruction ranges, specifying where DV is accessible.
916 const auto &Ranges = I.second;
920 LexicalScope *Scope = nullptr;
921 if (MDNode *IA = DV.getInlinedAt())
922 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
924 Scope = LScopes.findLexicalScope(DV.getContext());
925 // If variable scope is not found then skip this variable.
929 Processed.insert(DV);
930 const MachineInstr *MInsn = Ranges.front().first;
931 assert(MInsn->isDebugValue() && "History must begin with debug value");
932 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
933 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
934 DbgVariable *RegVar = ConcreteVariables.back().get();
935 InfoHolder.addScopeVariable(Scope, RegVar);
937 // Check if the first DBG_VALUE is valid for the rest of the function.
938 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
941 // Handle multiple DBG_VALUE instructions describing one variable.
942 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
944 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
945 DebugLocList &LocList = DotDebugLocEntries.back();
948 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
950 // Build the location list for this variable.
951 buildLocationList(LocList.List, Ranges);
952 // Finalize the entry by lowering it into a DWARF bytestream.
953 for (auto &Entry : LocList.List)
954 Entry.finalize(*Asm, TypeIdentifierMap);
957 // Collect info for variables that were optimized out.
958 DIArray Variables = SP.getVariables();
959 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
960 DIVariable DV(Variables.getElement(i));
961 assert(DV.isVariable());
962 if (!Processed.insert(DV).second)
964 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
965 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
967 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
968 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
973 // Return Label preceding the instruction.
974 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
975 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
976 assert(Label && "Didn't insert label before instruction");
980 // Return Label immediately following the instruction.
981 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
982 return LabelsAfterInsn.lookup(MI);
985 // Process beginning of an instruction.
986 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
987 assert(CurMI == nullptr);
989 // Check if source location changes, but ignore DBG_VALUE locations.
990 if (!MI->isDebugValue()) {
991 DebugLoc DL = MI->getDebugLoc();
992 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
995 if (DL == PrologEndLoc) {
996 Flags |= DWARF2_FLAG_PROLOGUE_END;
997 PrologEndLoc = DebugLoc();
998 Flags |= DWARF2_FLAG_IS_STMT;
1001 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
1002 Flags |= DWARF2_FLAG_IS_STMT;
1004 if (!DL.isUnknown()) {
1005 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1006 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1008 recordSourceLine(0, 0, nullptr, 0);
1012 // Insert labels where requested.
1013 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1014 LabelsBeforeInsn.find(MI);
1017 if (I == LabelsBeforeInsn.end())
1020 // Label already assigned.
1025 PrevLabel = MMI->getContext().CreateTempSymbol();
1026 Asm->OutStreamer.EmitLabel(PrevLabel);
1028 I->second = PrevLabel;
1031 // Process end of an instruction.
1032 void DwarfDebug::endInstruction() {
1033 assert(CurMI != nullptr);
1034 // Don't create a new label after DBG_VALUE instructions.
1035 // They don't generate code.
1036 if (!CurMI->isDebugValue())
1037 PrevLabel = nullptr;
1039 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1040 LabelsAfterInsn.find(CurMI);
1044 if (I == LabelsAfterInsn.end())
1047 // Label already assigned.
1051 // We need a label after this instruction.
1053 PrevLabel = MMI->getContext().CreateTempSymbol();
1054 Asm->OutStreamer.EmitLabel(PrevLabel);
1056 I->second = PrevLabel;
1059 // Each LexicalScope has first instruction and last instruction to mark
1060 // beginning and end of a scope respectively. Create an inverse map that list
1061 // scopes starts (and ends) with an instruction. One instruction may start (or
1062 // end) multiple scopes. Ignore scopes that are not reachable.
1063 void DwarfDebug::identifyScopeMarkers() {
1064 SmallVector<LexicalScope *, 4> WorkList;
1065 WorkList.push_back(LScopes.getCurrentFunctionScope());
1066 while (!WorkList.empty()) {
1067 LexicalScope *S = WorkList.pop_back_val();
1069 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1070 if (!Children.empty())
1071 WorkList.append(Children.begin(), Children.end());
1073 if (S->isAbstractScope())
1076 for (const InsnRange &R : S->getRanges()) {
1077 assert(R.first && "InsnRange does not have first instruction!");
1078 assert(R.second && "InsnRange does not have second instruction!");
1079 requestLabelBeforeInsn(R.first);
1080 requestLabelAfterInsn(R.second);
1085 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1086 // First known non-DBG_VALUE and non-frame setup location marks
1087 // the beginning of the function body.
1088 for (const auto &MBB : *MF)
1089 for (const auto &MI : MBB)
1090 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1091 !MI.getDebugLoc().isUnknown()) {
1092 // Did the target forget to set the FrameSetup flag for CFI insns?
1093 assert(!MI.isCFIInstruction() &&
1094 "First non-frame-setup instruction is a CFI instruction.");
1095 return MI.getDebugLoc();
1100 // Gather pre-function debug information. Assumes being called immediately
1101 // after the function entry point has been emitted.
1102 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1105 // If there's no debug info for the function we're not going to do anything.
1106 if (!MMI->hasDebugInfo())
1109 auto DI = FunctionDIs.find(MF->getFunction());
1110 if (DI == FunctionDIs.end())
1113 // Grab the lexical scopes for the function, if we don't have any of those
1114 // then we're not going to be able to do anything.
1115 LScopes.initialize(*MF);
1116 if (LScopes.empty())
1119 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1121 // Make sure that each lexical scope will have a begin/end label.
1122 identifyScopeMarkers();
1124 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1125 // belongs to so that we add to the correct per-cu line table in the
1127 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1128 // FnScope->getScopeNode() and DI->second should represent the same function,
1129 // though they may not be the same MDNode due to inline functions merged in
1130 // LTO where the debug info metadata still differs (either due to distinct
1131 // written differences - two versions of a linkonce_odr function
1132 // written/copied into two separate files, or some sub-optimal metadata that
1133 // isn't structurally identical (see: file path/name info from clang, which
1134 // includes the directory of the cpp file being built, even when the file name
1135 // is absolute (such as an <> lookup header)))
1136 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1137 assert(TheCU && "Unable to find compile unit!");
1138 if (Asm->OutStreamer.hasRawTextSupport())
1139 // Use a single line table if we are generating assembly.
1140 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1142 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1144 // Emit a label for the function so that we have a beginning address.
1145 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1146 // Assumes in correct section after the entry point.
1147 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1149 // Calculate history for local variables.
1150 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1153 // Request labels for the full history.
1154 for (const auto &I : DbgValues) {
1155 const auto &Ranges = I.second;
1159 // The first mention of a function argument gets the FunctionBeginSym
1160 // label, so arguments are visible when breaking at function entry.
1161 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1162 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1163 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1164 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1165 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1166 // Mark all non-overlapping initial pieces.
1167 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1168 DIExpression Piece = I->first->getDebugExpression();
1169 if (std::all_of(Ranges.begin(), I,
1170 [&](DbgValueHistoryMap::InstrRange Pred) {
1171 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1173 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1180 for (const auto &Range : Ranges) {
1181 requestLabelBeforeInsn(Range.first);
1183 requestLabelAfterInsn(Range.second);
1187 PrevInstLoc = DebugLoc();
1188 PrevLabel = FunctionBeginSym;
1190 // Record beginning of function.
1191 PrologEndLoc = findPrologueEndLoc(MF);
1192 if (!PrologEndLoc.isUnknown()) {
1193 DebugLoc FnStartDL =
1194 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1196 // We'd like to list the prologue as "not statements" but GDB behaves
1197 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1198 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1199 FnStartDL.getScope(MF->getFunction()->getContext()),
1200 DWARF2_FLAG_IS_STMT);
1204 // Gather and emit post-function debug information.
1205 void DwarfDebug::endFunction(const MachineFunction *MF) {
1206 assert(CurFn == MF &&
1207 "endFunction should be called with the same function as beginFunction");
1209 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1210 !FunctionDIs.count(MF->getFunction())) {
1211 // If we don't have a lexical scope for this function then there will
1212 // be a hole in the range information. Keep note of this by setting the
1213 // previously used section to nullptr.
1219 // Define end label for subprogram.
1220 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1221 // Assumes in correct section after the entry point.
1222 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1224 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1225 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1227 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1228 DISubprogram SP(FnScope->getScopeNode());
1229 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1231 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1232 collectVariableInfo(TheCU, SP, ProcessedVars);
1234 // Add the range of this function to the list of ranges for the CU.
1235 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1237 // Under -gmlt, skip building the subprogram if there are no inlined
1238 // subroutines inside it.
1239 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1240 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1241 assert(InfoHolder.getScopeVariables().empty());
1242 assert(DbgValues.empty());
1243 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1244 // by a -gmlt CU. Add a test and remove this assertion.
1245 assert(AbstractVariables.empty());
1246 LabelsBeforeInsn.clear();
1247 LabelsAfterInsn.clear();
1248 PrevLabel = nullptr;
1254 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1256 // Construct abstract scopes.
1257 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1258 DISubprogram SP(AScope->getScopeNode());
1259 assert(SP.isSubprogram());
1260 // Collect info for variables that were optimized out.
1261 DIArray Variables = SP.getVariables();
1262 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1263 DIVariable DV(Variables.getElement(i));
1264 assert(DV && DV.isVariable());
1265 if (!ProcessedVars.insert(DV).second)
1267 ensureAbstractVariableIsCreated(DV, DV.getContext());
1268 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1269 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1271 constructAbstractSubprogramScopeDIE(AScope);
1274 TheCU.constructSubprogramScopeDIE(FnScope);
1275 if (auto *SkelCU = TheCU.getSkeleton())
1276 if (!LScopes.getAbstractScopesList().empty())
1277 SkelCU->constructSubprogramScopeDIE(FnScope);
1280 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1281 // DbgVariables except those that are also in AbstractVariables (since they
1282 // can be used cross-function)
1283 InfoHolder.getScopeVariables().clear();
1285 LabelsBeforeInsn.clear();
1286 LabelsAfterInsn.clear();
1287 PrevLabel = nullptr;
1291 // Register a source line with debug info. Returns the unique label that was
1292 // emitted and which provides correspondence to the source line list.
1293 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1298 unsigned Discriminator = 0;
1299 if (DIScope Scope = DIScope(S)) {
1300 assert(Scope.isScope());
1301 Fn = Scope.getFilename();
1302 Dir = Scope.getDirectory();
1303 if (Scope.isLexicalBlockFile())
1304 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1306 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1307 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1308 .getOrCreateSourceID(Fn, Dir);
1310 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1314 //===----------------------------------------------------------------------===//
1316 //===----------------------------------------------------------------------===//
1318 // Emit initial Dwarf sections with a label at the start of each one.
1319 void DwarfDebug::emitSectionLabels() {
1320 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1322 // Dwarf sections base addresses.
1323 DwarfInfoSectionSym =
1324 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1325 if (useSplitDwarf()) {
1326 DwarfInfoDWOSectionSym =
1327 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1328 DwarfTypesDWOSectionSym = emitSectionSym(
1329 Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1331 DwarfAbbrevSectionSym =
1332 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1333 if (useSplitDwarf())
1334 DwarfAbbrevDWOSectionSym = emitSectionSym(
1335 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1336 if (GenerateARangeSection)
1337 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1339 DwarfLineSectionSym =
1340 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1341 if (GenerateGnuPubSections) {
1342 DwarfGnuPubNamesSectionSym =
1343 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1344 DwarfGnuPubTypesSectionSym =
1345 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1346 } else if (HasDwarfPubSections) {
1347 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1348 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1351 DwarfStrSectionSym =
1352 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1353 if (useSplitDwarf()) {
1354 DwarfStrDWOSectionSym =
1355 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1356 DwarfAddrSectionSym =
1357 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1358 DwarfDebugLocSectionSym =
1359 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1361 DwarfDebugLocSectionSym =
1362 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1363 DwarfDebugRangeSectionSym =
1364 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1367 // Recursively emits a debug information entry.
1368 void DwarfDebug::emitDIE(DIE &Die) {
1369 // Get the abbreviation for this DIE.
1370 const DIEAbbrev &Abbrev = Die.getAbbrev();
1372 // Emit the code (index) for the abbreviation.
1373 if (Asm->isVerbose())
1374 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1375 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1376 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1377 dwarf::TagString(Abbrev.getTag()));
1378 Asm->EmitULEB128(Abbrev.getNumber());
1380 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1381 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1383 // Emit the DIE attribute values.
1384 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1385 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1386 dwarf::Form Form = AbbrevData[i].getForm();
1387 assert(Form && "Too many attributes for DIE (check abbreviation)");
1389 if (Asm->isVerbose()) {
1390 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1391 if (Attr == dwarf::DW_AT_accessibility)
1392 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1393 cast<DIEInteger>(Values[i])->getValue()));
1396 // Emit an attribute using the defined form.
1397 Values[i]->EmitValue(Asm, Form);
1400 // Emit the DIE children if any.
1401 if (Abbrev.hasChildren()) {
1402 for (auto &Child : Die.getChildren())
1405 Asm->OutStreamer.AddComment("End Of Children Mark");
1410 // Emit the debug info section.
1411 void DwarfDebug::emitDebugInfo() {
1412 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1414 Holder.emitUnits(DwarfAbbrevSectionSym);
1417 // Emit the abbreviation section.
1418 void DwarfDebug::emitAbbreviations() {
1419 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1421 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1424 // Emit the last address of the section and the end of the line matrix.
1425 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1426 // Define last address of section.
1427 Asm->OutStreamer.AddComment("Extended Op");
1430 Asm->OutStreamer.AddComment("Op size");
1431 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1432 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1433 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1435 Asm->OutStreamer.AddComment("Section end label");
1437 Asm->OutStreamer.EmitSymbolValue(
1438 Asm->GetTempSymbol("section_end", SectionEnd),
1439 Asm->getDataLayout().getPointerSize());
1441 // Mark end of matrix.
1442 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1448 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1449 StringRef TableName, StringRef SymName) {
1450 Accel.FinalizeTable(Asm, TableName);
1451 Asm->OutStreamer.SwitchSection(Section);
1452 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1453 Asm->OutStreamer.EmitLabel(SectionBegin);
1455 // Emit the full data.
1456 Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1459 // Emit visible names into a hashed accelerator table section.
1460 void DwarfDebug::emitAccelNames() {
1461 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1462 "Names", "names_begin");
1465 // Emit objective C classes and categories into a hashed accelerator table
1467 void DwarfDebug::emitAccelObjC() {
1468 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1469 "ObjC", "objc_begin");
1472 // Emit namespace dies into a hashed accelerator table.
1473 void DwarfDebug::emitAccelNamespaces() {
1474 emitAccel(AccelNamespace,
1475 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1476 "namespac", "namespac_begin");
1479 // Emit type dies into a hashed accelerator table.
1480 void DwarfDebug::emitAccelTypes() {
1481 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1482 "types", "types_begin");
1485 // Public name handling.
1486 // The format for the various pubnames:
1488 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1489 // for the DIE that is named.
1491 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1492 // into the CU and the index value is computed according to the type of value
1493 // for the DIE that is named.
1495 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1496 // it's the offset within the debug_info/debug_types dwo section, however, the
1497 // reference in the pubname header doesn't change.
1499 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1500 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1502 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1504 // We could have a specification DIE that has our most of our knowledge,
1505 // look for that now.
1506 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1508 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1509 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1510 Linkage = dwarf::GIEL_EXTERNAL;
1511 } else if (Die->findAttribute(dwarf::DW_AT_external))
1512 Linkage = dwarf::GIEL_EXTERNAL;
1514 switch (Die->getTag()) {
1515 case dwarf::DW_TAG_class_type:
1516 case dwarf::DW_TAG_structure_type:
1517 case dwarf::DW_TAG_union_type:
1518 case dwarf::DW_TAG_enumeration_type:
1519 return dwarf::PubIndexEntryDescriptor(
1520 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1521 ? dwarf::GIEL_STATIC
1522 : dwarf::GIEL_EXTERNAL);
1523 case dwarf::DW_TAG_typedef:
1524 case dwarf::DW_TAG_base_type:
1525 case dwarf::DW_TAG_subrange_type:
1526 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1527 case dwarf::DW_TAG_namespace:
1528 return dwarf::GIEK_TYPE;
1529 case dwarf::DW_TAG_subprogram:
1530 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1531 case dwarf::DW_TAG_variable:
1532 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1533 case dwarf::DW_TAG_enumerator:
1534 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1535 dwarf::GIEL_STATIC);
1537 return dwarf::GIEK_NONE;
1541 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1543 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1544 const MCSection *PSec =
1545 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1546 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1548 emitDebugPubSection(GnuStyle, PSec, "Names",
1549 &DwarfCompileUnit::getGlobalNames);
1552 void DwarfDebug::emitDebugPubSection(
1553 bool GnuStyle, const MCSection *PSec, StringRef Name,
1554 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1555 for (const auto &NU : CUMap) {
1556 DwarfCompileUnit *TheU = NU.second;
1558 const auto &Globals = (TheU->*Accessor)();
1560 if (Globals.empty())
1563 if (auto *Skeleton = TheU->getSkeleton())
1565 unsigned ID = TheU->getUniqueID();
1567 // Start the dwarf pubnames section.
1568 Asm->OutStreamer.SwitchSection(PSec);
1571 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1572 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1573 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1574 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1576 Asm->OutStreamer.EmitLabel(BeginLabel);
1578 Asm->OutStreamer.AddComment("DWARF Version");
1579 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1581 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1582 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1584 Asm->OutStreamer.AddComment("Compilation Unit Length");
1585 Asm->EmitInt32(TheU->getLength());
1587 // Emit the pubnames for this compilation unit.
1588 for (const auto &GI : Globals) {
1589 const char *Name = GI.getKeyData();
1590 const DIE *Entity = GI.second;
1592 Asm->OutStreamer.AddComment("DIE offset");
1593 Asm->EmitInt32(Entity->getOffset());
1596 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1597 Asm->OutStreamer.AddComment(
1598 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1599 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1600 Asm->EmitInt8(Desc.toBits());
1603 Asm->OutStreamer.AddComment("External Name");
1604 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1607 Asm->OutStreamer.AddComment("End Mark");
1609 Asm->OutStreamer.EmitLabel(EndLabel);
1613 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1614 const MCSection *PSec =
1615 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1616 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1618 emitDebugPubSection(GnuStyle, PSec, "Types",
1619 &DwarfCompileUnit::getGlobalTypes);
1622 // Emit visible names into a debug str section.
1623 void DwarfDebug::emitDebugStr() {
1624 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1625 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1629 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1630 const DebugLocEntry &Entry) {
1631 auto Comment = Entry.getComments().begin();
1632 auto End = Entry.getComments().end();
1633 for (uint8_t Byte : Entry.getDWARFBytes())
1634 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1637 static void emitDebugLocValue(const AsmPrinter &AP,
1638 const DITypeIdentifierMap &TypeIdentifierMap,
1639 ByteStreamer &Streamer,
1640 const DebugLocEntry::Value &Value,
1641 unsigned PieceOffsetInBits) {
1642 DIVariable DV = Value.getVariable();
1643 DebugLocDwarfExpression DwarfExpr(
1644 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1645 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1647 if (Value.isInt()) {
1648 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1649 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1650 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1651 DwarfExpr.AddSignedConstant(Value.getInt());
1653 DwarfExpr.AddUnsignedConstant(Value.getInt());
1654 } else if (Value.isLocation()) {
1655 MachineLocation Loc = Value.getLoc();
1656 DIExpression Expr = Value.getExpression();
1657 if (!Expr || (Expr.getNumElements() == 0))
1659 AP.EmitDwarfRegOp(Streamer, Loc);
1661 // Complex address entry.
1662 if (Loc.getOffset()) {
1663 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1664 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1666 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1670 // else ... ignore constant fp. There is not any good way to
1671 // to represent them here in dwarf.
1676 void DebugLocEntry::finalize(const AsmPrinter &AP,
1677 const DITypeIdentifierMap &TypeIdentifierMap) {
1678 BufferByteStreamer Streamer(DWARFBytes, Comments);
1679 const DebugLocEntry::Value Value = Values[0];
1680 if (Value.isBitPiece()) {
1681 // Emit all pieces that belong to the same variable and range.
1682 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1683 return P.isBitPiece();
1684 }) && "all values are expected to be pieces");
1685 assert(std::is_sorted(Values.begin(), Values.end()) &&
1686 "pieces are expected to be sorted");
1688 unsigned Offset = 0;
1689 for (auto Piece : Values) {
1690 DIExpression Expr = Piece.getExpression();
1691 unsigned PieceOffset = Expr.getBitPieceOffset();
1692 unsigned PieceSize = Expr.getBitPieceSize();
1693 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1694 if (Offset < PieceOffset) {
1695 // The DWARF spec seriously mandates pieces with no locations for gaps.
1696 DebugLocDwarfExpression Expr(
1697 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1698 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1699 Expr.AddOpPiece(PieceOffset-Offset, 0);
1700 Offset += PieceOffset-Offset;
1702 Offset += PieceSize;
1705 DIVariable Var = Piece.getVariable();
1706 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1707 assert(PieceSize+PieceOffset <= VarSize
1708 && "piece is larger than or outside of variable");
1709 assert(PieceSize != VarSize
1710 && "piece covers entire variable");
1712 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1715 assert(Values.size() == 1 && "only pieces may have >1 value");
1716 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1721 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1722 Asm->OutStreamer.AddComment("Loc expr size");
1723 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1724 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1725 Asm->EmitLabelDifference(end, begin, 2);
1726 Asm->OutStreamer.EmitLabel(begin);
1728 APByteStreamer Streamer(*Asm);
1729 emitDebugLocEntry(Streamer, Entry);
1731 Asm->OutStreamer.EmitLabel(end);
1734 // Emit locations into the debug loc section.
1735 void DwarfDebug::emitDebugLoc() {
1736 // Start the dwarf loc section.
1737 Asm->OutStreamer.SwitchSection(
1738 Asm->getObjFileLowering().getDwarfLocSection());
1739 unsigned char Size = Asm->getDataLayout().getPointerSize();
1740 for (const auto &DebugLoc : DotDebugLocEntries) {
1741 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1742 const DwarfCompileUnit *CU = DebugLoc.CU;
1743 for (const auto &Entry : DebugLoc.List) {
1744 // Set up the range. This range is relative to the entry point of the
1745 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1746 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1747 if (auto *Base = CU->getBaseAddress()) {
1748 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1749 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1751 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1752 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1755 emitDebugLocEntryLocation(Entry);
1757 Asm->OutStreamer.EmitIntValue(0, Size);
1758 Asm->OutStreamer.EmitIntValue(0, Size);
1762 void DwarfDebug::emitDebugLocDWO() {
1763 Asm->OutStreamer.SwitchSection(
1764 Asm->getObjFileLowering().getDwarfLocDWOSection());
1765 for (const auto &DebugLoc : DotDebugLocEntries) {
1766 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1767 for (const auto &Entry : DebugLoc.List) {
1768 // Just always use start_length for now - at least that's one address
1769 // rather than two. We could get fancier and try to, say, reuse an
1770 // address we know we've emitted elsewhere (the start of the function?
1771 // The start of the CU or CU subrange that encloses this range?)
1772 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1773 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1774 Asm->EmitULEB128(idx);
1775 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1777 emitDebugLocEntryLocation(Entry);
1779 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1784 const MCSymbol *Start, *End;
1787 // Emit a debug aranges section, containing a CU lookup for any
1788 // address we can tie back to a CU.
1789 void DwarfDebug::emitDebugARanges() {
1790 // Provides a unique id per text section.
1791 DenseMap<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1793 // Prime section data.
1794 SectionMap[Asm->getObjFileLowering().getTextSection()];
1796 // Filter labels by section.
1797 for (const SymbolCU &SCU : ArangeLabels) {
1798 if (SCU.Sym->isInSection()) {
1799 // Make a note of this symbol and it's section.
1800 const MCSection *Section = &SCU.Sym->getSection();
1801 if (!Section->getKind().isMetadata())
1802 SectionMap[Section].push_back(SCU);
1804 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1805 // appear in the output. This sucks as we rely on sections to build
1806 // arange spans. We can do it without, but it's icky.
1807 SectionMap[nullptr].push_back(SCU);
1811 // Build a list of sections used.
1812 std::vector<const MCSection *> Sections;
1813 for (const auto &it : SectionMap) {
1814 const MCSection *Section = it.first;
1815 Sections.push_back(Section);
1818 // Sort the sections into order.
1819 // This is only done to ensure consistent output order across different runs.
1820 std::sort(Sections.begin(), Sections.end(), SectionSort);
1822 // Add terminating symbols for each section.
1823 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1824 const MCSection *Section = Sections[ID];
1825 MCSymbol *Sym = nullptr;
1828 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1829 // if we know the section name up-front. For user-created sections, the
1830 // resulting label may not be valid to use as a label. (section names can
1831 // use a greater set of characters on some systems)
1832 Sym = Asm->GetTempSymbol("debug_end", ID);
1833 Asm->OutStreamer.SwitchSection(Section);
1834 Asm->OutStreamer.EmitLabel(Sym);
1837 // Insert a final terminator.
1838 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1841 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1843 for (const MCSection *Section : Sections) {
1844 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1845 if (List.size() < 2)
1848 // If we have no section (e.g. common), just write out
1849 // individual spans for each symbol.
1851 for (const SymbolCU &Cur : List) {
1853 Span.Start = Cur.Sym;
1856 Spans[Cur.CU].push_back(Span);
1861 // Sort the symbols by offset within the section.
1862 std::sort(List.begin(), List.end(),
1863 [&](const SymbolCU &A, const SymbolCU &B) {
1864 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1865 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1867 // Symbols with no order assigned should be placed at the end.
1868 // (e.g. section end labels)
1876 // Build spans between each label.
1877 const MCSymbol *StartSym = List[0].Sym;
1878 for (size_t n = 1, e = List.size(); n < e; n++) {
1879 const SymbolCU &Prev = List[n - 1];
1880 const SymbolCU &Cur = List[n];
1882 // Try and build the longest span we can within the same CU.
1883 if (Cur.CU != Prev.CU) {
1885 Span.Start = StartSym;
1887 Spans[Prev.CU].push_back(Span);
1893 // Start the dwarf aranges section.
1894 Asm->OutStreamer.SwitchSection(
1895 Asm->getObjFileLowering().getDwarfARangesSection());
1897 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1899 // Build a list of CUs used.
1900 std::vector<DwarfCompileUnit *> CUs;
1901 for (const auto &it : Spans) {
1902 DwarfCompileUnit *CU = it.first;
1906 // Sort the CU list (again, to ensure consistent output order).
1907 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1908 return A->getUniqueID() < B->getUniqueID();
1911 // Emit an arange table for each CU we used.
1912 for (DwarfCompileUnit *CU : CUs) {
1913 std::vector<ArangeSpan> &List = Spans[CU];
1915 // Describe the skeleton CU's offset and length, not the dwo file's.
1916 if (auto *Skel = CU->getSkeleton())
1919 // Emit size of content not including length itself.
1920 unsigned ContentSize =
1921 sizeof(int16_t) + // DWARF ARange version number
1922 sizeof(int32_t) + // Offset of CU in the .debug_info section
1923 sizeof(int8_t) + // Pointer Size (in bytes)
1924 sizeof(int8_t); // Segment Size (in bytes)
1926 unsigned TupleSize = PtrSize * 2;
1928 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1930 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1932 ContentSize += Padding;
1933 ContentSize += (List.size() + 1) * TupleSize;
1935 // For each compile unit, write the list of spans it covers.
1936 Asm->OutStreamer.AddComment("Length of ARange Set");
1937 Asm->EmitInt32(ContentSize);
1938 Asm->OutStreamer.AddComment("DWARF Arange version number");
1939 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1940 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1941 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1942 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1943 Asm->EmitInt8(PtrSize);
1944 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1947 Asm->OutStreamer.EmitFill(Padding, 0xff);
1949 for (const ArangeSpan &Span : List) {
1950 Asm->EmitLabelReference(Span.Start, PtrSize);
1952 // Calculate the size as being from the span start to it's end.
1954 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1956 // For symbols without an end marker (e.g. common), we
1957 // write a single arange entry containing just that one symbol.
1958 uint64_t Size = SymSize[Span.Start];
1962 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1966 Asm->OutStreamer.AddComment("ARange terminator");
1967 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1968 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1972 // Emit visible names into a debug ranges section.
1973 void DwarfDebug::emitDebugRanges() {
1974 // Start the dwarf ranges section.
1975 Asm->OutStreamer.SwitchSection(
1976 Asm->getObjFileLowering().getDwarfRangesSection());
1978 // Size for our labels.
1979 unsigned char Size = Asm->getDataLayout().getPointerSize();
1981 // Grab the specific ranges for the compile units in the module.
1982 for (const auto &I : CUMap) {
1983 DwarfCompileUnit *TheCU = I.second;
1985 if (auto *Skel = TheCU->getSkeleton())
1988 // Iterate over the misc ranges for the compile units in the module.
1989 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1990 // Emit our symbol so we can find the beginning of the range.
1991 Asm->OutStreamer.EmitLabel(List.getSym());
1993 for (const RangeSpan &Range : List.getRanges()) {
1994 const MCSymbol *Begin = Range.getStart();
1995 const MCSymbol *End = Range.getEnd();
1996 assert(Begin && "Range without a begin symbol?");
1997 assert(End && "Range without an end symbol?");
1998 if (auto *Base = TheCU->getBaseAddress()) {
1999 Asm->EmitLabelDifference(Begin, Base, Size);
2000 Asm->EmitLabelDifference(End, Base, Size);
2002 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2003 Asm->OutStreamer.EmitSymbolValue(End, Size);
2007 // And terminate the list with two 0 values.
2008 Asm->OutStreamer.EmitIntValue(0, Size);
2009 Asm->OutStreamer.EmitIntValue(0, Size);
2014 // DWARF5 Experimental Separate Dwarf emitters.
2016 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2017 std::unique_ptr<DwarfUnit> NewU) {
2018 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2019 U.getCUNode().getSplitDebugFilename());
2021 if (!CompilationDir.empty())
2022 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2024 addGnuPubAttributes(*NewU, Die);
2026 SkeletonHolder.addUnit(std::move(NewU));
2029 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2030 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2031 // DW_AT_addr_base, DW_AT_ranges_base.
2032 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2034 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2035 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2036 DwarfCompileUnit &NewCU = *OwnedUnit;
2037 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2038 DwarfInfoSectionSym);
2040 NewCU.initStmtList(DwarfLineSectionSym);
2042 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2047 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2048 // compile units that would normally be in debug_info.
2049 void DwarfDebug::emitDebugInfoDWO() {
2050 assert(useSplitDwarf() && "No split dwarf debug info?");
2051 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2052 // emit relocations into the dwo file.
2053 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2056 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2057 // abbreviations for the .debug_info.dwo section.
2058 void DwarfDebug::emitDebugAbbrevDWO() {
2059 assert(useSplitDwarf() && "No split dwarf?");
2060 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2063 void DwarfDebug::emitDebugLineDWO() {
2064 assert(useSplitDwarf() && "No split dwarf?");
2065 Asm->OutStreamer.SwitchSection(
2066 Asm->getObjFileLowering().getDwarfLineDWOSection());
2067 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2070 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2071 // string section and is identical in format to traditional .debug_str
2073 void DwarfDebug::emitDebugStrDWO() {
2074 assert(useSplitDwarf() && "No split dwarf?");
2075 const MCSection *OffSec =
2076 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2077 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2081 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2082 if (!useSplitDwarf())
2085 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2086 return &SplitTypeUnitFileTable;
2089 static uint64_t makeTypeSignature(StringRef Identifier) {
2091 Hash.update(Identifier);
2092 // ... take the least significant 8 bytes and return those. Our MD5
2093 // implementation always returns its results in little endian, swap bytes
2095 MD5::MD5Result Result;
2097 return support::endian::read64le(Result + 8);
2100 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2101 StringRef Identifier, DIE &RefDie,
2102 DICompositeType CTy) {
2103 // Fast path if we're building some type units and one has already used the
2104 // address pool we know we're going to throw away all this work anyway, so
2105 // don't bother building dependent types.
2106 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2109 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2111 CU.addDIETypeSignature(RefDie, *TU);
2115 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2116 AddrPool.resetUsedFlag();
2118 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2119 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2120 this, &InfoHolder, getDwoLineTable(CU));
2121 DwarfTypeUnit &NewTU = *OwnedUnit;
2122 DIE &UnitDie = NewTU.getUnitDie();
2124 TypeUnitsUnderConstruction.push_back(
2125 std::make_pair(std::move(OwnedUnit), CTy));
2127 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2130 uint64_t Signature = makeTypeSignature(Identifier);
2131 NewTU.setTypeSignature(Signature);
2133 if (useSplitDwarf())
2134 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2136 CU.applyStmtList(UnitDie);
2138 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2141 NewTU.setType(NewTU.createTypeDIE(CTy));
2144 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2145 TypeUnitsUnderConstruction.clear();
2147 // Types referencing entries in the address table cannot be placed in type
2149 if (AddrPool.hasBeenUsed()) {
2151 // Remove all the types built while building this type.
2152 // This is pessimistic as some of these types might not be dependent on
2153 // the type that used an address.
2154 for (const auto &TU : TypeUnitsToAdd)
2155 DwarfTypeUnits.erase(TU.second);
2157 // Construct this type in the CU directly.
2158 // This is inefficient because all the dependent types will be rebuilt
2159 // from scratch, including building them in type units, discovering that
2160 // they depend on addresses, throwing them out and rebuilding them.
2161 CU.constructTypeDIE(RefDie, CTy);
2165 // If the type wasn't dependent on fission addresses, finish adding the type
2166 // and all its dependent types.
2167 for (auto &TU : TypeUnitsToAdd)
2168 InfoHolder.addUnit(std::move(TU.first));
2170 CU.addDIETypeSignature(RefDie, NewTU);
2173 // Accelerator table mutators - add each name along with its companion
2174 // DIE to the proper table while ensuring that the name that we're going
2175 // to reference is in the string table. We do this since the names we
2176 // add may not only be identical to the names in the DIE.
2177 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2178 if (!useDwarfAccelTables())
2180 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2184 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2185 if (!useDwarfAccelTables())
2187 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2191 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2192 if (!useDwarfAccelTables())
2194 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2198 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2199 if (!useDwarfAccelTables())
2201 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),