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 // Add the various names to the Dwarf accelerator table names.
291 // TODO: Determine whether or not we should add names for programs
292 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
293 // is only slightly different than the lookup of non-standard ObjC names.
294 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
295 if (!SP.isDefinition())
297 addAccelName(SP.getName(), Die);
299 // If the linkage name is different than the name, go ahead and output
300 // that as well into the name table.
301 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
302 addAccelName(SP.getLinkageName(), Die);
304 // If this is an Objective-C selector name add it to the ObjC accelerator
306 if (isObjCClass(SP.getName())) {
307 StringRef Class, Category;
308 getObjCClassCategory(SP.getName(), Class, Category);
309 addAccelObjC(Class, Die);
311 addAccelObjC(Category, Die);
312 // Also add the base method name to the name table.
313 addAccelName(getObjCMethodName(SP.getName()), Die);
317 /// isSubprogramContext - Return true if Context is either a subprogram
318 /// or another context nested inside a subprogram.
319 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
322 DIDescriptor D(Context);
323 if (D.isSubprogram())
326 return isSubprogramContext(resolve(DIType(Context).getContext()));
330 /// Check whether we should create a DIE for the given Scope, return true
331 /// if we don't create a DIE (the corresponding DIE is null).
332 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
333 if (Scope->isAbstractScope())
336 // We don't create a DIE if there is no Range.
337 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
341 if (Ranges.size() > 1)
344 // We don't create a DIE if we have a single Range and the end label
346 return !getLabelAfterInsn(Ranges.front().second);
349 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
351 if (auto *SkelCU = CU.getSkeleton())
355 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
356 assert(Scope && Scope->getScopeNode());
357 assert(Scope->isAbstractScope());
358 assert(!Scope->getInlinedAt());
360 const MDNode *SP = Scope->getScopeNode();
362 ProcessedSPNodes.insert(SP);
364 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
365 // was inlined from another compile unit.
366 auto &CU = SPMap[SP];
367 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
368 CU.constructAbstractSubprogramScopeDIE(Scope);
372 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
373 if (!GenerateGnuPubSections)
376 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
379 // Create new DwarfCompileUnit for the given metadata node with tag
380 // DW_TAG_compile_unit.
381 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
382 StringRef FN = DIUnit.getFilename();
383 CompilationDir = DIUnit.getDirectory();
385 auto OwnedUnit = make_unique<DwarfCompileUnit>(
386 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
387 DwarfCompileUnit &NewCU = *OwnedUnit;
388 DIE &Die = NewCU.getUnitDie();
389 InfoHolder.addUnit(std::move(OwnedUnit));
391 NewCU.setSkeleton(constructSkeletonCU(NewCU));
393 // LTO with assembly output shares a single line table amongst multiple CUs.
394 // To avoid the compilation directory being ambiguous, let the line table
395 // explicitly describe the directory of all files, never relying on the
396 // compilation directory.
397 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
398 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
399 NewCU.getUniqueID(), CompilationDir);
401 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
402 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
403 DIUnit.getLanguage());
404 NewCU.addString(Die, dwarf::DW_AT_name, FN);
406 if (!useSplitDwarf()) {
407 NewCU.initStmtList(DwarfLineSectionSym);
409 // If we're using split dwarf the compilation dir is going to be in the
410 // skeleton CU and so we don't need to duplicate it here.
411 if (!CompilationDir.empty())
412 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
414 addGnuPubAttributes(NewCU, Die);
417 if (DIUnit.isOptimized())
418 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
420 StringRef Flags = DIUnit.getFlags();
422 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
424 if (unsigned RVer = DIUnit.getRunTimeVersion())
425 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
426 dwarf::DW_FORM_data1, RVer);
429 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
430 DwarfInfoDWOSectionSym);
432 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
433 DwarfInfoSectionSym);
435 CUMap.insert(std::make_pair(DIUnit, &NewCU));
436 CUDieMap.insert(std::make_pair(&Die, &NewCU));
440 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
442 DIImportedEntity Module(N);
443 assert(Module.Verify());
444 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
445 D->addChild(TheCU.constructImportedEntityDIE(Module));
448 // Emit all Dwarf sections that should come prior to the content. Create
449 // global DIEs and emit initial debug info sections. This is invoked by
450 // the target AsmPrinter.
451 void DwarfDebug::beginModule() {
452 if (DisableDebugInfoPrinting)
455 const Module *M = MMI->getModule();
457 FunctionDIs = makeSubprogramMap(*M);
459 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
462 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
464 // Emit initial sections so we can reference labels later.
467 SingleCU = CU_Nodes->getNumOperands() == 1;
469 for (MDNode *N : CU_Nodes->operands()) {
470 DICompileUnit CUNode(N);
471 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
472 DIArray ImportedEntities = CUNode.getImportedEntities();
473 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
474 ScopesWithImportedEntities.push_back(std::make_pair(
475 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
476 ImportedEntities.getElement(i)));
477 // Stable sort to preserve the order of appearance of imported entities.
478 // This is to avoid out-of-order processing of interdependent declarations
479 // within the same scope, e.g. { namespace A = base; namespace B = A; }
480 std::stable_sort(ScopesWithImportedEntities.begin(),
481 ScopesWithImportedEntities.end(), less_first());
482 DIArray GVs = CUNode.getGlobalVariables();
483 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
484 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
485 DIArray SPs = CUNode.getSubprograms();
486 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
487 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
488 DIArray EnumTypes = CUNode.getEnumTypes();
489 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
490 DIType Ty(EnumTypes.getElement(i));
491 // The enum types array by design contains pointers to
492 // MDNodes rather than DIRefs. Unique them here.
493 DIType UniqueTy(resolve(Ty.getRef()));
494 CU.getOrCreateTypeDIE(UniqueTy);
496 DIArray RetainedTypes = CUNode.getRetainedTypes();
497 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
498 DIType Ty(RetainedTypes.getElement(i));
499 // The retained types array by design contains pointers to
500 // MDNodes rather than DIRefs. Unique them here.
501 DIType UniqueTy(resolve(Ty.getRef()));
502 CU.getOrCreateTypeDIE(UniqueTy);
504 // Emit imported_modules last so that the relevant context is already
506 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
507 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
510 // Tell MMI that we have debug info.
511 MMI->setDebugInfoAvailability(true);
514 void DwarfDebug::finishVariableDefinitions() {
515 for (const auto &Var : ConcreteVariables) {
516 DIE *VariableDie = Var->getDIE();
518 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
519 // in the ConcreteVariables list, rather than looking it up again here.
520 // DIE::getUnit isn't simple - it walks parent pointers, etc.
521 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
523 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
524 if (AbsVar && AbsVar->getDIE()) {
525 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
528 Unit->applyVariableAttributes(*Var, *VariableDie);
532 void DwarfDebug::finishSubprogramDefinitions() {
533 for (const auto &P : SPMap)
534 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
535 CU.finishSubprogramDefinition(DISubprogram(P.first));
540 // Collect info for variables that were optimized out.
541 void DwarfDebug::collectDeadVariables() {
542 const Module *M = MMI->getModule();
544 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
545 for (MDNode *N : CU_Nodes->operands()) {
546 DICompileUnit TheCU(N);
547 // Construct subprogram DIE and add variables DIEs.
548 DwarfCompileUnit *SPCU =
549 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
550 assert(SPCU && "Unable to find Compile Unit!");
551 DIArray Subprograms = TheCU.getSubprograms();
552 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
553 DISubprogram SP(Subprograms.getElement(i));
554 if (ProcessedSPNodes.count(SP) != 0)
556 SPCU->collectDeadVariables(SP);
562 void DwarfDebug::finalizeModuleInfo() {
563 finishSubprogramDefinitions();
565 finishVariableDefinitions();
567 // Collect info for variables that were optimized out.
568 collectDeadVariables();
570 // Handle anything that needs to be done on a per-unit basis after
571 // all other generation.
572 for (const auto &P : CUMap) {
573 auto &TheCU = *P.second;
574 // Emit DW_AT_containing_type attribute to connect types with their
575 // vtable holding type.
576 TheCU.constructContainingTypeDIEs();
578 // Add CU specific attributes if we need to add any.
579 // If we're splitting the dwarf out now that we've got the entire
580 // CU then add the dwo id to it.
581 auto *SkCU = TheCU.getSkeleton();
582 if (useSplitDwarf()) {
583 // Emit a unique identifier for this CU.
584 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
585 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
586 dwarf::DW_FORM_data8, ID);
587 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
588 dwarf::DW_FORM_data8, ID);
590 // We don't keep track of which addresses are used in which CU so this
591 // is a bit pessimistic under LTO.
592 if (!AddrPool.isEmpty())
593 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
594 DwarfAddrSectionSym, DwarfAddrSectionSym);
595 if (!SkCU->getRangeLists().empty())
596 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
597 DwarfDebugRangeSectionSym,
598 DwarfDebugRangeSectionSym);
601 // If we have code split among multiple sections or non-contiguous
602 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
603 // remain in the .o file, otherwise add a DW_AT_low_pc.
604 // FIXME: We should use ranges allow reordering of code ala
605 // .subsections_via_symbols in mach-o. This would mean turning on
606 // ranges for all subprogram DIEs for mach-o.
607 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
608 if (unsigned NumRanges = TheCU.getRanges().size()) {
610 // A DW_AT_low_pc attribute may also be specified in combination with
611 // DW_AT_ranges to specify the default base address for use in
612 // location lists (see Section 2.6.2) and range lists (see Section
614 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
616 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
617 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
621 // Compute DIE offsets and sizes.
622 InfoHolder.computeSizeAndOffsets();
624 SkeletonHolder.computeSizeAndOffsets();
627 // Emit all Dwarf sections that should come after the content.
628 void DwarfDebug::endModule() {
629 assert(CurFn == nullptr);
630 assert(CurMI == nullptr);
632 // If we aren't actually generating debug info (check beginModule -
633 // conditionalized on !DisableDebugInfoPrinting and the presence of the
634 // llvm.dbg.cu metadata node)
635 if (!DwarfInfoSectionSym)
638 // Finalize the debug info for the module.
639 finalizeModuleInfo();
643 // Emit all the DIEs into a debug info section.
646 // Corresponding abbreviations into a abbrev section.
649 // Emit info into a debug aranges section.
650 if (GenerateARangeSection)
653 // Emit info into a debug ranges section.
656 if (useSplitDwarf()) {
659 emitDebugAbbrevDWO();
662 // Emit DWO addresses.
663 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
665 // Emit info into a debug loc section.
668 // Emit info into the dwarf accelerator table sections.
669 if (useDwarfAccelTables()) {
672 emitAccelNamespaces();
676 // Emit the pubnames and pubtypes sections if requested.
677 if (HasDwarfPubSections) {
678 emitDebugPubNames(GenerateGnuPubSections);
679 emitDebugPubTypes(GenerateGnuPubSections);
684 AbstractVariables.clear();
687 // Find abstract variable, if any, associated with Var.
688 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
689 DIVariable &Cleansed) {
690 LLVMContext &Ctx = DV->getContext();
691 // More then one inlined variable corresponds to one abstract variable.
692 // FIXME: This duplication of variables when inlining should probably be
693 // removed. It's done to allow each DIVariable to describe its location
694 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
695 // make it accurate then remove this duplication/cleansing stuff.
696 Cleansed = cleanseInlinedVariable(DV, Ctx);
697 auto I = AbstractVariables.find(Cleansed);
698 if (I != AbstractVariables.end())
699 return I->second.get();
703 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
705 return getExistingAbstractVariable(DV, Cleansed);
708 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
709 LexicalScope *Scope) {
710 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
711 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
712 AbstractVariables[Var] = std::move(AbsDbgVariable);
715 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
716 const MDNode *ScopeNode) {
717 DIVariable Cleansed = DV;
718 if (getExistingAbstractVariable(DV, Cleansed))
721 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
725 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
726 const MDNode *ScopeNode) {
727 DIVariable Cleansed = DV;
728 if (getExistingAbstractVariable(DV, Cleansed))
731 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
732 createAbstractVariable(Cleansed, Scope);
735 // Collect variable information from side table maintained by MMI.
736 void DwarfDebug::collectVariableInfoFromMMITable(
737 SmallPtrSetImpl<const MDNode *> &Processed) {
738 for (const auto &VI : MMI->getVariableDbgInfo()) {
741 Processed.insert(VI.Var);
742 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
744 // If variable scope is not found then skip this variable.
748 DIVariable DV(VI.Var);
749 DIExpression Expr(VI.Expr);
750 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
751 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
752 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
753 ConcreteVariables.push_back(std::move(RegVar));
757 // Get .debug_loc entry for the instruction range starting at MI.
758 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
759 const MDNode *Expr = MI->getDebugExpression();
760 const MDNode *Var = MI->getDebugVariable();
762 assert(MI->getNumOperands() == 4);
763 if (MI->getOperand(0).isReg()) {
764 MachineLocation MLoc;
765 // If the second operand is an immediate, this is a
766 // register-indirect address.
767 if (!MI->getOperand(1).isImm())
768 MLoc.set(MI->getOperand(0).getReg());
770 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
771 return DebugLocEntry::Value(Var, Expr, MLoc);
773 if (MI->getOperand(0).isImm())
774 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
775 if (MI->getOperand(0).isFPImm())
776 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
777 if (MI->getOperand(0).isCImm())
778 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
780 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
783 /// Determine whether two variable pieces overlap.
784 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
785 if (!P1.isBitPiece() || !P2.isBitPiece())
787 unsigned l1 = P1.getBitPieceOffset();
788 unsigned l2 = P2.getBitPieceOffset();
789 unsigned r1 = l1 + P1.getBitPieceSize();
790 unsigned r2 = l2 + P2.getBitPieceSize();
791 // True where [l1,r1[ and [r1,r2[ overlap.
792 return (l1 < r2) && (l2 < r1);
795 /// Build the location list for all DBG_VALUEs in the function that
796 /// describe the same variable. If the ranges of several independent
797 /// pieces of the same variable overlap partially, split them up and
798 /// combine the ranges. The resulting DebugLocEntries are will have
799 /// strict monotonically increasing begin addresses and will never
804 // Ranges History [var, loc, piece ofs size]
805 // 0 | [x, (reg0, piece 0, 32)]
806 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
808 // 3 | [clobber reg0]
809 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
814 // [0-1] [x, (reg0, piece 0, 32)]
815 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
816 // [3-4] [x, (reg1, piece 32, 32)]
817 // [4- ] [x, (mem, piece 0, 64)]
819 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
820 const DbgValueHistoryMap::InstrRanges &Ranges) {
821 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
823 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
824 const MachineInstr *Begin = I->first;
825 const MachineInstr *End = I->second;
826 assert(Begin->isDebugValue() && "Invalid History entry");
828 // Check if a variable is inaccessible in this range.
829 if (Begin->getNumOperands() > 1 &&
830 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
835 // If this piece overlaps with any open ranges, truncate them.
836 DIExpression DIExpr = Begin->getDebugExpression();
837 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
838 [&](DebugLocEntry::Value R) {
839 return piecesOverlap(DIExpr, R.getExpression());
841 OpenRanges.erase(Last, OpenRanges.end());
843 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
844 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
846 const MCSymbol *EndLabel;
848 EndLabel = getLabelAfterInsn(End);
849 else if (std::next(I) == Ranges.end())
850 EndLabel = Asm->getFunctionEnd();
852 EndLabel = getLabelBeforeInsn(std::next(I)->first);
853 assert(EndLabel && "Forgot label after instruction ending a range!");
855 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
857 auto Value = getDebugLocValue(Begin);
858 DebugLocEntry Loc(StartLabel, EndLabel, Value);
859 bool couldMerge = false;
861 // If this is a piece, it may belong to the current DebugLocEntry.
862 if (DIExpr.isBitPiece()) {
863 // Add this value to the list of open ranges.
864 OpenRanges.push_back(Value);
866 // Attempt to add the piece to the last entry.
867 if (!DebugLoc.empty())
868 if (DebugLoc.back().MergeValues(Loc))
873 // Need to add a new DebugLocEntry. Add all values from still
874 // valid non-overlapping pieces.
875 if (OpenRanges.size())
876 Loc.addValues(OpenRanges);
878 DebugLoc.push_back(std::move(Loc));
881 // Attempt to coalesce the ranges of two otherwise identical
883 auto CurEntry = DebugLoc.rbegin();
884 auto PrevEntry = std::next(CurEntry);
885 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
889 dbgs() << CurEntry->getValues().size() << " Values:\n";
890 for (auto Value : CurEntry->getValues()) {
891 Value.getVariable()->dump();
892 Value.getExpression()->dump();
900 // Find variables for each lexical scope.
902 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
903 SmallPtrSetImpl<const MDNode *> &Processed) {
904 // Grab the variable info that was squirreled away in the MMI side-table.
905 collectVariableInfoFromMMITable(Processed);
907 for (const auto &I : DbgValues) {
908 DIVariable DV(I.first);
909 if (Processed.count(DV))
912 // Instruction ranges, specifying where DV is accessible.
913 const auto &Ranges = I.second;
917 LexicalScope *Scope = nullptr;
918 if (MDNode *IA = DV.getInlinedAt())
919 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
921 Scope = LScopes.findLexicalScope(DV.getContext());
922 // If variable scope is not found then skip this variable.
926 Processed.insert(DV);
927 const MachineInstr *MInsn = Ranges.front().first;
928 assert(MInsn->isDebugValue() && "History must begin with debug value");
929 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
930 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
931 DbgVariable *RegVar = ConcreteVariables.back().get();
932 InfoHolder.addScopeVariable(Scope, RegVar);
934 // Check if the first DBG_VALUE is valid for the rest of the function.
935 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
938 // Handle multiple DBG_VALUE instructions describing one variable.
939 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
941 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
942 DebugLocList &LocList = DotDebugLocEntries.back();
945 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
947 // Build the location list for this variable.
948 buildLocationList(LocList.List, Ranges);
949 // Finalize the entry by lowering it into a DWARF bytestream.
950 for (auto &Entry : LocList.List)
951 Entry.finalize(*Asm, TypeIdentifierMap);
954 // Collect info for variables that were optimized out.
955 DIArray Variables = SP.getVariables();
956 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
957 DIVariable DV(Variables.getElement(i));
958 assert(DV.isVariable());
959 if (!Processed.insert(DV).second)
961 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
962 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
964 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
965 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
970 // Return Label preceding the instruction.
971 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
972 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
973 assert(Label && "Didn't insert label before instruction");
977 // Return Label immediately following the instruction.
978 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
979 return LabelsAfterInsn.lookup(MI);
982 // Process beginning of an instruction.
983 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
984 assert(CurMI == nullptr);
986 // Check if source location changes, but ignore DBG_VALUE locations.
987 if (!MI->isDebugValue()) {
988 DebugLoc DL = MI->getDebugLoc();
989 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
992 if (DL == PrologEndLoc) {
993 Flags |= DWARF2_FLAG_PROLOGUE_END;
994 PrologEndLoc = DebugLoc();
995 Flags |= DWARF2_FLAG_IS_STMT;
998 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
999 Flags |= DWARF2_FLAG_IS_STMT;
1001 if (!DL.isUnknown()) {
1002 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1003 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1005 recordSourceLine(0, 0, nullptr, 0);
1009 // Insert labels where requested.
1010 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1011 LabelsBeforeInsn.find(MI);
1014 if (I == LabelsBeforeInsn.end())
1017 // Label already assigned.
1022 PrevLabel = MMI->getContext().CreateTempSymbol();
1023 Asm->OutStreamer.EmitLabel(PrevLabel);
1025 I->second = PrevLabel;
1028 // Process end of an instruction.
1029 void DwarfDebug::endInstruction() {
1030 assert(CurMI != nullptr);
1031 // Don't create a new label after DBG_VALUE instructions.
1032 // They don't generate code.
1033 if (!CurMI->isDebugValue())
1034 PrevLabel = nullptr;
1036 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1037 LabelsAfterInsn.find(CurMI);
1041 if (I == LabelsAfterInsn.end())
1044 // Label already assigned.
1048 // We need a label after this instruction.
1050 PrevLabel = MMI->getContext().CreateTempSymbol();
1051 Asm->OutStreamer.EmitLabel(PrevLabel);
1053 I->second = PrevLabel;
1056 // Each LexicalScope has first instruction and last instruction to mark
1057 // beginning and end of a scope respectively. Create an inverse map that list
1058 // scopes starts (and ends) with an instruction. One instruction may start (or
1059 // end) multiple scopes. Ignore scopes that are not reachable.
1060 void DwarfDebug::identifyScopeMarkers() {
1061 SmallVector<LexicalScope *, 4> WorkList;
1062 WorkList.push_back(LScopes.getCurrentFunctionScope());
1063 while (!WorkList.empty()) {
1064 LexicalScope *S = WorkList.pop_back_val();
1066 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1067 if (!Children.empty())
1068 WorkList.append(Children.begin(), Children.end());
1070 if (S->isAbstractScope())
1073 for (const InsnRange &R : S->getRanges()) {
1074 assert(R.first && "InsnRange does not have first instruction!");
1075 assert(R.second && "InsnRange does not have second instruction!");
1076 requestLabelBeforeInsn(R.first);
1077 requestLabelAfterInsn(R.second);
1082 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1083 // First known non-DBG_VALUE and non-frame setup location marks
1084 // the beginning of the function body.
1085 for (const auto &MBB : *MF)
1086 for (const auto &MI : MBB)
1087 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1088 !MI.getDebugLoc().isUnknown()) {
1089 // Did the target forget to set the FrameSetup flag for CFI insns?
1090 assert(!MI.isCFIInstruction() &&
1091 "First non-frame-setup instruction is a CFI instruction.");
1092 return MI.getDebugLoc();
1097 // Gather pre-function debug information. Assumes being called immediately
1098 // after the function entry point has been emitted.
1099 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1102 // If there's no debug info for the function we're not going to do anything.
1103 if (!MMI->hasDebugInfo())
1106 auto DI = FunctionDIs.find(MF->getFunction());
1107 if (DI == FunctionDIs.end())
1110 // Grab the lexical scopes for the function, if we don't have any of those
1111 // then we're not going to be able to do anything.
1112 LScopes.initialize(*MF);
1113 if (LScopes.empty())
1116 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1118 // Make sure that each lexical scope will have a begin/end label.
1119 identifyScopeMarkers();
1121 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1122 // belongs to so that we add to the correct per-cu line table in the
1124 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1125 // FnScope->getScopeNode() and DI->second should represent the same function,
1126 // though they may not be the same MDNode due to inline functions merged in
1127 // LTO where the debug info metadata still differs (either due to distinct
1128 // written differences - two versions of a linkonce_odr function
1129 // written/copied into two separate files, or some sub-optimal metadata that
1130 // isn't structurally identical (see: file path/name info from clang, which
1131 // includes the directory of the cpp file being built, even when the file name
1132 // is absolute (such as an <> lookup header)))
1133 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1134 assert(TheCU && "Unable to find compile unit!");
1135 if (Asm->OutStreamer.hasRawTextSupport())
1136 // Use a single line table if we are generating assembly.
1137 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1139 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1141 // Calculate history for local variables.
1142 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1145 // Request labels for the full history.
1146 for (const auto &I : DbgValues) {
1147 const auto &Ranges = I.second;
1151 // The first mention of a function argument gets the CurrentFnBegin
1152 // label, so arguments are visible when breaking at function entry.
1153 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1154 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1155 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1156 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1157 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1158 // Mark all non-overlapping initial pieces.
1159 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1160 DIExpression Piece = I->first->getDebugExpression();
1161 if (std::all_of(Ranges.begin(), I,
1162 [&](DbgValueHistoryMap::InstrRange Pred) {
1163 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1165 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1172 for (const auto &Range : Ranges) {
1173 requestLabelBeforeInsn(Range.first);
1175 requestLabelAfterInsn(Range.second);
1179 PrevInstLoc = DebugLoc();
1180 PrevLabel = Asm->getFunctionBegin();
1182 // Record beginning of function.
1183 PrologEndLoc = findPrologueEndLoc(MF);
1184 if (!PrologEndLoc.isUnknown()) {
1185 DebugLoc FnStartDL =
1186 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1188 // We'd like to list the prologue as "not statements" but GDB behaves
1189 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1190 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1191 FnStartDL.getScope(MF->getFunction()->getContext()),
1192 DWARF2_FLAG_IS_STMT);
1196 // Gather and emit post-function debug information.
1197 void DwarfDebug::endFunction(const MachineFunction *MF) {
1198 assert(CurFn == MF &&
1199 "endFunction should be called with the same function as beginFunction");
1201 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1202 !FunctionDIs.count(MF->getFunction())) {
1203 // If we don't have a lexical scope for this function then there will
1204 // be a hole in the range information. Keep note of this by setting the
1205 // previously used section to nullptr.
1211 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1212 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1214 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1215 DISubprogram SP(FnScope->getScopeNode());
1216 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1218 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1219 collectVariableInfo(TheCU, SP, ProcessedVars);
1221 // Add the range of this function to the list of ranges for the CU.
1222 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1224 // Under -gmlt, skip building the subprogram if there are no inlined
1225 // subroutines inside it.
1226 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1227 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1228 assert(InfoHolder.getScopeVariables().empty());
1229 assert(DbgValues.empty());
1230 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1231 // by a -gmlt CU. Add a test and remove this assertion.
1232 assert(AbstractVariables.empty());
1233 LabelsBeforeInsn.clear();
1234 LabelsAfterInsn.clear();
1235 PrevLabel = nullptr;
1241 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1243 // Construct abstract scopes.
1244 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1245 DISubprogram SP(AScope->getScopeNode());
1246 assert(SP.isSubprogram());
1247 // Collect info for variables that were optimized out.
1248 DIArray Variables = SP.getVariables();
1249 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1250 DIVariable DV(Variables.getElement(i));
1251 assert(DV && DV.isVariable());
1252 if (!ProcessedVars.insert(DV).second)
1254 ensureAbstractVariableIsCreated(DV, DV.getContext());
1255 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1256 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1258 constructAbstractSubprogramScopeDIE(AScope);
1261 TheCU.constructSubprogramScopeDIE(FnScope);
1262 if (auto *SkelCU = TheCU.getSkeleton())
1263 if (!LScopes.getAbstractScopesList().empty())
1264 SkelCU->constructSubprogramScopeDIE(FnScope);
1267 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1268 // DbgVariables except those that are also in AbstractVariables (since they
1269 // can be used cross-function)
1270 InfoHolder.getScopeVariables().clear();
1272 LabelsBeforeInsn.clear();
1273 LabelsAfterInsn.clear();
1274 PrevLabel = nullptr;
1278 // Register a source line with debug info. Returns the unique label that was
1279 // emitted and which provides correspondence to the source line list.
1280 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1285 unsigned Discriminator = 0;
1286 if (DIScope Scope = DIScope(S)) {
1287 assert(Scope.isScope());
1288 Fn = Scope.getFilename();
1289 Dir = Scope.getDirectory();
1290 if (Scope.isLexicalBlockFile())
1291 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1293 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1294 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1295 .getOrCreateSourceID(Fn, Dir);
1297 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1301 //===----------------------------------------------------------------------===//
1303 //===----------------------------------------------------------------------===//
1305 // Emit initial Dwarf sections with a label at the start of each one.
1306 void DwarfDebug::emitSectionLabels() {
1307 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1309 // Dwarf sections base addresses.
1310 DwarfInfoSectionSym =
1311 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1312 if (useSplitDwarf()) {
1313 DwarfInfoDWOSectionSym =
1314 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1315 DwarfTypesDWOSectionSym = emitSectionSym(
1316 Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1318 DwarfAbbrevSectionSym =
1319 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1320 if (useSplitDwarf())
1321 DwarfAbbrevDWOSectionSym = emitSectionSym(
1322 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1323 if (GenerateARangeSection)
1324 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1326 DwarfLineSectionSym =
1327 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1328 if (GenerateGnuPubSections) {
1329 DwarfGnuPubNamesSectionSym =
1330 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1331 DwarfGnuPubTypesSectionSym =
1332 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1333 } else if (HasDwarfPubSections) {
1334 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1335 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1338 DwarfStrSectionSym =
1339 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1340 if (useSplitDwarf()) {
1341 DwarfStrDWOSectionSym =
1342 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1343 DwarfAddrSectionSym =
1344 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1345 DwarfDebugLocSectionSym =
1346 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1348 DwarfDebugLocSectionSym =
1349 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1350 DwarfDebugRangeSectionSym =
1351 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1354 // Emit the debug info section.
1355 void DwarfDebug::emitDebugInfo() {
1356 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1358 Holder.emitUnits(DwarfAbbrevSectionSym);
1361 // Emit the abbreviation section.
1362 void DwarfDebug::emitAbbreviations() {
1363 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1365 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1368 // Emit the last address of the section and the end of the line matrix.
1369 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1370 // Define last address of section.
1371 Asm->OutStreamer.AddComment("Extended Op");
1374 Asm->OutStreamer.AddComment("Op size");
1375 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1376 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1377 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1379 Asm->OutStreamer.AddComment("Section end label");
1381 Asm->OutStreamer.EmitSymbolValue(
1382 Asm->GetTempSymbol("section_end", SectionEnd),
1383 Asm->getDataLayout().getPointerSize());
1385 // Mark end of matrix.
1386 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1392 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1393 StringRef TableName, StringRef SymName) {
1394 Accel.FinalizeTable(Asm, TableName);
1395 Asm->OutStreamer.SwitchSection(Section);
1396 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1397 Asm->OutStreamer.EmitLabel(SectionBegin);
1399 // Emit the full data.
1400 Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1403 // Emit visible names into a hashed accelerator table section.
1404 void DwarfDebug::emitAccelNames() {
1405 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1406 "Names", "names_begin");
1409 // Emit objective C classes and categories into a hashed accelerator table
1411 void DwarfDebug::emitAccelObjC() {
1412 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1413 "ObjC", "objc_begin");
1416 // Emit namespace dies into a hashed accelerator table.
1417 void DwarfDebug::emitAccelNamespaces() {
1418 emitAccel(AccelNamespace,
1419 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1420 "namespac", "namespac_begin");
1423 // Emit type dies into a hashed accelerator table.
1424 void DwarfDebug::emitAccelTypes() {
1425 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1426 "types", "types_begin");
1429 // Public name handling.
1430 // The format for the various pubnames:
1432 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1433 // for the DIE that is named.
1435 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1436 // into the CU and the index value is computed according to the type of value
1437 // for the DIE that is named.
1439 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1440 // it's the offset within the debug_info/debug_types dwo section, however, the
1441 // reference in the pubname header doesn't change.
1443 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1444 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1446 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1448 // We could have a specification DIE that has our most of our knowledge,
1449 // look for that now.
1450 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1452 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1453 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1454 Linkage = dwarf::GIEL_EXTERNAL;
1455 } else if (Die->findAttribute(dwarf::DW_AT_external))
1456 Linkage = dwarf::GIEL_EXTERNAL;
1458 switch (Die->getTag()) {
1459 case dwarf::DW_TAG_class_type:
1460 case dwarf::DW_TAG_structure_type:
1461 case dwarf::DW_TAG_union_type:
1462 case dwarf::DW_TAG_enumeration_type:
1463 return dwarf::PubIndexEntryDescriptor(
1464 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1465 ? dwarf::GIEL_STATIC
1466 : dwarf::GIEL_EXTERNAL);
1467 case dwarf::DW_TAG_typedef:
1468 case dwarf::DW_TAG_base_type:
1469 case dwarf::DW_TAG_subrange_type:
1470 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1471 case dwarf::DW_TAG_namespace:
1472 return dwarf::GIEK_TYPE;
1473 case dwarf::DW_TAG_subprogram:
1474 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1475 case dwarf::DW_TAG_variable:
1476 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1477 case dwarf::DW_TAG_enumerator:
1478 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1479 dwarf::GIEL_STATIC);
1481 return dwarf::GIEK_NONE;
1485 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1487 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1488 const MCSection *PSec =
1489 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1490 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1492 emitDebugPubSection(GnuStyle, PSec, "Names",
1493 &DwarfCompileUnit::getGlobalNames);
1496 void DwarfDebug::emitDebugPubSection(
1497 bool GnuStyle, const MCSection *PSec, StringRef Name,
1498 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1499 for (const auto &NU : CUMap) {
1500 DwarfCompileUnit *TheU = NU.second;
1502 const auto &Globals = (TheU->*Accessor)();
1504 if (Globals.empty())
1507 if (auto *Skeleton = TheU->getSkeleton())
1509 unsigned ID = TheU->getUniqueID();
1511 // Start the dwarf pubnames section.
1512 Asm->OutStreamer.SwitchSection(PSec);
1515 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1516 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1517 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1518 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1520 Asm->OutStreamer.EmitLabel(BeginLabel);
1522 Asm->OutStreamer.AddComment("DWARF Version");
1523 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1525 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1526 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1528 Asm->OutStreamer.AddComment("Compilation Unit Length");
1529 Asm->EmitInt32(TheU->getLength());
1531 // Emit the pubnames for this compilation unit.
1532 for (const auto &GI : Globals) {
1533 const char *Name = GI.getKeyData();
1534 const DIE *Entity = GI.second;
1536 Asm->OutStreamer.AddComment("DIE offset");
1537 Asm->EmitInt32(Entity->getOffset());
1540 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1541 Asm->OutStreamer.AddComment(
1542 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1543 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1544 Asm->EmitInt8(Desc.toBits());
1547 Asm->OutStreamer.AddComment("External Name");
1548 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1551 Asm->OutStreamer.AddComment("End Mark");
1553 Asm->OutStreamer.EmitLabel(EndLabel);
1557 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1558 const MCSection *PSec =
1559 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1560 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1562 emitDebugPubSection(GnuStyle, PSec, "Types",
1563 &DwarfCompileUnit::getGlobalTypes);
1566 // Emit visible names into a debug str section.
1567 void DwarfDebug::emitDebugStr() {
1568 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1569 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1573 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1574 const DebugLocEntry &Entry) {
1575 auto Comment = Entry.getComments().begin();
1576 auto End = Entry.getComments().end();
1577 for (uint8_t Byte : Entry.getDWARFBytes())
1578 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1581 static void emitDebugLocValue(const AsmPrinter &AP,
1582 const DITypeIdentifierMap &TypeIdentifierMap,
1583 ByteStreamer &Streamer,
1584 const DebugLocEntry::Value &Value,
1585 unsigned PieceOffsetInBits) {
1586 DIVariable DV = Value.getVariable();
1587 DebugLocDwarfExpression DwarfExpr(
1588 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1589 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1591 if (Value.isInt()) {
1592 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1593 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1594 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1595 DwarfExpr.AddSignedConstant(Value.getInt());
1597 DwarfExpr.AddUnsignedConstant(Value.getInt());
1598 } else if (Value.isLocation()) {
1599 MachineLocation Loc = Value.getLoc();
1600 DIExpression Expr = Value.getExpression();
1601 if (!Expr || (Expr.getNumElements() == 0))
1603 AP.EmitDwarfRegOp(Streamer, Loc);
1605 // Complex address entry.
1606 if (Loc.getOffset()) {
1607 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1608 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1610 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1614 // else ... ignore constant fp. There is not any good way to
1615 // to represent them here in dwarf.
1620 void DebugLocEntry::finalize(const AsmPrinter &AP,
1621 const DITypeIdentifierMap &TypeIdentifierMap) {
1622 BufferByteStreamer Streamer(DWARFBytes, Comments);
1623 const DebugLocEntry::Value Value = Values[0];
1624 if (Value.isBitPiece()) {
1625 // Emit all pieces that belong to the same variable and range.
1626 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1627 return P.isBitPiece();
1628 }) && "all values are expected to be pieces");
1629 assert(std::is_sorted(Values.begin(), Values.end()) &&
1630 "pieces are expected to be sorted");
1632 unsigned Offset = 0;
1633 for (auto Piece : Values) {
1634 DIExpression Expr = Piece.getExpression();
1635 unsigned PieceOffset = Expr.getBitPieceOffset();
1636 unsigned PieceSize = Expr.getBitPieceSize();
1637 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1638 if (Offset < PieceOffset) {
1639 // The DWARF spec seriously mandates pieces with no locations for gaps.
1640 DebugLocDwarfExpression Expr(
1641 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1642 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1643 Expr.AddOpPiece(PieceOffset-Offset, 0);
1644 Offset += PieceOffset-Offset;
1646 Offset += PieceSize;
1649 DIVariable Var = Piece.getVariable();
1650 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1651 assert(PieceSize+PieceOffset <= VarSize
1652 && "piece is larger than or outside of variable");
1653 assert(PieceSize != VarSize
1654 && "piece covers entire variable");
1656 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1659 assert(Values.size() == 1 && "only pieces may have >1 value");
1660 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1665 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1666 Asm->OutStreamer.AddComment("Loc expr size");
1667 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1668 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1669 Asm->EmitLabelDifference(end, begin, 2);
1670 Asm->OutStreamer.EmitLabel(begin);
1672 APByteStreamer Streamer(*Asm);
1673 emitDebugLocEntry(Streamer, Entry);
1675 Asm->OutStreamer.EmitLabel(end);
1678 // Emit locations into the debug loc section.
1679 void DwarfDebug::emitDebugLoc() {
1680 // Start the dwarf loc section.
1681 Asm->OutStreamer.SwitchSection(
1682 Asm->getObjFileLowering().getDwarfLocSection());
1683 unsigned char Size = Asm->getDataLayout().getPointerSize();
1684 for (const auto &DebugLoc : DotDebugLocEntries) {
1685 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1686 const DwarfCompileUnit *CU = DebugLoc.CU;
1687 for (const auto &Entry : DebugLoc.List) {
1688 // Set up the range. This range is relative to the entry point of the
1689 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1690 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1691 if (auto *Base = CU->getBaseAddress()) {
1692 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1693 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1695 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1696 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1699 emitDebugLocEntryLocation(Entry);
1701 Asm->OutStreamer.EmitIntValue(0, Size);
1702 Asm->OutStreamer.EmitIntValue(0, Size);
1706 void DwarfDebug::emitDebugLocDWO() {
1707 Asm->OutStreamer.SwitchSection(
1708 Asm->getObjFileLowering().getDwarfLocDWOSection());
1709 for (const auto &DebugLoc : DotDebugLocEntries) {
1710 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1711 for (const auto &Entry : DebugLoc.List) {
1712 // Just always use start_length for now - at least that's one address
1713 // rather than two. We could get fancier and try to, say, reuse an
1714 // address we know we've emitted elsewhere (the start of the function?
1715 // The start of the CU or CU subrange that encloses this range?)
1716 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1717 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1718 Asm->EmitULEB128(idx);
1719 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1721 emitDebugLocEntryLocation(Entry);
1723 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1728 const MCSymbol *Start, *End;
1731 // Emit a debug aranges section, containing a CU lookup for any
1732 // address we can tie back to a CU.
1733 void DwarfDebug::emitDebugARanges() {
1734 // Provides a unique id per text section.
1735 MapVector<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1737 // Filter labels by section.
1738 for (const SymbolCU &SCU : ArangeLabels) {
1739 if (SCU.Sym->isInSection()) {
1740 // Make a note of this symbol and it's section.
1741 const MCSection *Section = &SCU.Sym->getSection();
1742 if (!Section->getKind().isMetadata())
1743 SectionMap[Section].push_back(SCU);
1745 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1746 // appear in the output. This sucks as we rely on sections to build
1747 // arange spans. We can do it without, but it's icky.
1748 SectionMap[nullptr].push_back(SCU);
1752 // Add terminating symbols for each section.
1754 for (const auto &I : SectionMap) {
1755 const MCSection *Section = I.first;
1756 MCSymbol *Sym = nullptr;
1759 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1760 // if we know the section name up-front. For user-created sections, the
1761 // resulting label may not be valid to use as a label. (section names can
1762 // use a greater set of characters on some systems)
1763 Sym = Asm->GetTempSymbol("debug_end", ID);
1764 Asm->OutStreamer.SwitchSection(Section);
1765 Asm->OutStreamer.EmitLabel(Sym);
1768 // Insert a final terminator.
1769 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1773 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1775 for (auto &I : SectionMap) {
1776 const MCSection *Section = I.first;
1777 SmallVector<SymbolCU, 8> &List = I.second;
1778 if (List.size() < 2)
1781 // If we have no section (e.g. common), just write out
1782 // individual spans for each symbol.
1784 for (const SymbolCU &Cur : List) {
1786 Span.Start = Cur.Sym;
1789 Spans[Cur.CU].push_back(Span);
1794 // Sort the symbols by offset within the section.
1795 std::sort(List.begin(), List.end(),
1796 [&](const SymbolCU &A, const SymbolCU &B) {
1797 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1798 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1800 // Symbols with no order assigned should be placed at the end.
1801 // (e.g. section end labels)
1809 // Build spans between each label.
1810 const MCSymbol *StartSym = List[0].Sym;
1811 for (size_t n = 1, e = List.size(); n < e; n++) {
1812 const SymbolCU &Prev = List[n - 1];
1813 const SymbolCU &Cur = List[n];
1815 // Try and build the longest span we can within the same CU.
1816 if (Cur.CU != Prev.CU) {
1818 Span.Start = StartSym;
1820 Spans[Prev.CU].push_back(Span);
1826 // Start the dwarf aranges section.
1827 Asm->OutStreamer.SwitchSection(
1828 Asm->getObjFileLowering().getDwarfARangesSection());
1830 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1832 // Build a list of CUs used.
1833 std::vector<DwarfCompileUnit *> CUs;
1834 for (const auto &it : Spans) {
1835 DwarfCompileUnit *CU = it.first;
1839 // Sort the CU list (again, to ensure consistent output order).
1840 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1841 return A->getUniqueID() < B->getUniqueID();
1844 // Emit an arange table for each CU we used.
1845 for (DwarfCompileUnit *CU : CUs) {
1846 std::vector<ArangeSpan> &List = Spans[CU];
1848 // Describe the skeleton CU's offset and length, not the dwo file's.
1849 if (auto *Skel = CU->getSkeleton())
1852 // Emit size of content not including length itself.
1853 unsigned ContentSize =
1854 sizeof(int16_t) + // DWARF ARange version number
1855 sizeof(int32_t) + // Offset of CU in the .debug_info section
1856 sizeof(int8_t) + // Pointer Size (in bytes)
1857 sizeof(int8_t); // Segment Size (in bytes)
1859 unsigned TupleSize = PtrSize * 2;
1861 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1863 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1865 ContentSize += Padding;
1866 ContentSize += (List.size() + 1) * TupleSize;
1868 // For each compile unit, write the list of spans it covers.
1869 Asm->OutStreamer.AddComment("Length of ARange Set");
1870 Asm->EmitInt32(ContentSize);
1871 Asm->OutStreamer.AddComment("DWARF Arange version number");
1872 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1873 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1874 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1875 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1876 Asm->EmitInt8(PtrSize);
1877 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1880 Asm->OutStreamer.EmitFill(Padding, 0xff);
1882 for (const ArangeSpan &Span : List) {
1883 Asm->EmitLabelReference(Span.Start, PtrSize);
1885 // Calculate the size as being from the span start to it's end.
1887 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1889 // For symbols without an end marker (e.g. common), we
1890 // write a single arange entry containing just that one symbol.
1891 uint64_t Size = SymSize[Span.Start];
1895 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1899 Asm->OutStreamer.AddComment("ARange terminator");
1900 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1901 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1905 // Emit visible names into a debug ranges section.
1906 void DwarfDebug::emitDebugRanges() {
1907 // Start the dwarf ranges section.
1908 Asm->OutStreamer.SwitchSection(
1909 Asm->getObjFileLowering().getDwarfRangesSection());
1911 // Size for our labels.
1912 unsigned char Size = Asm->getDataLayout().getPointerSize();
1914 // Grab the specific ranges for the compile units in the module.
1915 for (const auto &I : CUMap) {
1916 DwarfCompileUnit *TheCU = I.second;
1918 if (auto *Skel = TheCU->getSkeleton())
1921 // Iterate over the misc ranges for the compile units in the module.
1922 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1923 // Emit our symbol so we can find the beginning of the range.
1924 Asm->OutStreamer.EmitLabel(List.getSym());
1926 for (const RangeSpan &Range : List.getRanges()) {
1927 const MCSymbol *Begin = Range.getStart();
1928 const MCSymbol *End = Range.getEnd();
1929 assert(Begin && "Range without a begin symbol?");
1930 assert(End && "Range without an end symbol?");
1931 if (auto *Base = TheCU->getBaseAddress()) {
1932 Asm->EmitLabelDifference(Begin, Base, Size);
1933 Asm->EmitLabelDifference(End, Base, Size);
1935 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1936 Asm->OutStreamer.EmitSymbolValue(End, Size);
1940 // And terminate the list with two 0 values.
1941 Asm->OutStreamer.EmitIntValue(0, Size);
1942 Asm->OutStreamer.EmitIntValue(0, Size);
1947 // DWARF5 Experimental Separate Dwarf emitters.
1949 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1950 std::unique_ptr<DwarfUnit> NewU) {
1951 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1952 U.getCUNode().getSplitDebugFilename());
1954 if (!CompilationDir.empty())
1955 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1957 addGnuPubAttributes(*NewU, Die);
1959 SkeletonHolder.addUnit(std::move(NewU));
1962 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1963 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1964 // DW_AT_addr_base, DW_AT_ranges_base.
1965 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1967 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1968 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1969 DwarfCompileUnit &NewCU = *OwnedUnit;
1970 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
1971 DwarfInfoSectionSym);
1973 NewCU.initStmtList(DwarfLineSectionSym);
1975 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1980 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1981 // compile units that would normally be in debug_info.
1982 void DwarfDebug::emitDebugInfoDWO() {
1983 assert(useSplitDwarf() && "No split dwarf debug info?");
1984 // Don't pass an abbrev symbol, using a constant zero instead so as not to
1985 // emit relocations into the dwo file.
1986 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
1989 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1990 // abbreviations for the .debug_info.dwo section.
1991 void DwarfDebug::emitDebugAbbrevDWO() {
1992 assert(useSplitDwarf() && "No split dwarf?");
1993 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1996 void DwarfDebug::emitDebugLineDWO() {
1997 assert(useSplitDwarf() && "No split dwarf?");
1998 Asm->OutStreamer.SwitchSection(
1999 Asm->getObjFileLowering().getDwarfLineDWOSection());
2000 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2003 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2004 // string section and is identical in format to traditional .debug_str
2006 void DwarfDebug::emitDebugStrDWO() {
2007 assert(useSplitDwarf() && "No split dwarf?");
2008 const MCSection *OffSec =
2009 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2010 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2014 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2015 if (!useSplitDwarf())
2018 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2019 return &SplitTypeUnitFileTable;
2022 static uint64_t makeTypeSignature(StringRef Identifier) {
2024 Hash.update(Identifier);
2025 // ... take the least significant 8 bytes and return those. Our MD5
2026 // implementation always returns its results in little endian, swap bytes
2028 MD5::MD5Result Result;
2030 return support::endian::read64le(Result + 8);
2033 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2034 StringRef Identifier, DIE &RefDie,
2035 DICompositeType CTy) {
2036 // Fast path if we're building some type units and one has already used the
2037 // address pool we know we're going to throw away all this work anyway, so
2038 // don't bother building dependent types.
2039 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2042 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2044 CU.addDIETypeSignature(RefDie, *TU);
2048 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2049 AddrPool.resetUsedFlag();
2051 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2052 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2053 this, &InfoHolder, getDwoLineTable(CU));
2054 DwarfTypeUnit &NewTU = *OwnedUnit;
2055 DIE &UnitDie = NewTU.getUnitDie();
2057 TypeUnitsUnderConstruction.push_back(
2058 std::make_pair(std::move(OwnedUnit), CTy));
2060 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2063 uint64_t Signature = makeTypeSignature(Identifier);
2064 NewTU.setTypeSignature(Signature);
2066 if (useSplitDwarf())
2067 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2069 CU.applyStmtList(UnitDie);
2071 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2074 NewTU.setType(NewTU.createTypeDIE(CTy));
2077 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2078 TypeUnitsUnderConstruction.clear();
2080 // Types referencing entries in the address table cannot be placed in type
2082 if (AddrPool.hasBeenUsed()) {
2084 // Remove all the types built while building this type.
2085 // This is pessimistic as some of these types might not be dependent on
2086 // the type that used an address.
2087 for (const auto &TU : TypeUnitsToAdd)
2088 DwarfTypeUnits.erase(TU.second);
2090 // Construct this type in the CU directly.
2091 // This is inefficient because all the dependent types will be rebuilt
2092 // from scratch, including building them in type units, discovering that
2093 // they depend on addresses, throwing them out and rebuilding them.
2094 CU.constructTypeDIE(RefDie, CTy);
2098 // If the type wasn't dependent on fission addresses, finish adding the type
2099 // and all its dependent types.
2100 for (auto &TU : TypeUnitsToAdd)
2101 InfoHolder.addUnit(std::move(TU.first));
2103 CU.addDIETypeSignature(RefDie, NewTU);
2106 // Accelerator table mutators - add each name along with its companion
2107 // DIE to the proper table while ensuring that the name that we're going
2108 // to reference is in the string table. We do this since the names we
2109 // add may not only be identical to the names in the DIE.
2110 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2111 if (!useDwarfAccelTables())
2113 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2117 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2118 if (!useDwarfAccelTables())
2120 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2124 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2125 if (!useDwarfAccelTables())
2127 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2131 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2132 if (!useDwarfAccelTables())
2134 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),