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, "info_string", DIEValueAllocator),
193 UsedNonDefaultText(false),
194 SkeletonHolder(A, "skel_string", DIEValueAllocator),
195 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
196 IsPS4(Triple(A->getTargetTriple()).isPS4()),
197 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
198 dwarf::DW_FORM_data4)),
199 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
200 dwarf::DW_FORM_data4)),
201 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
202 dwarf::DW_FORM_data4)),
203 AccelTypes(TypeAtoms) {
205 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
206 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
207 DwarfLineSectionSym = nullptr;
208 DwarfAddrSectionSym = nullptr;
209 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
213 // Turn on accelerator tables for Darwin by default, pubnames by
214 // default for non-Darwin/PS4, 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 && !IsPS4;
228 HasDwarfPubSections = DwarfPubSections == Enable;
230 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
231 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
232 : MMI->getModule()->getDwarfVersion();
234 // Darwin and PS4 use the standard TLS opcode (defined in DWARF 3).
235 // Everybody else uses GNU's.
236 UseGNUTLSOpcode = !(IsDarwin || IsPS4) || DwarfVersion < 3;
238 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
241 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
246 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
247 DwarfDebug::~DwarfDebug() { }
249 // Switch to the specified MCSection and emit an assembler
250 // temporary label to it if SymbolStem is specified.
251 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
252 const char *SymbolStem = nullptr) {
253 Asm->OutStreamer.SwitchSection(Section);
257 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
258 Asm->OutStreamer.EmitLabel(TmpSym);
262 static bool isObjCClass(StringRef Name) {
263 return Name.startswith("+") || Name.startswith("-");
266 static bool hasObjCCategory(StringRef Name) {
267 if (!isObjCClass(Name))
270 return Name.find(") ") != StringRef::npos;
273 static void getObjCClassCategory(StringRef In, StringRef &Class,
274 StringRef &Category) {
275 if (!hasObjCCategory(In)) {
276 Class = In.slice(In.find('[') + 1, In.find(' '));
281 Class = In.slice(In.find('[') + 1, In.find('('));
282 Category = In.slice(In.find('[') + 1, In.find(' '));
286 static StringRef getObjCMethodName(StringRef In) {
287 return In.slice(In.find(' ') + 1, In.find(']'));
290 // Helper for sorting sections into a stable output order.
291 static bool SectionSort(const MCSection *A, const MCSection *B) {
292 std::string LA = (A ? A->getLabelBeginName() : "");
293 std::string LB = (B ? B->getLabelBeginName() : "");
297 // Add the various names to the Dwarf accelerator table names.
298 // TODO: Determine whether or not we should add names for programs
299 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
300 // is only slightly different than the lookup of non-standard ObjC names.
301 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
302 if (!SP.isDefinition())
304 addAccelName(SP.getName(), Die);
306 // If the linkage name is different than the name, go ahead and output
307 // that as well into the name table.
308 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
309 addAccelName(SP.getLinkageName(), Die);
311 // If this is an Objective-C selector name add it to the ObjC accelerator
313 if (isObjCClass(SP.getName())) {
314 StringRef Class, Category;
315 getObjCClassCategory(SP.getName(), Class, Category);
316 addAccelObjC(Class, Die);
318 addAccelObjC(Category, Die);
319 // Also add the base method name to the name table.
320 addAccelName(getObjCMethodName(SP.getName()), Die);
324 /// isSubprogramContext - Return true if Context is either a subprogram
325 /// or another context nested inside a subprogram.
326 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
329 DIDescriptor D(Context);
330 if (D.isSubprogram())
333 return isSubprogramContext(resolve(DIType(Context).getContext()));
337 /// Check whether we should create a DIE for the given Scope, return true
338 /// if we don't create a DIE (the corresponding DIE is null).
339 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
340 if (Scope->isAbstractScope())
343 // We don't create a DIE if there is no Range.
344 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
348 if (Ranges.size() > 1)
351 // We don't create a DIE if we have a single Range and the end label
353 return !getLabelAfterInsn(Ranges.front().second);
356 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
358 if (auto *SkelCU = CU.getSkeleton())
362 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
363 assert(Scope && Scope->getScopeNode());
364 assert(Scope->isAbstractScope());
365 assert(!Scope->getInlinedAt());
367 const MDNode *SP = Scope->getScopeNode();
369 ProcessedSPNodes.insert(SP);
371 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
372 // was inlined from another compile unit.
373 auto &CU = SPMap[SP];
374 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
375 CU.constructAbstractSubprogramScopeDIE(Scope);
379 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
380 if (!GenerateGnuPubSections)
383 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
386 // Create new DwarfCompileUnit for the given metadata node with tag
387 // DW_TAG_compile_unit.
388 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
389 StringRef FN = DIUnit.getFilename();
390 CompilationDir = DIUnit.getDirectory();
392 auto OwnedUnit = make_unique<DwarfCompileUnit>(
393 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
394 DwarfCompileUnit &NewCU = *OwnedUnit;
395 DIE &Die = NewCU.getUnitDie();
396 InfoHolder.addUnit(std::move(OwnedUnit));
398 NewCU.setSkeleton(constructSkeletonCU(NewCU));
400 // LTO with assembly output shares a single line table amongst multiple CUs.
401 // To avoid the compilation directory being ambiguous, let the line table
402 // explicitly describe the directory of all files, never relying on the
403 // compilation directory.
404 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
405 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
406 NewCU.getUniqueID(), CompilationDir);
408 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
409 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
410 DIUnit.getLanguage());
411 NewCU.addString(Die, dwarf::DW_AT_name, FN);
413 if (!useSplitDwarf()) {
414 NewCU.initStmtList(DwarfLineSectionSym);
416 // If we're using split dwarf the compilation dir is going to be in the
417 // skeleton CU and so we don't need to duplicate it here.
418 if (!CompilationDir.empty())
419 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
421 addGnuPubAttributes(NewCU, Die);
424 if (DIUnit.isOptimized())
425 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
427 StringRef Flags = DIUnit.getFlags();
429 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
431 if (unsigned RVer = DIUnit.getRunTimeVersion())
432 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
433 dwarf::DW_FORM_data1, RVer);
436 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
437 DwarfInfoDWOSectionSym);
439 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
440 DwarfInfoSectionSym);
442 CUMap.insert(std::make_pair(DIUnit, &NewCU));
443 CUDieMap.insert(std::make_pair(&Die, &NewCU));
447 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
449 DIImportedEntity Module(N);
450 assert(Module.Verify());
451 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
452 D->addChild(TheCU.constructImportedEntityDIE(Module));
455 // Emit all Dwarf sections that should come prior to the content. Create
456 // global DIEs and emit initial debug info sections. This is invoked by
457 // the target AsmPrinter.
458 void DwarfDebug::beginModule() {
459 if (DisableDebugInfoPrinting)
462 const Module *M = MMI->getModule();
464 FunctionDIs = makeSubprogramMap(*M);
466 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
469 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
471 // Emit initial sections so we can reference labels later.
474 SingleCU = CU_Nodes->getNumOperands() == 1;
476 for (MDNode *N : CU_Nodes->operands()) {
477 DICompileUnit CUNode(N);
478 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
479 DIArray ImportedEntities = CUNode.getImportedEntities();
480 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
481 ScopesWithImportedEntities.push_back(std::make_pair(
482 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
483 ImportedEntities.getElement(i)));
484 // Stable sort to preserve the order of appearance of imported entities.
485 // This is to avoid out-of-order processing of interdependent declarations
486 // within the same scope, e.g. { namespace A = base; namespace B = A; }
487 std::stable_sort(ScopesWithImportedEntities.begin(),
488 ScopesWithImportedEntities.end(), less_first());
489 DIArray GVs = CUNode.getGlobalVariables();
490 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
491 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
492 DIArray SPs = CUNode.getSubprograms();
493 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
494 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
495 DIArray EnumTypes = CUNode.getEnumTypes();
496 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
497 DIType Ty(EnumTypes.getElement(i));
498 // The enum types array by design contains pointers to
499 // MDNodes rather than DIRefs. Unique them here.
500 DIType UniqueTy(resolve(Ty.getRef()));
501 CU.getOrCreateTypeDIE(UniqueTy);
503 DIArray RetainedTypes = CUNode.getRetainedTypes();
504 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
505 DIType Ty(RetainedTypes.getElement(i));
506 // The retained types array by design contains pointers to
507 // MDNodes rather than DIRefs. Unique them here.
508 DIType UniqueTy(resolve(Ty.getRef()));
509 CU.getOrCreateTypeDIE(UniqueTy);
511 // Emit imported_modules last so that the relevant context is already
513 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
514 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
517 // Tell MMI that we have debug info.
518 MMI->setDebugInfoAvailability(true);
521 void DwarfDebug::finishVariableDefinitions() {
522 for (const auto &Var : ConcreteVariables) {
523 DIE *VariableDie = Var->getDIE();
525 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
526 // in the ConcreteVariables list, rather than looking it up again here.
527 // DIE::getUnit isn't simple - it walks parent pointers, etc.
528 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
530 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
531 if (AbsVar && AbsVar->getDIE()) {
532 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
535 Unit->applyVariableAttributes(*Var, *VariableDie);
539 void DwarfDebug::finishSubprogramDefinitions() {
540 for (const auto &P : SPMap)
541 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
542 CU.finishSubprogramDefinition(DISubprogram(P.first));
547 // Collect info for variables that were optimized out.
548 void DwarfDebug::collectDeadVariables() {
549 const Module *M = MMI->getModule();
551 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
552 for (MDNode *N : CU_Nodes->operands()) {
553 DICompileUnit TheCU(N);
554 // Construct subprogram DIE and add variables DIEs.
555 DwarfCompileUnit *SPCU =
556 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
557 assert(SPCU && "Unable to find Compile Unit!");
558 DIArray Subprograms = TheCU.getSubprograms();
559 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
560 DISubprogram SP(Subprograms.getElement(i));
561 if (ProcessedSPNodes.count(SP) != 0)
563 SPCU->collectDeadVariables(SP);
569 void DwarfDebug::finalizeModuleInfo() {
570 finishSubprogramDefinitions();
572 finishVariableDefinitions();
574 // Collect info for variables that were optimized out.
575 collectDeadVariables();
577 // Handle anything that needs to be done on a per-unit basis after
578 // all other generation.
579 for (const auto &P : CUMap) {
580 auto &TheCU = *P.second;
581 // Emit DW_AT_containing_type attribute to connect types with their
582 // vtable holding type.
583 TheCU.constructContainingTypeDIEs();
585 // Add CU specific attributes if we need to add any.
586 // If we're splitting the dwarf out now that we've got the entire
587 // CU then add the dwo id to it.
588 auto *SkCU = TheCU.getSkeleton();
589 if (useSplitDwarf()) {
590 // Emit a unique identifier for this CU.
591 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
592 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
593 dwarf::DW_FORM_data8, ID);
594 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
595 dwarf::DW_FORM_data8, ID);
597 // We don't keep track of which addresses are used in which CU so this
598 // is a bit pessimistic under LTO.
599 if (!AddrPool.isEmpty())
600 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
601 DwarfAddrSectionSym, DwarfAddrSectionSym);
602 if (!SkCU->getRangeLists().empty())
603 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
604 DwarfDebugRangeSectionSym,
605 DwarfDebugRangeSectionSym);
608 // If we have code split among multiple sections or non-contiguous
609 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
610 // remain in the .o file, otherwise add a DW_AT_low_pc.
611 // FIXME: We should use ranges allow reordering of code ala
612 // .subsections_via_symbols in mach-o. This would mean turning on
613 // ranges for all subprogram DIEs for mach-o.
614 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
615 if (unsigned NumRanges = TheCU.getRanges().size()) {
617 // A DW_AT_low_pc attribute may also be specified in combination with
618 // DW_AT_ranges to specify the default base address for use in
619 // location lists (see Section 2.6.2) and range lists (see Section
621 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
623 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
624 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
628 // Compute DIE offsets and sizes.
629 InfoHolder.computeSizeAndOffsets();
631 SkeletonHolder.computeSizeAndOffsets();
634 // Emit all Dwarf sections that should come after the content.
635 void DwarfDebug::endModule() {
636 assert(CurFn == nullptr);
637 assert(CurMI == nullptr);
639 // If we aren't actually generating debug info (check beginModule -
640 // conditionalized on !DisableDebugInfoPrinting and the presence of the
641 // llvm.dbg.cu metadata node)
642 if (!DwarfInfoSectionSym)
645 // Finalize the debug info for the module.
646 finalizeModuleInfo();
650 // Emit all the DIEs into a debug info section.
653 // Corresponding abbreviations into a abbrev section.
656 // Emit info into a debug aranges section.
657 if (GenerateARangeSection)
660 // Emit info into a debug ranges section.
663 if (useSplitDwarf()) {
666 emitDebugAbbrevDWO();
669 // Emit DWO addresses.
670 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
672 // Emit info into a debug loc section.
675 // Emit info into the dwarf accelerator table sections.
676 if (useDwarfAccelTables()) {
679 emitAccelNamespaces();
683 // Emit the pubnames and pubtypes sections if requested.
684 if (HasDwarfPubSections) {
685 emitDebugPubNames(GenerateGnuPubSections);
686 emitDebugPubTypes(GenerateGnuPubSections);
691 AbstractVariables.clear();
694 // Find abstract variable, if any, associated with Var.
695 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
696 DIVariable &Cleansed) {
697 LLVMContext &Ctx = DV->getContext();
698 // More then one inlined variable corresponds to one abstract variable.
699 // FIXME: This duplication of variables when inlining should probably be
700 // removed. It's done to allow each DIVariable to describe its location
701 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
702 // make it accurate then remove this duplication/cleansing stuff.
703 Cleansed = cleanseInlinedVariable(DV, Ctx);
704 auto I = AbstractVariables.find(Cleansed);
705 if (I != AbstractVariables.end())
706 return I->second.get();
710 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
712 return getExistingAbstractVariable(DV, Cleansed);
715 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
716 LexicalScope *Scope) {
717 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
718 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
719 AbstractVariables[Var] = std::move(AbsDbgVariable);
722 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
723 const MDNode *ScopeNode) {
724 DIVariable Cleansed = DV;
725 if (getExistingAbstractVariable(DV, Cleansed))
728 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
732 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
733 const MDNode *ScopeNode) {
734 DIVariable Cleansed = DV;
735 if (getExistingAbstractVariable(DV, Cleansed))
738 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
739 createAbstractVariable(Cleansed, Scope);
742 // Collect variable information from side table maintained by MMI.
743 void DwarfDebug::collectVariableInfoFromMMITable(
744 SmallPtrSetImpl<const MDNode *> &Processed) {
745 for (const auto &VI : MMI->getVariableDbgInfo()) {
748 Processed.insert(VI.Var);
749 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
751 // If variable scope is not found then skip this variable.
755 DIVariable DV(VI.Var);
756 DIExpression Expr(VI.Expr);
757 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
758 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
759 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
760 ConcreteVariables.push_back(std::move(RegVar));
764 // Get .debug_loc entry for the instruction range starting at MI.
765 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
766 const MDNode *Expr = MI->getDebugExpression();
767 const MDNode *Var = MI->getDebugVariable();
769 assert(MI->getNumOperands() == 4);
770 if (MI->getOperand(0).isReg()) {
771 MachineLocation MLoc;
772 // If the second operand is an immediate, this is a
773 // register-indirect address.
774 if (!MI->getOperand(1).isImm())
775 MLoc.set(MI->getOperand(0).getReg());
777 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
778 return DebugLocEntry::Value(Var, Expr, MLoc);
780 if (MI->getOperand(0).isImm())
781 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
782 if (MI->getOperand(0).isFPImm())
783 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
784 if (MI->getOperand(0).isCImm())
785 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
787 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
790 /// Determine whether two variable pieces overlap.
791 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
792 if (!P1.isBitPiece() || !P2.isBitPiece())
794 unsigned l1 = P1.getBitPieceOffset();
795 unsigned l2 = P2.getBitPieceOffset();
796 unsigned r1 = l1 + P1.getBitPieceSize();
797 unsigned r2 = l2 + P2.getBitPieceSize();
798 // True where [l1,r1[ and [r1,r2[ overlap.
799 return (l1 < r2) && (l2 < r1);
802 /// Build the location list for all DBG_VALUEs in the function that
803 /// describe the same variable. If the ranges of several independent
804 /// pieces of the same variable overlap partially, split them up and
805 /// combine the ranges. The resulting DebugLocEntries are will have
806 /// strict monotonically increasing begin addresses and will never
811 // Ranges History [var, loc, piece ofs size]
812 // 0 | [x, (reg0, piece 0, 32)]
813 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
815 // 3 | [clobber reg0]
816 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
821 // [0-1] [x, (reg0, piece 0, 32)]
822 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
823 // [3-4] [x, (reg1, piece 32, 32)]
824 // [4- ] [x, (mem, piece 0, 64)]
826 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
827 const DbgValueHistoryMap::InstrRanges &Ranges) {
828 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
830 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
831 const MachineInstr *Begin = I->first;
832 const MachineInstr *End = I->second;
833 assert(Begin->isDebugValue() && "Invalid History entry");
835 // Check if a variable is inaccessible in this range.
836 if (Begin->getNumOperands() > 1 &&
837 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
842 // If this piece overlaps with any open ranges, truncate them.
843 DIExpression DIExpr = Begin->getDebugExpression();
844 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
845 [&](DebugLocEntry::Value R) {
846 return piecesOverlap(DIExpr, R.getExpression());
848 OpenRanges.erase(Last, OpenRanges.end());
850 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
851 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
853 const MCSymbol *EndLabel;
855 EndLabel = getLabelAfterInsn(End);
856 else if (std::next(I) == Ranges.end())
857 EndLabel = Asm->getFunctionEnd();
859 EndLabel = getLabelBeforeInsn(std::next(I)->first);
860 assert(EndLabel && "Forgot label after instruction ending a range!");
862 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
864 auto Value = getDebugLocValue(Begin);
865 DebugLocEntry Loc(StartLabel, EndLabel, Value);
866 bool couldMerge = false;
868 // If this is a piece, it may belong to the current DebugLocEntry.
869 if (DIExpr.isBitPiece()) {
870 // Add this value to the list of open ranges.
871 OpenRanges.push_back(Value);
873 // Attempt to add the piece to the last entry.
874 if (!DebugLoc.empty())
875 if (DebugLoc.back().MergeValues(Loc))
880 // Need to add a new DebugLocEntry. Add all values from still
881 // valid non-overlapping pieces.
882 if (OpenRanges.size())
883 Loc.addValues(OpenRanges);
885 DebugLoc.push_back(std::move(Loc));
888 // Attempt to coalesce the ranges of two otherwise identical
890 auto CurEntry = DebugLoc.rbegin();
891 auto PrevEntry = std::next(CurEntry);
892 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
896 dbgs() << CurEntry->getValues().size() << " Values:\n";
897 for (auto Value : CurEntry->getValues()) {
898 Value.getVariable()->dump();
899 Value.getExpression()->dump();
907 // Find variables for each lexical scope.
909 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
910 SmallPtrSetImpl<const MDNode *> &Processed) {
911 // Grab the variable info that was squirreled away in the MMI side-table.
912 collectVariableInfoFromMMITable(Processed);
914 for (const auto &I : DbgValues) {
915 DIVariable DV(I.first);
916 if (Processed.count(DV))
919 // Instruction ranges, specifying where DV is accessible.
920 const auto &Ranges = I.second;
924 LexicalScope *Scope = nullptr;
925 if (MDNode *IA = DV.getInlinedAt())
926 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
928 Scope = LScopes.findLexicalScope(DV.getContext());
929 // If variable scope is not found then skip this variable.
933 Processed.insert(DV);
934 const MachineInstr *MInsn = Ranges.front().first;
935 assert(MInsn->isDebugValue() && "History must begin with debug value");
936 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
937 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
938 DbgVariable *RegVar = ConcreteVariables.back().get();
939 InfoHolder.addScopeVariable(Scope, RegVar);
941 // Check if the first DBG_VALUE is valid for the rest of the function.
942 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
945 // Handle multiple DBG_VALUE instructions describing one variable.
946 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
948 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
949 DebugLocList &LocList = DotDebugLocEntries.back();
952 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
954 // Build the location list for this variable.
955 buildLocationList(LocList.List, Ranges);
956 // Finalize the entry by lowering it into a DWARF bytestream.
957 for (auto &Entry : LocList.List)
958 Entry.finalize(*Asm, TypeIdentifierMap);
961 // Collect info for variables that were optimized out.
962 DIArray Variables = SP.getVariables();
963 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
964 DIVariable DV(Variables.getElement(i));
965 assert(DV.isVariable());
966 if (!Processed.insert(DV).second)
968 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
969 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
971 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
972 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
977 // Return Label preceding the instruction.
978 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
979 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
980 assert(Label && "Didn't insert label before instruction");
984 // Return Label immediately following the instruction.
985 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
986 return LabelsAfterInsn.lookup(MI);
989 // Process beginning of an instruction.
990 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
991 assert(CurMI == nullptr);
993 // Check if source location changes, but ignore DBG_VALUE locations.
994 if (!MI->isDebugValue()) {
995 DebugLoc DL = MI->getDebugLoc();
996 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
999 if (DL == PrologEndLoc) {
1000 Flags |= DWARF2_FLAG_PROLOGUE_END;
1001 PrologEndLoc = DebugLoc();
1002 Flags |= DWARF2_FLAG_IS_STMT;
1005 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
1006 Flags |= DWARF2_FLAG_IS_STMT;
1008 if (!DL.isUnknown()) {
1009 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1010 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1012 recordSourceLine(0, 0, nullptr, 0);
1016 // Insert labels where requested.
1017 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1018 LabelsBeforeInsn.find(MI);
1021 if (I == LabelsBeforeInsn.end())
1024 // Label already assigned.
1029 PrevLabel = MMI->getContext().CreateTempSymbol();
1030 Asm->OutStreamer.EmitLabel(PrevLabel);
1032 I->second = PrevLabel;
1035 // Process end of an instruction.
1036 void DwarfDebug::endInstruction() {
1037 assert(CurMI != nullptr);
1038 // Don't create a new label after DBG_VALUE instructions.
1039 // They don't generate code.
1040 if (!CurMI->isDebugValue())
1041 PrevLabel = nullptr;
1043 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1044 LabelsAfterInsn.find(CurMI);
1048 if (I == LabelsAfterInsn.end())
1051 // Label already assigned.
1055 // We need a label after this instruction.
1057 PrevLabel = MMI->getContext().CreateTempSymbol();
1058 Asm->OutStreamer.EmitLabel(PrevLabel);
1060 I->second = PrevLabel;
1063 // Each LexicalScope has first instruction and last instruction to mark
1064 // beginning and end of a scope respectively. Create an inverse map that list
1065 // scopes starts (and ends) with an instruction. One instruction may start (or
1066 // end) multiple scopes. Ignore scopes that are not reachable.
1067 void DwarfDebug::identifyScopeMarkers() {
1068 SmallVector<LexicalScope *, 4> WorkList;
1069 WorkList.push_back(LScopes.getCurrentFunctionScope());
1070 while (!WorkList.empty()) {
1071 LexicalScope *S = WorkList.pop_back_val();
1073 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1074 if (!Children.empty())
1075 WorkList.append(Children.begin(), Children.end());
1077 if (S->isAbstractScope())
1080 for (const InsnRange &R : S->getRanges()) {
1081 assert(R.first && "InsnRange does not have first instruction!");
1082 assert(R.second && "InsnRange does not have second instruction!");
1083 requestLabelBeforeInsn(R.first);
1084 requestLabelAfterInsn(R.second);
1089 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1090 // First known non-DBG_VALUE and non-frame setup location marks
1091 // the beginning of the function body.
1092 for (const auto &MBB : *MF)
1093 for (const auto &MI : MBB)
1094 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1095 !MI.getDebugLoc().isUnknown()) {
1096 // Did the target forget to set the FrameSetup flag for CFI insns?
1097 assert(!MI.isCFIInstruction() &&
1098 "First non-frame-setup instruction is a CFI instruction.");
1099 return MI.getDebugLoc();
1104 // Gather pre-function debug information. Assumes being called immediately
1105 // after the function entry point has been emitted.
1106 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1109 // If there's no debug info for the function we're not going to do anything.
1110 if (!MMI->hasDebugInfo())
1113 auto DI = FunctionDIs.find(MF->getFunction());
1114 if (DI == FunctionDIs.end())
1117 // Grab the lexical scopes for the function, if we don't have any of those
1118 // then we're not going to be able to do anything.
1119 LScopes.initialize(*MF);
1120 if (LScopes.empty())
1123 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1125 // Make sure that each lexical scope will have a begin/end label.
1126 identifyScopeMarkers();
1128 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1129 // belongs to so that we add to the correct per-cu line table in the
1131 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1132 // FnScope->getScopeNode() and DI->second should represent the same function,
1133 // though they may not be the same MDNode due to inline functions merged in
1134 // LTO where the debug info metadata still differs (either due to distinct
1135 // written differences - two versions of a linkonce_odr function
1136 // written/copied into two separate files, or some sub-optimal metadata that
1137 // isn't structurally identical (see: file path/name info from clang, which
1138 // includes the directory of the cpp file being built, even when the file name
1139 // is absolute (such as an <> lookup header)))
1140 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1141 assert(TheCU && "Unable to find compile unit!");
1142 if (Asm->OutStreamer.hasRawTextSupport())
1143 // Use a single line table if we are generating assembly.
1144 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1146 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1148 // Calculate history for local variables.
1149 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1152 // Request labels for the full history.
1153 for (const auto &I : DbgValues) {
1154 const auto &Ranges = I.second;
1158 // The first mention of a function argument gets the CurrentFnBegin
1159 // label, so arguments are visible when breaking at function entry.
1160 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1161 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1162 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1163 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1164 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1165 // Mark all non-overlapping initial pieces.
1166 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1167 DIExpression Piece = I->first->getDebugExpression();
1168 if (std::all_of(Ranges.begin(), I,
1169 [&](DbgValueHistoryMap::InstrRange Pred) {
1170 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1172 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1179 for (const auto &Range : Ranges) {
1180 requestLabelBeforeInsn(Range.first);
1182 requestLabelAfterInsn(Range.second);
1186 PrevInstLoc = DebugLoc();
1187 PrevLabel = Asm->getFunctionBegin();
1189 // Record beginning of function.
1190 PrologEndLoc = findPrologueEndLoc(MF);
1191 if (!PrologEndLoc.isUnknown()) {
1192 DebugLoc FnStartDL =
1193 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1195 // We'd like to list the prologue as "not statements" but GDB behaves
1196 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1197 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1198 FnStartDL.getScope(MF->getFunction()->getContext()),
1199 DWARF2_FLAG_IS_STMT);
1203 // Gather and emit post-function debug information.
1204 void DwarfDebug::endFunction(const MachineFunction *MF) {
1205 assert(CurFn == MF &&
1206 "endFunction should be called with the same function as beginFunction");
1208 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1209 !FunctionDIs.count(MF->getFunction())) {
1210 // If we don't have a lexical scope for this function then there will
1211 // be a hole in the range information. Keep note of this by setting the
1212 // previously used section to nullptr.
1218 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1219 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1221 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1222 DISubprogram SP(FnScope->getScopeNode());
1223 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1225 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1226 collectVariableInfo(TheCU, SP, ProcessedVars);
1228 // Add the range of this function to the list of ranges for the CU.
1229 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1231 // Under -gmlt, skip building the subprogram if there are no inlined
1232 // subroutines inside it.
1233 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1234 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1235 assert(InfoHolder.getScopeVariables().empty());
1236 assert(DbgValues.empty());
1237 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1238 // by a -gmlt CU. Add a test and remove this assertion.
1239 assert(AbstractVariables.empty());
1240 LabelsBeforeInsn.clear();
1241 LabelsAfterInsn.clear();
1242 PrevLabel = nullptr;
1248 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1250 // Construct abstract scopes.
1251 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1252 DISubprogram SP(AScope->getScopeNode());
1253 assert(SP.isSubprogram());
1254 // Collect info for variables that were optimized out.
1255 DIArray Variables = SP.getVariables();
1256 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1257 DIVariable DV(Variables.getElement(i));
1258 assert(DV && DV.isVariable());
1259 if (!ProcessedVars.insert(DV).second)
1261 ensureAbstractVariableIsCreated(DV, DV.getContext());
1262 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1263 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1265 constructAbstractSubprogramScopeDIE(AScope);
1268 TheCU.constructSubprogramScopeDIE(FnScope);
1269 if (auto *SkelCU = TheCU.getSkeleton())
1270 if (!LScopes.getAbstractScopesList().empty())
1271 SkelCU->constructSubprogramScopeDIE(FnScope);
1274 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1275 // DbgVariables except those that are also in AbstractVariables (since they
1276 // can be used cross-function)
1277 InfoHolder.getScopeVariables().clear();
1279 LabelsBeforeInsn.clear();
1280 LabelsAfterInsn.clear();
1281 PrevLabel = nullptr;
1285 // Register a source line with debug info. Returns the unique label that was
1286 // emitted and which provides correspondence to the source line list.
1287 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1292 unsigned Discriminator = 0;
1293 if (DIScope Scope = DIScope(S)) {
1294 assert(Scope.isScope());
1295 Fn = Scope.getFilename();
1296 Dir = Scope.getDirectory();
1297 if (Scope.isLexicalBlockFile())
1298 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1300 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1301 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1302 .getOrCreateSourceID(Fn, Dir);
1304 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1308 //===----------------------------------------------------------------------===//
1310 //===----------------------------------------------------------------------===//
1312 // Emit initial Dwarf sections with a label at the start of each one.
1313 void DwarfDebug::emitSectionLabels() {
1314 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1316 // Dwarf sections base addresses.
1317 DwarfInfoSectionSym =
1318 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1319 if (useSplitDwarf()) {
1320 DwarfInfoDWOSectionSym =
1321 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1322 DwarfTypesDWOSectionSym = emitSectionSym(
1323 Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1325 DwarfAbbrevSectionSym =
1326 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1327 if (useSplitDwarf())
1328 DwarfAbbrevDWOSectionSym = emitSectionSym(
1329 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1330 if (GenerateARangeSection)
1331 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1333 DwarfLineSectionSym =
1334 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1335 if (GenerateGnuPubSections) {
1336 DwarfGnuPubNamesSectionSym =
1337 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1338 DwarfGnuPubTypesSectionSym =
1339 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1340 } else if (HasDwarfPubSections) {
1341 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1342 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1345 DwarfStrSectionSym =
1346 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1347 if (useSplitDwarf()) {
1348 DwarfStrDWOSectionSym =
1349 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1350 DwarfAddrSectionSym =
1351 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1352 DwarfDebugLocSectionSym =
1353 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1355 DwarfDebugLocSectionSym =
1356 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1357 DwarfDebugRangeSectionSym =
1358 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1361 // Emit the debug info section.
1362 void DwarfDebug::emitDebugInfo() {
1363 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1365 Holder.emitUnits(DwarfAbbrevSectionSym);
1368 // Emit the abbreviation section.
1369 void DwarfDebug::emitAbbreviations() {
1370 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1372 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1375 // Emit the last address of the section and the end of the line matrix.
1376 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1377 // Define last address of section.
1378 Asm->OutStreamer.AddComment("Extended Op");
1381 Asm->OutStreamer.AddComment("Op size");
1382 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1383 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1384 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1386 Asm->OutStreamer.AddComment("Section end label");
1388 Asm->OutStreamer.EmitSymbolValue(
1389 Asm->GetTempSymbol("section_end", SectionEnd),
1390 Asm->getDataLayout().getPointerSize());
1392 // Mark end of matrix.
1393 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1399 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1400 StringRef TableName, StringRef SymName) {
1401 Accel.FinalizeTable(Asm, TableName);
1402 Asm->OutStreamer.SwitchSection(Section);
1403 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1404 Asm->OutStreamer.EmitLabel(SectionBegin);
1406 // Emit the full data.
1407 Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1410 // Emit visible names into a hashed accelerator table section.
1411 void DwarfDebug::emitAccelNames() {
1412 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1413 "Names", "names_begin");
1416 // Emit objective C classes and categories into a hashed accelerator table
1418 void DwarfDebug::emitAccelObjC() {
1419 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1420 "ObjC", "objc_begin");
1423 // Emit namespace dies into a hashed accelerator table.
1424 void DwarfDebug::emitAccelNamespaces() {
1425 emitAccel(AccelNamespace,
1426 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1427 "namespac", "namespac_begin");
1430 // Emit type dies into a hashed accelerator table.
1431 void DwarfDebug::emitAccelTypes() {
1432 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1433 "types", "types_begin");
1436 // Public name handling.
1437 // The format for the various pubnames:
1439 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1440 // for the DIE that is named.
1442 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1443 // into the CU and the index value is computed according to the type of value
1444 // for the DIE that is named.
1446 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1447 // it's the offset within the debug_info/debug_types dwo section, however, the
1448 // reference in the pubname header doesn't change.
1450 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1451 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1453 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1455 // We could have a specification DIE that has our most of our knowledge,
1456 // look for that now.
1457 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1459 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1460 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1461 Linkage = dwarf::GIEL_EXTERNAL;
1462 } else if (Die->findAttribute(dwarf::DW_AT_external))
1463 Linkage = dwarf::GIEL_EXTERNAL;
1465 switch (Die->getTag()) {
1466 case dwarf::DW_TAG_class_type:
1467 case dwarf::DW_TAG_structure_type:
1468 case dwarf::DW_TAG_union_type:
1469 case dwarf::DW_TAG_enumeration_type:
1470 return dwarf::PubIndexEntryDescriptor(
1471 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1472 ? dwarf::GIEL_STATIC
1473 : dwarf::GIEL_EXTERNAL);
1474 case dwarf::DW_TAG_typedef:
1475 case dwarf::DW_TAG_base_type:
1476 case dwarf::DW_TAG_subrange_type:
1477 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1478 case dwarf::DW_TAG_namespace:
1479 return dwarf::GIEK_TYPE;
1480 case dwarf::DW_TAG_subprogram:
1481 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1482 case dwarf::DW_TAG_variable:
1483 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1484 case dwarf::DW_TAG_enumerator:
1485 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1486 dwarf::GIEL_STATIC);
1488 return dwarf::GIEK_NONE;
1492 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1494 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1495 const MCSection *PSec =
1496 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1497 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1499 emitDebugPubSection(GnuStyle, PSec, "Names",
1500 &DwarfCompileUnit::getGlobalNames);
1503 void DwarfDebug::emitDebugPubSection(
1504 bool GnuStyle, const MCSection *PSec, StringRef Name,
1505 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1506 for (const auto &NU : CUMap) {
1507 DwarfCompileUnit *TheU = NU.second;
1509 const auto &Globals = (TheU->*Accessor)();
1511 if (Globals.empty())
1514 if (auto *Skeleton = TheU->getSkeleton())
1516 unsigned ID = TheU->getUniqueID();
1518 // Start the dwarf pubnames section.
1519 Asm->OutStreamer.SwitchSection(PSec);
1522 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1523 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1524 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1525 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1527 Asm->OutStreamer.EmitLabel(BeginLabel);
1529 Asm->OutStreamer.AddComment("DWARF Version");
1530 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1532 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1533 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1535 Asm->OutStreamer.AddComment("Compilation Unit Length");
1536 Asm->EmitInt32(TheU->getLength());
1538 // Emit the pubnames for this compilation unit.
1539 for (const auto &GI : Globals) {
1540 const char *Name = GI.getKeyData();
1541 const DIE *Entity = GI.second;
1543 Asm->OutStreamer.AddComment("DIE offset");
1544 Asm->EmitInt32(Entity->getOffset());
1547 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1548 Asm->OutStreamer.AddComment(
1549 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1550 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1551 Asm->EmitInt8(Desc.toBits());
1554 Asm->OutStreamer.AddComment("External Name");
1555 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1558 Asm->OutStreamer.AddComment("End Mark");
1560 Asm->OutStreamer.EmitLabel(EndLabel);
1564 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1565 const MCSection *PSec =
1566 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1567 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1569 emitDebugPubSection(GnuStyle, PSec, "Types",
1570 &DwarfCompileUnit::getGlobalTypes);
1573 // Emit visible names into a debug str section.
1574 void DwarfDebug::emitDebugStr() {
1575 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1576 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1580 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1581 const DebugLocEntry &Entry) {
1582 auto Comment = Entry.getComments().begin();
1583 auto End = Entry.getComments().end();
1584 for (uint8_t Byte : Entry.getDWARFBytes())
1585 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1588 static void emitDebugLocValue(const AsmPrinter &AP,
1589 const DITypeIdentifierMap &TypeIdentifierMap,
1590 ByteStreamer &Streamer,
1591 const DebugLocEntry::Value &Value,
1592 unsigned PieceOffsetInBits) {
1593 DIVariable DV = Value.getVariable();
1594 DebugLocDwarfExpression DwarfExpr(
1595 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1596 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1598 if (Value.isInt()) {
1599 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1600 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1601 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1602 DwarfExpr.AddSignedConstant(Value.getInt());
1604 DwarfExpr.AddUnsignedConstant(Value.getInt());
1605 } else if (Value.isLocation()) {
1606 MachineLocation Loc = Value.getLoc();
1607 DIExpression Expr = Value.getExpression();
1608 if (!Expr || (Expr.getNumElements() == 0))
1610 AP.EmitDwarfRegOp(Streamer, Loc);
1612 // Complex address entry.
1613 if (Loc.getOffset()) {
1614 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1615 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1617 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1621 // else ... ignore constant fp. There is not any good way to
1622 // to represent them here in dwarf.
1627 void DebugLocEntry::finalize(const AsmPrinter &AP,
1628 const DITypeIdentifierMap &TypeIdentifierMap) {
1629 BufferByteStreamer Streamer(DWARFBytes, Comments);
1630 const DebugLocEntry::Value Value = Values[0];
1631 if (Value.isBitPiece()) {
1632 // Emit all pieces that belong to the same variable and range.
1633 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1634 return P.isBitPiece();
1635 }) && "all values are expected to be pieces");
1636 assert(std::is_sorted(Values.begin(), Values.end()) &&
1637 "pieces are expected to be sorted");
1639 unsigned Offset = 0;
1640 for (auto Piece : Values) {
1641 DIExpression Expr = Piece.getExpression();
1642 unsigned PieceOffset = Expr.getBitPieceOffset();
1643 unsigned PieceSize = Expr.getBitPieceSize();
1644 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1645 if (Offset < PieceOffset) {
1646 // The DWARF spec seriously mandates pieces with no locations for gaps.
1647 DebugLocDwarfExpression Expr(
1648 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1649 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1650 Expr.AddOpPiece(PieceOffset-Offset, 0);
1651 Offset += PieceOffset-Offset;
1653 Offset += PieceSize;
1656 DIVariable Var = Piece.getVariable();
1657 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1658 assert(PieceSize+PieceOffset <= VarSize
1659 && "piece is larger than or outside of variable");
1660 assert(PieceSize != VarSize
1661 && "piece covers entire variable");
1663 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1666 assert(Values.size() == 1 && "only pieces may have >1 value");
1667 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1672 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1673 Asm->OutStreamer.AddComment("Loc expr size");
1674 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1675 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1676 Asm->EmitLabelDifference(end, begin, 2);
1677 Asm->OutStreamer.EmitLabel(begin);
1679 APByteStreamer Streamer(*Asm);
1680 emitDebugLocEntry(Streamer, Entry);
1682 Asm->OutStreamer.EmitLabel(end);
1685 // Emit locations into the debug loc section.
1686 void DwarfDebug::emitDebugLoc() {
1687 // Start the dwarf loc section.
1688 Asm->OutStreamer.SwitchSection(
1689 Asm->getObjFileLowering().getDwarfLocSection());
1690 unsigned char Size = Asm->getDataLayout().getPointerSize();
1691 for (const auto &DebugLoc : DotDebugLocEntries) {
1692 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1693 const DwarfCompileUnit *CU = DebugLoc.CU;
1694 for (const auto &Entry : DebugLoc.List) {
1695 // Set up the range. This range is relative to the entry point of the
1696 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1697 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1698 if (auto *Base = CU->getBaseAddress()) {
1699 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1700 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1702 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1703 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1706 emitDebugLocEntryLocation(Entry);
1708 Asm->OutStreamer.EmitIntValue(0, Size);
1709 Asm->OutStreamer.EmitIntValue(0, Size);
1713 void DwarfDebug::emitDebugLocDWO() {
1714 Asm->OutStreamer.SwitchSection(
1715 Asm->getObjFileLowering().getDwarfLocDWOSection());
1716 for (const auto &DebugLoc : DotDebugLocEntries) {
1717 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1718 for (const auto &Entry : DebugLoc.List) {
1719 // Just always use start_length for now - at least that's one address
1720 // rather than two. We could get fancier and try to, say, reuse an
1721 // address we know we've emitted elsewhere (the start of the function?
1722 // The start of the CU or CU subrange that encloses this range?)
1723 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1724 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1725 Asm->EmitULEB128(idx);
1726 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1728 emitDebugLocEntryLocation(Entry);
1730 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1735 const MCSymbol *Start, *End;
1738 // Emit a debug aranges section, containing a CU lookup for any
1739 // address we can tie back to a CU.
1740 void DwarfDebug::emitDebugARanges() {
1741 // Provides a unique id per text section.
1742 DenseMap<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1744 // Prime section data.
1745 SectionMap[Asm->getObjFileLowering().getTextSection()];
1747 // Filter labels by section.
1748 for (const SymbolCU &SCU : ArangeLabels) {
1749 if (SCU.Sym->isInSection()) {
1750 // Make a note of this symbol and it's section.
1751 const MCSection *Section = &SCU.Sym->getSection();
1752 if (!Section->getKind().isMetadata())
1753 SectionMap[Section].push_back(SCU);
1755 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1756 // appear in the output. This sucks as we rely on sections to build
1757 // arange spans. We can do it without, but it's icky.
1758 SectionMap[nullptr].push_back(SCU);
1762 // Build a list of sections used.
1763 std::vector<const MCSection *> Sections;
1764 for (const auto &it : SectionMap) {
1765 const MCSection *Section = it.first;
1766 Sections.push_back(Section);
1769 // Sort the sections into order.
1770 // This is only done to ensure consistent output order across different runs.
1771 std::sort(Sections.begin(), Sections.end(), SectionSort);
1773 // Add terminating symbols for each section.
1774 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1775 const MCSection *Section = Sections[ID];
1776 MCSymbol *Sym = nullptr;
1779 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1780 // if we know the section name up-front. For user-created sections, the
1781 // resulting label may not be valid to use as a label. (section names can
1782 // use a greater set of characters on some systems)
1783 Sym = Asm->GetTempSymbol("debug_end", ID);
1784 Asm->OutStreamer.SwitchSection(Section);
1785 Asm->OutStreamer.EmitLabel(Sym);
1788 // Insert a final terminator.
1789 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1792 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1794 for (const MCSection *Section : Sections) {
1795 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1796 if (List.size() < 2)
1799 // If we have no section (e.g. common), just write out
1800 // individual spans for each symbol.
1802 for (const SymbolCU &Cur : List) {
1804 Span.Start = Cur.Sym;
1807 Spans[Cur.CU].push_back(Span);
1812 // Sort the symbols by offset within the section.
1813 std::sort(List.begin(), List.end(),
1814 [&](const SymbolCU &A, const SymbolCU &B) {
1815 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1816 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1818 // Symbols with no order assigned should be placed at the end.
1819 // (e.g. section end labels)
1827 // Build spans between each label.
1828 const MCSymbol *StartSym = List[0].Sym;
1829 for (size_t n = 1, e = List.size(); n < e; n++) {
1830 const SymbolCU &Prev = List[n - 1];
1831 const SymbolCU &Cur = List[n];
1833 // Try and build the longest span we can within the same CU.
1834 if (Cur.CU != Prev.CU) {
1836 Span.Start = StartSym;
1838 Spans[Prev.CU].push_back(Span);
1844 // Start the dwarf aranges section.
1845 Asm->OutStreamer.SwitchSection(
1846 Asm->getObjFileLowering().getDwarfARangesSection());
1848 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1850 // Build a list of CUs used.
1851 std::vector<DwarfCompileUnit *> CUs;
1852 for (const auto &it : Spans) {
1853 DwarfCompileUnit *CU = it.first;
1857 // Sort the CU list (again, to ensure consistent output order).
1858 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1859 return A->getUniqueID() < B->getUniqueID();
1862 // Emit an arange table for each CU we used.
1863 for (DwarfCompileUnit *CU : CUs) {
1864 std::vector<ArangeSpan> &List = Spans[CU];
1866 // Describe the skeleton CU's offset and length, not the dwo file's.
1867 if (auto *Skel = CU->getSkeleton())
1870 // Emit size of content not including length itself.
1871 unsigned ContentSize =
1872 sizeof(int16_t) + // DWARF ARange version number
1873 sizeof(int32_t) + // Offset of CU in the .debug_info section
1874 sizeof(int8_t) + // Pointer Size (in bytes)
1875 sizeof(int8_t); // Segment Size (in bytes)
1877 unsigned TupleSize = PtrSize * 2;
1879 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1881 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1883 ContentSize += Padding;
1884 ContentSize += (List.size() + 1) * TupleSize;
1886 // For each compile unit, write the list of spans it covers.
1887 Asm->OutStreamer.AddComment("Length of ARange Set");
1888 Asm->EmitInt32(ContentSize);
1889 Asm->OutStreamer.AddComment("DWARF Arange version number");
1890 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1891 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1892 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1893 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1894 Asm->EmitInt8(PtrSize);
1895 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1898 Asm->OutStreamer.EmitFill(Padding, 0xff);
1900 for (const ArangeSpan &Span : List) {
1901 Asm->EmitLabelReference(Span.Start, PtrSize);
1903 // Calculate the size as being from the span start to it's end.
1905 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1907 // For symbols without an end marker (e.g. common), we
1908 // write a single arange entry containing just that one symbol.
1909 uint64_t Size = SymSize[Span.Start];
1913 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1917 Asm->OutStreamer.AddComment("ARange terminator");
1918 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1919 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1923 // Emit visible names into a debug ranges section.
1924 void DwarfDebug::emitDebugRanges() {
1925 // Start the dwarf ranges section.
1926 Asm->OutStreamer.SwitchSection(
1927 Asm->getObjFileLowering().getDwarfRangesSection());
1929 // Size for our labels.
1930 unsigned char Size = Asm->getDataLayout().getPointerSize();
1932 // Grab the specific ranges for the compile units in the module.
1933 for (const auto &I : CUMap) {
1934 DwarfCompileUnit *TheCU = I.second;
1936 if (auto *Skel = TheCU->getSkeleton())
1939 // Iterate over the misc ranges for the compile units in the module.
1940 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1941 // Emit our symbol so we can find the beginning of the range.
1942 Asm->OutStreamer.EmitLabel(List.getSym());
1944 for (const RangeSpan &Range : List.getRanges()) {
1945 const MCSymbol *Begin = Range.getStart();
1946 const MCSymbol *End = Range.getEnd();
1947 assert(Begin && "Range without a begin symbol?");
1948 assert(End && "Range without an end symbol?");
1949 if (auto *Base = TheCU->getBaseAddress()) {
1950 Asm->EmitLabelDifference(Begin, Base, Size);
1951 Asm->EmitLabelDifference(End, Base, Size);
1953 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1954 Asm->OutStreamer.EmitSymbolValue(End, Size);
1958 // And terminate the list with two 0 values.
1959 Asm->OutStreamer.EmitIntValue(0, Size);
1960 Asm->OutStreamer.EmitIntValue(0, Size);
1965 // DWARF5 Experimental Separate Dwarf emitters.
1967 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1968 std::unique_ptr<DwarfUnit> NewU) {
1969 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1970 U.getCUNode().getSplitDebugFilename());
1972 if (!CompilationDir.empty())
1973 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1975 addGnuPubAttributes(*NewU, Die);
1977 SkeletonHolder.addUnit(std::move(NewU));
1980 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1981 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1982 // DW_AT_addr_base, DW_AT_ranges_base.
1983 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1985 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1986 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1987 DwarfCompileUnit &NewCU = *OwnedUnit;
1988 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
1989 DwarfInfoSectionSym);
1991 NewCU.initStmtList(DwarfLineSectionSym);
1993 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1998 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1999 // compile units that would normally be in debug_info.
2000 void DwarfDebug::emitDebugInfoDWO() {
2001 assert(useSplitDwarf() && "No split dwarf debug info?");
2002 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2003 // emit relocations into the dwo file.
2004 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2007 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2008 // abbreviations for the .debug_info.dwo section.
2009 void DwarfDebug::emitDebugAbbrevDWO() {
2010 assert(useSplitDwarf() && "No split dwarf?");
2011 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2014 void DwarfDebug::emitDebugLineDWO() {
2015 assert(useSplitDwarf() && "No split dwarf?");
2016 Asm->OutStreamer.SwitchSection(
2017 Asm->getObjFileLowering().getDwarfLineDWOSection());
2018 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2021 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2022 // string section and is identical in format to traditional .debug_str
2024 void DwarfDebug::emitDebugStrDWO() {
2025 assert(useSplitDwarf() && "No split dwarf?");
2026 const MCSection *OffSec =
2027 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2028 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2032 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2033 if (!useSplitDwarf())
2036 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2037 return &SplitTypeUnitFileTable;
2040 static uint64_t makeTypeSignature(StringRef Identifier) {
2042 Hash.update(Identifier);
2043 // ... take the least significant 8 bytes and return those. Our MD5
2044 // implementation always returns its results in little endian, swap bytes
2046 MD5::MD5Result Result;
2048 return support::endian::read64le(Result + 8);
2051 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2052 StringRef Identifier, DIE &RefDie,
2053 DICompositeType CTy) {
2054 // Fast path if we're building some type units and one has already used the
2055 // address pool we know we're going to throw away all this work anyway, so
2056 // don't bother building dependent types.
2057 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2060 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2062 CU.addDIETypeSignature(RefDie, *TU);
2066 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2067 AddrPool.resetUsedFlag();
2069 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2070 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2071 this, &InfoHolder, getDwoLineTable(CU));
2072 DwarfTypeUnit &NewTU = *OwnedUnit;
2073 DIE &UnitDie = NewTU.getUnitDie();
2075 TypeUnitsUnderConstruction.push_back(
2076 std::make_pair(std::move(OwnedUnit), CTy));
2078 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2081 uint64_t Signature = makeTypeSignature(Identifier);
2082 NewTU.setTypeSignature(Signature);
2084 if (useSplitDwarf())
2085 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2087 CU.applyStmtList(UnitDie);
2089 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2092 NewTU.setType(NewTU.createTypeDIE(CTy));
2095 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2096 TypeUnitsUnderConstruction.clear();
2098 // Types referencing entries in the address table cannot be placed in type
2100 if (AddrPool.hasBeenUsed()) {
2102 // Remove all the types built while building this type.
2103 // This is pessimistic as some of these types might not be dependent on
2104 // the type that used an address.
2105 for (const auto &TU : TypeUnitsToAdd)
2106 DwarfTypeUnits.erase(TU.second);
2108 // Construct this type in the CU directly.
2109 // This is inefficient because all the dependent types will be rebuilt
2110 // from scratch, including building them in type units, discovering that
2111 // they depend on addresses, throwing them out and rebuilding them.
2112 CU.constructTypeDIE(RefDie, CTy);
2116 // If the type wasn't dependent on fission addresses, finish adding the type
2117 // and all its dependent types.
2118 for (auto &TU : TypeUnitsToAdd)
2119 InfoHolder.addUnit(std::move(TU.first));
2121 CU.addDIETypeSignature(RefDie, NewTU);
2124 // Accelerator table mutators - add each name along with its companion
2125 // DIE to the proper table while ensuring that the name that we're going
2126 // to reference is in the string table. We do this since the names we
2127 // add may not only be identical to the names in the DIE.
2128 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2129 if (!useDwarfAccelTables())
2131 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2135 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2136 if (!useDwarfAccelTables())
2138 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2142 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2143 if (!useDwarfAccelTables())
2145 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2149 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2150 if (!useDwarfAccelTables())
2152 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),