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 "ByteStreamer.h"
15 #include "DwarfDebug.h"
18 #include "DwarfUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DIBuilder.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MD5.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
52 #define DEBUG_TYPE "dwarfdebug"
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
70 cl::desc("Generate dwarf aranges"),
74 enum DefaultOnOff { Default, Enable, Disable };
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113 return DD->resolve(Ref);
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
122 DIType DbgVariable::getType() const {
123 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
124 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
125 // addresses instead.
126 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
127 /* Byref variables, in Blocks, are declared by the programmer as
128 "SomeType VarName;", but the compiler creates a
129 __Block_byref_x_VarName struct, and gives the variable VarName
130 either the struct, or a pointer to the struct, as its type. This
131 is necessary for various behind-the-scenes things the compiler
132 needs to do with by-reference variables in blocks.
134 However, as far as the original *programmer* is concerned, the
135 variable should still have type 'SomeType', as originally declared.
137 The following function dives into the __Block_byref_x_VarName
138 struct to find the original type of the variable. This will be
139 passed back to the code generating the type for the Debug
140 Information Entry for the variable 'VarName'. 'VarName' will then
141 have the original type 'SomeType' in its debug information.
143 The original type 'SomeType' will be the type of the field named
144 'VarName' inside the __Block_byref_x_VarName struct.
146 NOTE: In order for this to not completely fail on the debugger
147 side, the Debug Information Entry for the variable VarName needs to
148 have a DW_AT_location that tells the debugger how to unwind through
149 the pointers and __Block_byref_x_VarName struct to find the actual
150 value of the variable. The function addBlockByrefType does this. */
152 uint16_t tag = Ty.getTag();
154 if (tag == dwarf::DW_TAG_pointer_type)
155 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
157 DIArray Elements = DICompositeType(subType).getTypeArray();
158 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
159 DIDerivedType DT(Elements.getElement(i));
160 if (getName() == DT.getName())
161 return (resolve(DT.getTypeDerivedFrom()));
167 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
170 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
172 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
173 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
174 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
175 UsedNonDefaultText(false),
176 SkeletonHolder(A, "skel_string", DIEValueAllocator),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
198 if (DwarfAccelTables == Default)
199 HasDwarfAccelTables = IsDarwin;
201 HasDwarfAccelTables = DwarfAccelTables == Enable;
203 if (SplitDwarf == Default)
204 HasSplitDwarf = false;
206 HasSplitDwarf = SplitDwarf == Enable;
208 if (DwarfPubSections == Default)
209 HasDwarfPubSections = !IsDarwin;
211 HasDwarfPubSections = DwarfPubSections == Enable;
213 DwarfVersion = DwarfVersionNumber
215 : MMI->getModule()->getDwarfVersion();
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Switch to the specified MCSection and emit an assembler
224 // temporary label to it if SymbolStem is specified.
225 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
226 const char *SymbolStem = nullptr) {
227 Asm->OutStreamer.SwitchSection(Section);
231 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
232 Asm->OutStreamer.EmitLabel(TmpSym);
236 static bool isObjCClass(StringRef Name) {
237 return Name.startswith("+") || Name.startswith("-");
240 static bool hasObjCCategory(StringRef Name) {
241 if (!isObjCClass(Name))
244 return Name.find(") ") != StringRef::npos;
247 static void getObjCClassCategory(StringRef In, StringRef &Class,
248 StringRef &Category) {
249 if (!hasObjCCategory(In)) {
250 Class = In.slice(In.find('[') + 1, In.find(' '));
255 Class = In.slice(In.find('[') + 1, In.find('('));
256 Category = In.slice(In.find('[') + 1, In.find(' '));
260 static StringRef getObjCMethodName(StringRef In) {
261 return In.slice(In.find(' ') + 1, In.find(']'));
264 // Helper for sorting sections into a stable output order.
265 static bool SectionSort(const MCSection *A, const MCSection *B) {
266 std::string LA = (A ? A->getLabelBeginName() : "");
267 std::string LB = (B ? B->getLabelBeginName() : "");
271 // Add the various names to the Dwarf accelerator table names.
272 // TODO: Determine whether or not we should add names for programs
273 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
274 // is only slightly different than the lookup of non-standard ObjC names.
275 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
276 if (!SP.isDefinition())
278 addAccelName(SP.getName(), Die);
280 // If the linkage name is different than the name, go ahead and output
281 // that as well into the name table.
282 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
283 addAccelName(SP.getLinkageName(), Die);
285 // If this is an Objective-C selector name add it to the ObjC accelerator
287 if (isObjCClass(SP.getName())) {
288 StringRef Class, Category;
289 getObjCClassCategory(SP.getName(), Class, Category);
290 addAccelObjC(Class, Die);
292 addAccelObjC(Category, Die);
293 // Also add the base method name to the name table.
294 addAccelName(getObjCMethodName(SP.getName()), Die);
298 /// isSubprogramContext - Return true if Context is either a subprogram
299 /// or another context nested inside a subprogram.
300 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
303 DIDescriptor D(Context);
304 if (D.isSubprogram())
307 return isSubprogramContext(resolve(DIType(Context).getContext()));
311 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
312 // and DW_AT_high_pc attributes. If there are global variables in this
313 // scope then create and insert DIEs for these variables.
314 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
316 DIE *SPDie = SPCU.getDIE(SP);
318 assert(SPDie && "Unable to find subprogram DIE!");
320 // If we're updating an abstract DIE, then we will be adding the children and
321 // object pointer later on. But what we don't want to do is process the
322 // concrete DIE twice.
323 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
324 // Pick up abstract subprogram DIE.
325 SPDie = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
326 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
328 DISubprogram SPDecl = SP.getFunctionDeclaration();
329 if (!SPDecl.isSubprogram()) {
330 // There is not any need to generate specification DIE for a function
331 // defined at compile unit level. If a function is defined inside another
332 // function then gdb prefers the definition at top level and but does not
333 // expect specification DIE in parent function. So avoid creating
334 // specification DIE for a function defined inside a function.
335 DIScope SPContext = resolve(SP.getContext());
336 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
337 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
338 SPCU.addFlag(*SPDie, dwarf::DW_AT_declaration);
341 DICompositeType SPTy = SP.getType();
342 DIArray Args = SPTy.getTypeArray();
343 uint16_t SPTag = SPTy.getTag();
344 if (SPTag == dwarf::DW_TAG_subroutine_type)
345 SPCU.constructSubprogramArguments(*SPDie, Args);
346 DIE *SPDeclDie = SPDie;
348 &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
349 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_specification, *SPDeclDie);
354 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
356 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
357 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
358 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
360 // Add name to the name table, we do this here because we're guaranteed
361 // to have concrete versions of our DW_TAG_subprogram nodes.
362 addSubprogramNames(SP, *SPDie);
367 /// Check whether we should create a DIE for the given Scope, return true
368 /// if we don't create a DIE (the corresponding DIE is null).
369 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
370 if (Scope->isAbstractScope())
373 // We don't create a DIE if there is no Range.
374 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
378 if (Ranges.size() > 1)
381 // We don't create a DIE if we have a single Range and the end label
383 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
384 MCSymbol *End = getLabelAfterInsn(RI->second);
388 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
389 dwarf::Attribute A, const MCSymbol *L,
390 const MCSymbol *Sec) {
391 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
392 U.addSectionLabel(D, A, L);
394 U.addSectionDelta(D, A, L, Sec);
397 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
398 const SmallVectorImpl<InsnRange> &Range) {
399 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
400 // emitting it appropriately.
401 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
403 // Under fission, ranges are specified by constant offsets relative to the
404 // CU's DW_AT_GNU_ranges_base.
406 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
407 DwarfDebugRangeSectionSym);
409 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
410 DwarfDebugRangeSectionSym);
412 RangeSpanList List(RangeSym);
413 for (const InsnRange &R : Range) {
414 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
415 List.addRange(std::move(Span));
418 // Add the range list to the set of ranges to be emitted.
419 TheCU.addRangeList(std::move(List));
422 // Construct new DW_TAG_lexical_block for this scope and attach
423 // DW_AT_low_pc/DW_AT_high_pc labels.
425 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
426 LexicalScope *Scope) {
427 if (isLexicalScopeDIENull(Scope))
430 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
431 if (Scope->isAbstractScope())
434 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
436 // If we have multiple ranges, emit them into the range section.
437 if (ScopeRanges.size() > 1) {
438 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
442 // Construct the address range for this DIE.
443 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
444 MCSymbol *Start = getLabelBeforeInsn(RI->first);
445 MCSymbol *End = getLabelAfterInsn(RI->second);
446 assert(End && "End label should not be null!");
448 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
449 assert(End->isDefined() && "Invalid end label for an inlined scope!");
451 attachLowHighPC(TheCU, *ScopeDIE, Start, End);
456 // This scope represents inlined body of a function. Construct DIE to
457 // represent this concrete inlined copy of the function.
459 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
460 LexicalScope *Scope) {
461 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
462 assert(!ScopeRanges.empty() &&
463 "LexicalScope does not have instruction markers!");
465 if (!Scope->getScopeNode())
467 DIScope DS(Scope->getScopeNode());
468 DISubprogram InlinedSP = getDISubprogram(DS);
469 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
471 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
475 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
476 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
478 // If we have multiple ranges, emit them into the range section.
479 if (ScopeRanges.size() > 1)
480 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
482 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
483 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
484 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
486 if (!StartLabel || !EndLabel)
487 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
489 assert(StartLabel->isDefined() &&
490 "Invalid starting label for an inlined scope!");
491 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
493 attachLowHighPC(TheCU, *ScopeDIE, StartLabel, EndLabel);
496 InlinedSubprogramDIEs.insert(OriginDIE);
498 // Add the call site information to the DIE.
499 DILocation DL(Scope->getInlinedAt());
500 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
501 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
502 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
504 // Add name to the name table, we do this here because we're guaranteed
505 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
506 addSubprogramNames(InlinedSP, *ScopeDIE);
511 DIE *DwarfDebug::createScopeChildrenDIE(
512 DwarfCompileUnit &TheCU, LexicalScope *Scope,
513 SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
514 DIE *ObjectPointer = nullptr;
516 // Collect arguments for current function.
517 if (LScopes.isCurrentFunctionScope(Scope)) {
518 for (DbgVariable *ArgDV : CurrentFnArguments)
521 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope()));
522 if (ArgDV->isObjectPointer())
523 ObjectPointer = Children.back().get();
526 // If this is a variadic function, add an unspecified parameter.
527 DISubprogram SP(Scope->getScopeNode());
528 DIArray FnArgs = SP.getType().getTypeArray();
529 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
530 .isUnspecifiedParameter()) {
532 make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
536 // Collect lexical scope children first.
537 for (DbgVariable *DV : ScopeVariables.lookup(Scope)) {
539 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope()));
540 if (DV->isObjectPointer())
541 ObjectPointer = Children.back().get();
543 for (LexicalScope *LS : Scope->getChildren())
544 if (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
545 Children.push_back(std::move(Nested));
546 return ObjectPointer;
549 DIE *DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU, LexicalScope *Scope) {
550 assert(Scope && Scope->getScopeNode());
552 DIScope DS(Scope->getScopeNode());
554 assert(!Scope->getInlinedAt());
555 assert(DS.isSubprogram());
557 ProcessedSPNodes.insert(DS);
559 SmallVector<std::unique_ptr<DIE>, 8> Children;
562 if (Scope->isAbstractScope()) {
563 ScopeDIE = TheCU.getDIE(DS);
564 // Note down abstract DIE.
566 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
568 assert(Children.empty() &&
569 "We create children only when the scope DIE is not null.");
573 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
575 // We create children when the scope DIE is not null.
576 if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
577 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
580 for (auto &I : Children)
581 ScopeDIE->addChild(std::move(I));
586 // Construct a DIE for this scope.
587 std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
588 LexicalScope *Scope) {
589 if (!Scope || !Scope->getScopeNode())
592 DIScope DS(Scope->getScopeNode());
594 assert(Scope->getInlinedAt() ||
595 !DS.isSubprogram() && "Only handle inlined subprograms here, use "
596 "constructSubprogramScopeDIE for non-inlined "
599 SmallVector<std::unique_ptr<DIE>, 8> Children;
601 // We try to create the scope DIE first, then the children DIEs. This will
602 // avoid creating un-used children then removing them later when we find out
603 // the scope DIE is null.
604 std::unique_ptr<DIE> ScopeDIE;
605 if (Scope->getInlinedAt()) {
606 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
609 // We create children when the scope DIE is not null.
610 createScopeChildrenDIE(TheCU, Scope, Children);
612 // Early exit when we know the scope DIE is going to be null.
613 if (isLexicalScopeDIENull(Scope))
616 // We create children here when we know the scope DIE is not going to be
617 // null and the children will be added to the scope DIE.
618 createScopeChildrenDIE(TheCU, Scope, Children);
620 // There is no need to emit empty lexical block DIE.
621 std::pair<ImportedEntityMap::const_iterator,
622 ImportedEntityMap::const_iterator> Range =
624 ScopesWithImportedEntities.begin(),
625 ScopesWithImportedEntities.end(),
626 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
628 if (Children.empty() && Range.first == Range.second)
630 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
631 assert(ScopeDIE && "Scope DIE should not be null.");
632 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
634 constructImportedEntityDIE(TheCU, i->second, *ScopeDIE);
638 for (auto &I : Children)
639 ScopeDIE->addChild(std::move(I));
644 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
645 if (!GenerateGnuPubSections)
648 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
651 // Create new DwarfCompileUnit for the given metadata node with tag
652 // DW_TAG_compile_unit.
653 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
654 StringRef FN = DIUnit.getFilename();
655 CompilationDir = DIUnit.getDirectory();
657 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
658 auto OwnedUnit = make_unique<DwarfCompileUnit>(
659 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
660 DwarfCompileUnit &NewCU = *OwnedUnit;
661 InfoHolder.addUnit(std::move(OwnedUnit));
663 // LTO with assembly output shares a single line table amongst multiple CUs.
664 // To avoid the compilation directory being ambiguous, let the line table
665 // explicitly describe the directory of all files, never relying on the
666 // compilation directory.
667 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
668 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
669 NewCU.getUniqueID(), CompilationDir);
671 NewCU.addString(*Die, dwarf::DW_AT_producer, DIUnit.getProducer());
672 NewCU.addUInt(*Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
673 DIUnit.getLanguage());
674 NewCU.addString(*Die, dwarf::DW_AT_name, FN);
676 if (!useSplitDwarf()) {
677 NewCU.initStmtList(DwarfLineSectionSym);
679 // If we're using split dwarf the compilation dir is going to be in the
680 // skeleton CU and so we don't need to duplicate it here.
681 if (!CompilationDir.empty())
682 NewCU.addString(*Die, dwarf::DW_AT_comp_dir, CompilationDir);
684 addGnuPubAttributes(NewCU, *Die);
687 if (DIUnit.isOptimized())
688 NewCU.addFlag(*Die, dwarf::DW_AT_APPLE_optimized);
690 StringRef Flags = DIUnit.getFlags();
692 NewCU.addString(*Die, dwarf::DW_AT_APPLE_flags, Flags);
694 if (unsigned RVer = DIUnit.getRunTimeVersion())
695 NewCU.addUInt(*Die, dwarf::DW_AT_APPLE_major_runtime_vers,
696 dwarf::DW_FORM_data1, RVer);
701 if (useSplitDwarf()) {
702 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
703 DwarfInfoDWOSectionSym);
704 NewCU.setSkeleton(constructSkeletonCU(NewCU));
706 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
707 DwarfInfoSectionSym);
709 CUMap.insert(std::make_pair(DIUnit, &NewCU));
710 CUDieMap.insert(std::make_pair(Die, &NewCU));
714 // Construct subprogram DIE.
715 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
717 // FIXME: We should only call this routine once, however, during LTO if a
718 // program is defined in multiple CUs we could end up calling it out of
719 // beginModule as we walk the CUs.
721 DwarfCompileUnit *&CURef = SPMap[N];
727 if (!SP.isDefinition())
728 // This is a method declaration which will be handled while constructing
732 DIE &SubprogramDie = *TheCU.getOrCreateSubprogramDIE(SP);
734 // Expose as a global name.
735 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
738 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
740 DIImportedEntity Module(N);
741 assert(Module.Verify());
742 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
743 constructImportedEntityDIE(TheCU, Module, *D);
746 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
747 const MDNode *N, DIE &Context) {
748 DIImportedEntity Module(N);
749 assert(Module.Verify());
750 return constructImportedEntityDIE(TheCU, Module, Context);
753 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
754 const DIImportedEntity &Module,
756 assert(Module.Verify() &&
757 "Use one of the MDNode * overloads to handle invalid metadata");
758 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), Context, Module);
760 DIDescriptor Entity = resolve(Module.getEntity());
761 if (Entity.isNameSpace())
762 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
763 else if (Entity.isSubprogram())
764 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
765 else if (Entity.isType())
766 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
768 EntityDie = TheCU.getDIE(Entity);
769 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
770 Module.getContext().getFilename(),
771 Module.getContext().getDirectory());
772 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
773 StringRef Name = Module.getName();
775 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
778 // Emit all Dwarf sections that should come prior to the content. Create
779 // global DIEs and emit initial debug info sections. This is invoked by
780 // the target AsmPrinter.
781 void DwarfDebug::beginModule() {
782 if (DisableDebugInfoPrinting)
785 const Module *M = MMI->getModule();
787 // If module has named metadata anchors then use them, otherwise scan the
788 // module using debug info finder to collect debug info.
789 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
792 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
794 // Emit initial sections so we can reference labels later.
797 SingleCU = CU_Nodes->getNumOperands() == 1;
799 for (MDNode *N : CU_Nodes->operands()) {
800 DICompileUnit CUNode(N);
801 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
802 DIArray ImportedEntities = CUNode.getImportedEntities();
803 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
804 ScopesWithImportedEntities.push_back(std::make_pair(
805 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
806 ImportedEntities.getElement(i)));
807 std::sort(ScopesWithImportedEntities.begin(),
808 ScopesWithImportedEntities.end(), less_first());
809 DIArray GVs = CUNode.getGlobalVariables();
810 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
811 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
812 DIArray SPs = CUNode.getSubprograms();
813 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
814 constructSubprogramDIE(CU, SPs.getElement(i));
815 DIArray EnumTypes = CUNode.getEnumTypes();
816 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
817 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
818 DIArray RetainedTypes = CUNode.getRetainedTypes();
819 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
820 DIType Ty(RetainedTypes.getElement(i));
821 // The retained types array by design contains pointers to
822 // MDNodes rather than DIRefs. Unique them here.
823 DIType UniqueTy(resolve(Ty.getRef()));
824 CU.getOrCreateTypeDIE(UniqueTy);
826 // Emit imported_modules last so that the relevant context is already
828 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
829 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
832 // Tell MMI that we have debug info.
833 MMI->setDebugInfoAvailability(true);
835 // Prime section data.
836 SectionMap[Asm->getObjFileLowering().getTextSection()];
839 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
840 void DwarfDebug::computeInlinedDIEs() {
841 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
842 for (DIE *ISP : InlinedSubprogramDIEs)
843 FirstCU->addUInt(*ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
845 for (const auto &AI : AbstractSPDies) {
846 DIE &ISP = *AI.second;
847 if (InlinedSubprogramDIEs.count(&ISP))
849 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
853 // Collect info for variables that were optimized out.
854 void DwarfDebug::collectDeadVariables() {
855 const Module *M = MMI->getModule();
857 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
858 for (MDNode *N : CU_Nodes->operands()) {
859 DICompileUnit TheCU(N);
860 DIArray Subprograms = TheCU.getSubprograms();
861 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
862 DISubprogram SP(Subprograms.getElement(i));
863 if (ProcessedSPNodes.count(SP) != 0)
865 if (!SP.isSubprogram())
867 if (!SP.isDefinition())
869 DIArray Variables = SP.getVariables();
870 if (Variables.getNumElements() == 0)
873 // Construct subprogram DIE and add variables DIEs.
874 DwarfCompileUnit *SPCU =
875 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
876 assert(SPCU && "Unable to find Compile Unit!");
877 // FIXME: See the comment in constructSubprogramDIE about duplicate
879 constructSubprogramDIE(*SPCU, SP);
880 DIE *SPDIE = SPCU->getDIE(SP);
881 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
882 DIVariable DV(Variables.getElement(vi));
883 if (!DV.isVariable())
885 DbgVariable NewVar(DV, nullptr, this);
886 SPDIE->addChild(SPCU->constructVariableDIE(NewVar, false));
893 void DwarfDebug::finalizeModuleInfo() {
894 // Collect info for variables that were optimized out.
895 collectDeadVariables();
897 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
898 computeInlinedDIEs();
900 // Handle anything that needs to be done on a per-unit basis after
901 // all other generation.
902 for (const auto &TheU : getUnits()) {
903 // Emit DW_AT_containing_type attribute to connect types with their
904 // vtable holding type.
905 TheU->constructContainingTypeDIEs();
907 // Add CU specific attributes if we need to add any.
908 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
909 // If we're splitting the dwarf out now that we've got the entire
910 // CU then add the dwo id to it.
911 DwarfCompileUnit *SkCU =
912 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
913 if (useSplitDwarf()) {
914 // Emit a unique identifier for this CU.
915 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
916 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
917 dwarf::DW_FORM_data8, ID);
918 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
919 dwarf::DW_FORM_data8, ID);
921 // We don't keep track of which addresses are used in which CU so this
922 // is a bit pessimistic under LTO.
923 if (!AddrPool.isEmpty())
924 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
925 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
926 DwarfAddrSectionSym);
927 if (!TheU->getRangeLists().empty())
928 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
929 dwarf::DW_AT_GNU_ranges_base,
930 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
933 // If we have code split among multiple sections or non-contiguous
934 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
935 // remain in the .o file, otherwise add a DW_AT_low_pc.
936 // FIXME: We should use ranges allow reordering of code ala
937 // .subsections_via_symbols in mach-o. This would mean turning on
938 // ranges for all subprogram DIEs for mach-o.
939 DwarfCompileUnit &U =
940 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
941 unsigned NumRanges = TheU->getRanges().size();
944 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
945 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
946 DwarfDebugRangeSectionSym);
948 // A DW_AT_low_pc attribute may also be specified in combination with
949 // DW_AT_ranges to specify the default base address for use in
950 // location lists (see Section 2.6.2) and range lists (see Section
952 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
955 RangeSpan &Range = TheU->getRanges().back();
956 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
958 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
965 // Compute DIE offsets and sizes.
966 InfoHolder.computeSizeAndOffsets();
968 SkeletonHolder.computeSizeAndOffsets();
971 void DwarfDebug::endSections() {
972 // Filter labels by section.
973 for (const SymbolCU &SCU : ArangeLabels) {
974 if (SCU.Sym->isInSection()) {
975 // Make a note of this symbol and it's section.
976 const MCSection *Section = &SCU.Sym->getSection();
977 if (!Section->getKind().isMetadata())
978 SectionMap[Section].push_back(SCU);
980 // Some symbols (e.g. common/bss on mach-o) can have no section but still
981 // appear in the output. This sucks as we rely on sections to build
982 // arange spans. We can do it without, but it's icky.
983 SectionMap[nullptr].push_back(SCU);
987 // Build a list of sections used.
988 std::vector<const MCSection *> Sections;
989 for (const auto &it : SectionMap) {
990 const MCSection *Section = it.first;
991 Sections.push_back(Section);
994 // Sort the sections into order.
995 // This is only done to ensure consistent output order across different runs.
996 std::sort(Sections.begin(), Sections.end(), SectionSort);
998 // Add terminating symbols for each section.
999 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1000 const MCSection *Section = Sections[ID];
1001 MCSymbol *Sym = nullptr;
1004 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1005 // if we know the section name up-front. For user-created sections, the
1006 // resulting label may not be valid to use as a label. (section names can
1007 // use a greater set of characters on some systems)
1008 Sym = Asm->GetTempSymbol("debug_end", ID);
1009 Asm->OutStreamer.SwitchSection(Section);
1010 Asm->OutStreamer.EmitLabel(Sym);
1013 // Insert a final terminator.
1014 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1018 // Emit all Dwarf sections that should come after the content.
1019 void DwarfDebug::endModule() {
1020 assert(CurFn == nullptr);
1021 assert(CurMI == nullptr);
1026 // End any existing sections.
1027 // TODO: Does this need to happen?
1030 // Finalize the debug info for the module.
1031 finalizeModuleInfo();
1035 // Emit all the DIEs into a debug info section.
1038 // Corresponding abbreviations into a abbrev section.
1039 emitAbbreviations();
1041 // Emit info into a debug aranges section.
1042 if (GenerateARangeSection)
1045 // Emit info into a debug ranges section.
1048 if (useSplitDwarf()) {
1051 emitDebugAbbrevDWO();
1053 // Emit DWO addresses.
1054 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1057 // Emit info into a debug loc section.
1060 // Emit info into the dwarf accelerator table sections.
1061 if (useDwarfAccelTables()) {
1064 emitAccelNamespaces();
1068 // Emit the pubnames and pubtypes sections if requested.
1069 if (HasDwarfPubSections) {
1070 emitDebugPubNames(GenerateGnuPubSections);
1071 emitDebugPubTypes(GenerateGnuPubSections);
1077 // Reset these for the next Module if we have one.
1081 // Find abstract variable, if any, associated with Var.
1082 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1083 DebugLoc ScopeLoc) {
1084 LLVMContext &Ctx = DV->getContext();
1085 // More then one inlined variable corresponds to one abstract variable.
1086 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1087 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1089 return AbsDbgVariable;
1091 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1095 AbsDbgVariable = new DbgVariable(Var, nullptr, this);
1096 addScopeVariable(Scope, AbsDbgVariable);
1097 AbstractVariables[Var] = AbsDbgVariable;
1098 return AbsDbgVariable;
1101 // If Var is a current function argument then add it to CurrentFnArguments list.
1102 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1103 if (!LScopes.isCurrentFunctionScope(Scope))
1105 DIVariable DV = Var->getVariable();
1106 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1108 unsigned ArgNo = DV.getArgNumber();
1112 size_t Size = CurrentFnArguments.size();
1114 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1115 // llvm::Function argument size is not good indicator of how many
1116 // arguments does the function have at source level.
1118 CurrentFnArguments.resize(ArgNo * 2);
1119 CurrentFnArguments[ArgNo - 1] = Var;
1123 // Collect variable information from side table maintained by MMI.
1124 void DwarfDebug::collectVariableInfoFromMMITable(
1125 SmallPtrSet<const MDNode *, 16> &Processed) {
1126 for (const auto &VI : MMI->getVariableDbgInfo()) {
1129 Processed.insert(VI.Var);
1130 DIVariable DV(VI.Var);
1131 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1133 // If variable scope is not found then skip this variable.
1137 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1138 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1139 RegVar->setFrameIndex(VI.Slot);
1140 if (!addCurrentFnArgument(RegVar, Scope))
1141 addScopeVariable(Scope, RegVar);
1143 AbsDbgVariable->setFrameIndex(VI.Slot);
1147 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1149 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1150 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1151 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1152 MI->getOperand(0).getReg() &&
1153 (MI->getOperand(1).isImm() ||
1154 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1157 // Get .debug_loc entry for the instruction range starting at MI.
1158 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1159 const MDNode *Var = MI->getDebugVariable();
1161 assert(MI->getNumOperands() == 3);
1162 if (MI->getOperand(0).isReg()) {
1163 MachineLocation MLoc;
1164 // If the second operand is an immediate, this is a
1165 // register-indirect address.
1166 if (!MI->getOperand(1).isImm())
1167 MLoc.set(MI->getOperand(0).getReg());
1169 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1170 return DebugLocEntry::Value(Var, MLoc);
1172 if (MI->getOperand(0).isImm())
1173 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1174 if (MI->getOperand(0).isFPImm())
1175 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1176 if (MI->getOperand(0).isCImm())
1177 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1179 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1182 // Find variables for each lexical scope.
1184 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1185 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1186 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1188 // Grab the variable info that was squirreled away in the MMI side-table.
1189 collectVariableInfoFromMMITable(Processed);
1191 for (const MDNode *Var : UserVariables) {
1192 if (Processed.count(Var))
1195 // History contains relevant DBG_VALUE instructions for Var and instructions
1197 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1198 if (History.empty())
1200 const MachineInstr *MInsn = History.front();
1203 LexicalScope *Scope = nullptr;
1204 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1205 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1206 Scope = LScopes.getCurrentFunctionScope();
1207 else if (MDNode *IA = DV.getInlinedAt())
1208 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1210 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1211 // If variable scope is not found then skip this variable.
1215 Processed.insert(DV);
1216 assert(MInsn->isDebugValue() && "History must begin with debug value");
1217 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1218 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1219 if (!addCurrentFnArgument(RegVar, Scope))
1220 addScopeVariable(Scope, RegVar);
1222 AbsVar->setMInsn(MInsn);
1224 // Simplify ranges that are fully coalesced.
1225 if (History.size() <= 1 ||
1226 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1227 RegVar->setMInsn(MInsn);
1231 // Handle multiple DBG_VALUE instructions describing one variable.
1232 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1234 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1235 DebugLocList &LocList = DotDebugLocEntries.back();
1237 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1238 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1239 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1240 HI = History.begin(),
1243 const MachineInstr *Begin = *HI;
1244 assert(Begin->isDebugValue() && "Invalid History entry");
1246 // Check if DBG_VALUE is truncating a range.
1247 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1248 !Begin->getOperand(0).getReg())
1251 // Compute the range for a register location.
1252 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1253 const MCSymbol *SLabel = nullptr;
1256 // If Begin is the last instruction in History then its value is valid
1257 // until the end of the function.
1258 SLabel = FunctionEndSym;
1260 const MachineInstr *End = HI[1];
1261 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1262 << "\t" << *Begin << "\t" << *End << "\n");
1263 if (End->isDebugValue())
1264 SLabel = getLabelBeforeInsn(End);
1266 // End is a normal instruction clobbering the range.
1267 SLabel = getLabelAfterInsn(End);
1268 assert(SLabel && "Forgot label after clobber instruction");
1273 // The value is valid until the next DBG_VALUE or clobber.
1274 DebugLocEntry Loc(FLabel, SLabel, getDebugLocValue(Begin), TheCU);
1275 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1276 DebugLoc.push_back(std::move(Loc));
1280 // Collect info for variables that were optimized out.
1281 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1282 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1283 DIVariable DV(Variables.getElement(i));
1284 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1286 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1287 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1291 // Return Label preceding the instruction.
1292 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1293 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1294 assert(Label && "Didn't insert label before instruction");
1298 // Return Label immediately following the instruction.
1299 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1300 return LabelsAfterInsn.lookup(MI);
1303 // Process beginning of an instruction.
1304 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1305 assert(CurMI == nullptr);
1307 // Check if source location changes, but ignore DBG_VALUE locations.
1308 if (!MI->isDebugValue()) {
1309 DebugLoc DL = MI->getDebugLoc();
1310 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1313 if (DL == PrologEndLoc) {
1314 Flags |= DWARF2_FLAG_PROLOGUE_END;
1315 PrologEndLoc = DebugLoc();
1317 if (PrologEndLoc.isUnknown())
1318 Flags |= DWARF2_FLAG_IS_STMT;
1320 if (!DL.isUnknown()) {
1321 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1322 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1324 recordSourceLine(0, 0, nullptr, 0);
1328 // Insert labels where requested.
1329 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1330 LabelsBeforeInsn.find(MI);
1333 if (I == LabelsBeforeInsn.end())
1336 // Label already assigned.
1341 PrevLabel = MMI->getContext().CreateTempSymbol();
1342 Asm->OutStreamer.EmitLabel(PrevLabel);
1344 I->second = PrevLabel;
1347 // Process end of an instruction.
1348 void DwarfDebug::endInstruction() {
1349 assert(CurMI != nullptr);
1350 // Don't create a new label after DBG_VALUE instructions.
1351 // They don't generate code.
1352 if (!CurMI->isDebugValue())
1353 PrevLabel = nullptr;
1355 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1356 LabelsAfterInsn.find(CurMI);
1360 if (I == LabelsAfterInsn.end())
1363 // Label already assigned.
1367 // We need a label after this instruction.
1369 PrevLabel = MMI->getContext().CreateTempSymbol();
1370 Asm->OutStreamer.EmitLabel(PrevLabel);
1372 I->second = PrevLabel;
1375 // Each LexicalScope has first instruction and last instruction to mark
1376 // beginning and end of a scope respectively. Create an inverse map that list
1377 // scopes starts (and ends) with an instruction. One instruction may start (or
1378 // end) multiple scopes. Ignore scopes that are not reachable.
1379 void DwarfDebug::identifyScopeMarkers() {
1380 SmallVector<LexicalScope *, 4> WorkList;
1381 WorkList.push_back(LScopes.getCurrentFunctionScope());
1382 while (!WorkList.empty()) {
1383 LexicalScope *S = WorkList.pop_back_val();
1385 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1386 if (!Children.empty())
1387 WorkList.append(Children.begin(), Children.end());
1389 if (S->isAbstractScope())
1392 for (const InsnRange &R : S->getRanges()) {
1393 assert(R.first && "InsnRange does not have first instruction!");
1394 assert(R.second && "InsnRange does not have second instruction!");
1395 requestLabelBeforeInsn(R.first);
1396 requestLabelAfterInsn(R.second);
1401 // Gather pre-function debug information. Assumes being called immediately
1402 // after the function entry point has been emitted.
1403 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1406 // If there's no debug info for the function we're not going to do anything.
1407 if (!MMI->hasDebugInfo())
1410 // Grab the lexical scopes for the function, if we don't have any of those
1411 // then we're not going to be able to do anything.
1412 LScopes.initialize(*MF);
1413 if (LScopes.empty())
1416 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1418 // Make sure that each lexical scope will have a begin/end label.
1419 identifyScopeMarkers();
1421 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1422 // belongs to so that we add to the correct per-cu line table in the
1424 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1425 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1426 assert(TheCU && "Unable to find compile unit!");
1427 if (Asm->OutStreamer.hasRawTextSupport())
1428 // Use a single line table if we are generating assembly.
1429 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1431 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1433 // Emit a label for the function so that we have a beginning address.
1434 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1435 // Assumes in correct section after the entry point.
1436 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1438 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1439 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1440 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1442 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1444 bool AtBlockEntry = true;
1445 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1447 const MachineInstr *MI = II;
1449 if (MI->isDebugValue()) {
1450 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1452 // Keep track of user variables.
1453 const MDNode *Var = MI->getDebugVariable();
1455 // Variable is in a register, we need to check for clobbers.
1456 if (isDbgValueInDefinedReg(MI))
1457 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1459 // Check the history of this variable.
1460 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1461 if (History.empty()) {
1462 UserVariables.push_back(Var);
1463 // The first mention of a function argument gets the FunctionBeginSym
1464 // label, so arguments are visible when breaking at function entry.
1466 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1467 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1468 LabelsBeforeInsn[MI] = FunctionBeginSym;
1470 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1471 const MachineInstr *Prev = History.back();
1472 if (Prev->isDebugValue()) {
1473 // Coalesce identical entries at the end of History.
1474 if (History.size() >= 2 &&
1475 Prev->isIdenticalTo(History[History.size() - 2])) {
1476 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1477 << "\t" << *Prev << "\t"
1478 << *History[History.size() - 2] << "\n");
1482 // Terminate old register assignments that don't reach MI;
1483 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1484 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1485 isDbgValueInDefinedReg(Prev)) {
1486 // Previous register assignment needs to terminate at the end of
1488 MachineBasicBlock::const_iterator LastMI =
1489 PrevMBB->getLastNonDebugInstr();
1490 if (LastMI == PrevMBB->end()) {
1491 // Drop DBG_VALUE for empty range.
1492 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1493 << "\t" << *Prev << "\n");
1495 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1496 // Terminate after LastMI.
1497 History.push_back(LastMI);
1501 History.push_back(MI);
1503 // Not a DBG_VALUE instruction.
1504 if (!MI->isPosition())
1505 AtBlockEntry = false;
1507 // First known non-DBG_VALUE and non-frame setup location marks
1508 // the beginning of the function body.
1509 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1510 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1511 PrologEndLoc = MI->getDebugLoc();
1513 // Check if the instruction clobbers any registers with debug vars.
1514 for (const MachineOperand &MO : MI->operands()) {
1515 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1517 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1520 const MDNode *Var = LiveUserVar[Reg];
1523 // Reg is now clobbered.
1524 LiveUserVar[Reg] = nullptr;
1526 // Was MD last defined by a DBG_VALUE referring to Reg?
1527 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1528 if (HistI == DbgValues.end())
1530 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1531 if (History.empty())
1533 const MachineInstr *Prev = History.back();
1534 // Sanity-check: Register assignments are terminated at the end of
1536 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1538 // Is the variable still in Reg?
1539 if (!isDbgValueInDefinedReg(Prev) ||
1540 Prev->getOperand(0).getReg() != Reg)
1542 // Var is clobbered. Make sure the next instruction gets a label.
1543 History.push_back(MI);
1550 for (auto &I : DbgValues) {
1551 SmallVectorImpl<const MachineInstr *> &History = I.second;
1552 if (History.empty())
1555 // Make sure the final register assignments are terminated.
1556 const MachineInstr *Prev = History.back();
1557 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1558 const MachineBasicBlock *PrevMBB = Prev->getParent();
1559 MachineBasicBlock::const_iterator LastMI =
1560 PrevMBB->getLastNonDebugInstr();
1561 if (LastMI == PrevMBB->end())
1562 // Drop DBG_VALUE for empty range.
1564 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1565 // Terminate after LastMI.
1566 History.push_back(LastMI);
1569 // Request labels for the full history.
1570 for (const MachineInstr *MI : History) {
1571 if (MI->isDebugValue())
1572 requestLabelBeforeInsn(MI);
1574 requestLabelAfterInsn(MI);
1578 PrevInstLoc = DebugLoc();
1579 PrevLabel = FunctionBeginSym;
1581 // Record beginning of function.
1582 if (!PrologEndLoc.isUnknown()) {
1583 DebugLoc FnStartDL =
1584 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1586 FnStartDL.getLine(), FnStartDL.getCol(),
1587 FnStartDL.getScope(MF->getFunction()->getContext()),
1588 // We'd like to list the prologue as "not statements" but GDB behaves
1589 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1590 DWARF2_FLAG_IS_STMT);
1594 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1595 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1596 DIVariable DV = Var->getVariable();
1597 // Variables with positive arg numbers are parameters.
1598 if (unsigned ArgNum = DV.getArgNumber()) {
1599 // Keep all parameters in order at the start of the variable list to ensure
1600 // function types are correct (no out-of-order parameters)
1602 // This could be improved by only doing it for optimized builds (unoptimized
1603 // builds have the right order to begin with), searching from the back (this
1604 // would catch the unoptimized case quickly), or doing a binary search
1605 // rather than linear search.
1606 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1607 while (I != Vars.end()) {
1608 unsigned CurNum = (*I)->getVariable().getArgNumber();
1609 // A local (non-parameter) variable has been found, insert immediately
1613 // A later indexed parameter has been found, insert immediately before it.
1614 if (CurNum > ArgNum)
1618 Vars.insert(I, Var);
1622 Vars.push_back(Var);
1625 // Gather and emit post-function debug information.
1626 void DwarfDebug::endFunction(const MachineFunction *MF) {
1627 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1628 // though the beginFunction may not be called at all.
1629 // We should handle both cases.
1633 assert(CurFn == MF);
1634 assert(CurFn != nullptr);
1636 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1637 // If we don't have a lexical scope for this function then there will
1638 // be a hole in the range information. Keep note of this by setting the
1639 // previously used section to nullptr.
1640 PrevSection = nullptr;
1646 // Define end label for subprogram.
1647 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1648 // Assumes in correct section after the entry point.
1649 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1651 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1652 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1654 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1655 collectVariableInfo(ProcessedVars);
1657 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1658 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1660 // Construct abstract scopes.
1661 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1662 DISubprogram SP(AScope->getScopeNode());
1663 if (SP.isSubprogram()) {
1664 // Collect info for variables that were optimized out.
1665 DIArray Variables = SP.getVariables();
1666 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1667 DIVariable DV(Variables.getElement(i));
1668 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1670 // Check that DbgVariable for DV wasn't created earlier, when
1671 // findAbstractVariable() was called for inlined instance of DV.
1672 LLVMContext &Ctx = DV->getContext();
1673 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1674 if (AbstractVariables.lookup(CleanDV))
1676 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1677 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1680 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1681 constructSubprogramScopeDIE(TheCU, AScope);
1684 DIE &CurFnDIE = *constructSubprogramScopeDIE(TheCU, FnScope);
1685 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1686 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1688 // Add the range of this function to the list of ranges for the CU.
1689 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1690 TheCU.addRange(std::move(Span));
1691 PrevSection = Asm->getCurrentSection();
1695 for (auto &I : ScopeVariables)
1696 DeleteContainerPointers(I.second);
1697 ScopeVariables.clear();
1698 DeleteContainerPointers(CurrentFnArguments);
1699 UserVariables.clear();
1701 AbstractVariables.clear();
1702 LabelsBeforeInsn.clear();
1703 LabelsAfterInsn.clear();
1704 PrevLabel = nullptr;
1708 // Register a source line with debug info. Returns the unique label that was
1709 // emitted and which provides correspondence to the source line list.
1710 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1715 unsigned Discriminator = 0;
1717 DIDescriptor Scope(S);
1719 if (Scope.isCompileUnit()) {
1720 DICompileUnit CU(S);
1721 Fn = CU.getFilename();
1722 Dir = CU.getDirectory();
1723 } else if (Scope.isFile()) {
1725 Fn = F.getFilename();
1726 Dir = F.getDirectory();
1727 } else if (Scope.isSubprogram()) {
1729 Fn = SP.getFilename();
1730 Dir = SP.getDirectory();
1731 } else if (Scope.isLexicalBlockFile()) {
1732 DILexicalBlockFile DBF(S);
1733 Fn = DBF.getFilename();
1734 Dir = DBF.getDirectory();
1735 } else if (Scope.isLexicalBlock()) {
1736 DILexicalBlock DB(S);
1737 Fn = DB.getFilename();
1738 Dir = DB.getDirectory();
1739 Discriminator = DB.getDiscriminator();
1741 llvm_unreachable("Unexpected scope info");
1743 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1744 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1745 .getOrCreateSourceID(Fn, Dir);
1747 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1751 //===----------------------------------------------------------------------===//
1753 //===----------------------------------------------------------------------===//
1755 // Emit initial Dwarf sections with a label at the start of each one.
1756 void DwarfDebug::emitSectionLabels() {
1757 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1759 // Dwarf sections base addresses.
1760 DwarfInfoSectionSym =
1761 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1762 if (useSplitDwarf())
1763 DwarfInfoDWOSectionSym =
1764 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1765 DwarfAbbrevSectionSym =
1766 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1767 if (useSplitDwarf())
1768 DwarfAbbrevDWOSectionSym = emitSectionSym(
1769 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1770 if (GenerateARangeSection)
1771 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1773 DwarfLineSectionSym =
1774 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1775 if (GenerateGnuPubSections) {
1776 DwarfGnuPubNamesSectionSym =
1777 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1778 DwarfGnuPubTypesSectionSym =
1779 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1780 } else if (HasDwarfPubSections) {
1781 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1782 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1785 DwarfStrSectionSym =
1786 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1787 if (useSplitDwarf()) {
1788 DwarfStrDWOSectionSym =
1789 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1790 DwarfAddrSectionSym =
1791 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1792 DwarfDebugLocSectionSym =
1793 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1795 DwarfDebugLocSectionSym =
1796 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1797 DwarfDebugRangeSectionSym =
1798 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1801 // Recursively emits a debug information entry.
1802 void DwarfDebug::emitDIE(DIE &Die) {
1803 // Get the abbreviation for this DIE.
1804 const DIEAbbrev &Abbrev = Die.getAbbrev();
1806 // Emit the code (index) for the abbreviation.
1807 if (Asm->isVerbose())
1808 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1809 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1810 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1811 dwarf::TagString(Abbrev.getTag()));
1812 Asm->EmitULEB128(Abbrev.getNumber());
1814 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1815 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1817 // Emit the DIE attribute values.
1818 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1819 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1820 dwarf::Form Form = AbbrevData[i].getForm();
1821 assert(Form && "Too many attributes for DIE (check abbreviation)");
1823 if (Asm->isVerbose()) {
1824 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1825 if (Attr == dwarf::DW_AT_accessibility)
1826 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1827 cast<DIEInteger>(Values[i])->getValue()));
1830 // Emit an attribute using the defined form.
1831 Values[i]->EmitValue(Asm, Form);
1834 // Emit the DIE children if any.
1835 if (Abbrev.hasChildren()) {
1836 for (auto &Child : Die.getChildren())
1839 Asm->OutStreamer.AddComment("End Of Children Mark");
1844 // Emit the debug info section.
1845 void DwarfDebug::emitDebugInfo() {
1846 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1848 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1851 // Emit the abbreviation section.
1852 void DwarfDebug::emitAbbreviations() {
1853 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1855 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1858 // Emit the last address of the section and the end of the line matrix.
1859 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1860 // Define last address of section.
1861 Asm->OutStreamer.AddComment("Extended Op");
1864 Asm->OutStreamer.AddComment("Op size");
1865 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1866 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1867 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1869 Asm->OutStreamer.AddComment("Section end label");
1871 Asm->OutStreamer.EmitSymbolValue(
1872 Asm->GetTempSymbol("section_end", SectionEnd),
1873 Asm->getDataLayout().getPointerSize());
1875 // Mark end of matrix.
1876 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1882 // Emit visible names into a hashed accelerator table section.
1883 void DwarfDebug::emitAccelNames() {
1884 AccelNames.FinalizeTable(Asm, "Names");
1885 Asm->OutStreamer.SwitchSection(
1886 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1887 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1888 Asm->OutStreamer.EmitLabel(SectionBegin);
1890 // Emit the full data.
1891 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1894 // Emit objective C classes and categories into a hashed accelerator table
1896 void DwarfDebug::emitAccelObjC() {
1897 AccelObjC.FinalizeTable(Asm, "ObjC");
1898 Asm->OutStreamer.SwitchSection(
1899 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1900 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1901 Asm->OutStreamer.EmitLabel(SectionBegin);
1903 // Emit the full data.
1904 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1907 // Emit namespace dies into a hashed accelerator table.
1908 void DwarfDebug::emitAccelNamespaces() {
1909 AccelNamespace.FinalizeTable(Asm, "namespac");
1910 Asm->OutStreamer.SwitchSection(
1911 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1912 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1913 Asm->OutStreamer.EmitLabel(SectionBegin);
1915 // Emit the full data.
1916 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1919 // Emit type dies into a hashed accelerator table.
1920 void DwarfDebug::emitAccelTypes() {
1922 AccelTypes.FinalizeTable(Asm, "types");
1923 Asm->OutStreamer.SwitchSection(
1924 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1925 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1926 Asm->OutStreamer.EmitLabel(SectionBegin);
1928 // Emit the full data.
1929 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1932 // Public name handling.
1933 // The format for the various pubnames:
1935 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1936 // for the DIE that is named.
1938 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1939 // into the CU and the index value is computed according to the type of value
1940 // for the DIE that is named.
1942 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1943 // it's the offset within the debug_info/debug_types dwo section, however, the
1944 // reference in the pubname header doesn't change.
1946 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1947 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1949 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1951 // We could have a specification DIE that has our most of our knowledge,
1952 // look for that now.
1953 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1955 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1956 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1957 Linkage = dwarf::GIEL_EXTERNAL;
1958 } else if (Die->findAttribute(dwarf::DW_AT_external))
1959 Linkage = dwarf::GIEL_EXTERNAL;
1961 switch (Die->getTag()) {
1962 case dwarf::DW_TAG_class_type:
1963 case dwarf::DW_TAG_structure_type:
1964 case dwarf::DW_TAG_union_type:
1965 case dwarf::DW_TAG_enumeration_type:
1966 return dwarf::PubIndexEntryDescriptor(
1967 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1968 ? dwarf::GIEL_STATIC
1969 : dwarf::GIEL_EXTERNAL);
1970 case dwarf::DW_TAG_typedef:
1971 case dwarf::DW_TAG_base_type:
1972 case dwarf::DW_TAG_subrange_type:
1973 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1974 case dwarf::DW_TAG_namespace:
1975 return dwarf::GIEK_TYPE;
1976 case dwarf::DW_TAG_subprogram:
1977 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1978 case dwarf::DW_TAG_constant:
1979 case dwarf::DW_TAG_variable:
1980 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1981 case dwarf::DW_TAG_enumerator:
1982 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1983 dwarf::GIEL_STATIC);
1985 return dwarf::GIEK_NONE;
1989 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1991 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1992 const MCSection *PSec =
1993 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1994 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1996 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1999 void DwarfDebug::emitDebugPubSection(
2000 bool GnuStyle, const MCSection *PSec, StringRef Name,
2001 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2002 for (const auto &NU : CUMap) {
2003 DwarfCompileUnit *TheU = NU.second;
2005 const auto &Globals = (TheU->*Accessor)();
2007 if (Globals.empty())
2010 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2012 unsigned ID = TheU->getUniqueID();
2014 // Start the dwarf pubnames section.
2015 Asm->OutStreamer.SwitchSection(PSec);
2018 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2019 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2020 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2021 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2023 Asm->OutStreamer.EmitLabel(BeginLabel);
2025 Asm->OutStreamer.AddComment("DWARF Version");
2026 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2028 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2029 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2031 Asm->OutStreamer.AddComment("Compilation Unit Length");
2032 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2034 // Emit the pubnames for this compilation unit.
2035 for (const auto &GI : Globals) {
2036 const char *Name = GI.getKeyData();
2037 const DIE *Entity = GI.second;
2039 Asm->OutStreamer.AddComment("DIE offset");
2040 Asm->EmitInt32(Entity->getOffset());
2043 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2044 Asm->OutStreamer.AddComment(
2045 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2046 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2047 Asm->EmitInt8(Desc.toBits());
2050 Asm->OutStreamer.AddComment("External Name");
2051 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2054 Asm->OutStreamer.AddComment("End Mark");
2056 Asm->OutStreamer.EmitLabel(EndLabel);
2060 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2061 const MCSection *PSec =
2062 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2063 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2065 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2068 // Emit visible names into a debug str section.
2069 void DwarfDebug::emitDebugStr() {
2070 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2071 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2074 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2075 const DebugLocEntry &Entry) {
2076 assert(Entry.getValues().size() == 1 &&
2077 "multi-value entries are not supported yet.");
2078 const DebugLocEntry::Value Value = Entry.getValues()[0];
2079 DIVariable DV(Value.getVariable());
2080 if (Value.isInt()) {
2081 DIBasicType BTy(resolve(DV.getType()));
2082 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2083 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2084 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2085 Streamer.EmitSLEB128(Value.getInt());
2087 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2088 Streamer.EmitULEB128(Value.getInt());
2090 } else if (Value.isLocation()) {
2091 MachineLocation Loc = Value.getLoc();
2092 if (!DV.hasComplexAddress())
2094 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2096 // Complex address entry.
2097 unsigned N = DV.getNumAddrElements();
2099 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2100 if (Loc.getOffset()) {
2102 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2103 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2104 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2105 Streamer.EmitSLEB128(DV.getAddrElement(1));
2107 // If first address element is OpPlus then emit
2108 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2109 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2110 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2114 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2117 // Emit remaining complex address elements.
2118 for (; i < N; ++i) {
2119 uint64_t Element = DV.getAddrElement(i);
2120 if (Element == DIBuilder::OpPlus) {
2121 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2122 Streamer.EmitULEB128(DV.getAddrElement(++i));
2123 } else if (Element == DIBuilder::OpDeref) {
2125 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2127 llvm_unreachable("unknown Opcode found in complex address");
2131 // else ... ignore constant fp. There is not any good way to
2132 // to represent them here in dwarf.
2136 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2137 Asm->OutStreamer.AddComment("Loc expr size");
2138 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2139 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2140 Asm->EmitLabelDifference(end, begin, 2);
2141 Asm->OutStreamer.EmitLabel(begin);
2143 APByteStreamer Streamer(*Asm);
2144 emitDebugLocEntry(Streamer, Entry);
2146 Asm->OutStreamer.EmitLabel(end);
2149 // Emit locations into the debug loc section.
2150 void DwarfDebug::emitDebugLoc() {
2151 // Start the dwarf loc section.
2152 Asm->OutStreamer.SwitchSection(
2153 Asm->getObjFileLowering().getDwarfLocSection());
2154 unsigned char Size = Asm->getDataLayout().getPointerSize();
2155 for (const auto &DebugLoc : DotDebugLocEntries) {
2156 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2157 for (const auto &Entry : DebugLoc.List) {
2158 // Set up the range. This range is relative to the entry point of the
2159 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2160 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2161 const DwarfCompileUnit *CU = Entry.getCU();
2162 if (CU->getRanges().size() == 1) {
2163 // Grab the begin symbol from the first range as our base.
2164 const MCSymbol *Base = CU->getRanges()[0].getStart();
2165 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2166 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2168 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2169 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2172 emitDebugLocEntryLocation(Entry);
2174 Asm->OutStreamer.EmitIntValue(0, Size);
2175 Asm->OutStreamer.EmitIntValue(0, Size);
2179 void DwarfDebug::emitDebugLocDWO() {
2180 Asm->OutStreamer.SwitchSection(
2181 Asm->getObjFileLowering().getDwarfLocDWOSection());
2182 for (const auto &DebugLoc : DotDebugLocEntries) {
2183 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2184 for (const auto &Entry : DebugLoc.List) {
2185 // Just always use start_length for now - at least that's one address
2186 // rather than two. We could get fancier and try to, say, reuse an
2187 // address we know we've emitted elsewhere (the start of the function?
2188 // The start of the CU or CU subrange that encloses this range?)
2189 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2190 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2191 Asm->EmitULEB128(idx);
2192 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2194 emitDebugLocEntryLocation(Entry);
2196 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2201 const MCSymbol *Start, *End;
2204 // Emit a debug aranges section, containing a CU lookup for any
2205 // address we can tie back to a CU.
2206 void DwarfDebug::emitDebugARanges() {
2207 // Start the dwarf aranges section.
2208 Asm->OutStreamer.SwitchSection(
2209 Asm->getObjFileLowering().getDwarfARangesSection());
2211 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2215 // Build a list of sections used.
2216 std::vector<const MCSection *> Sections;
2217 for (const auto &it : SectionMap) {
2218 const MCSection *Section = it.first;
2219 Sections.push_back(Section);
2222 // Sort the sections into order.
2223 // This is only done to ensure consistent output order across different runs.
2224 std::sort(Sections.begin(), Sections.end(), SectionSort);
2226 // Build a set of address spans, sorted by CU.
2227 for (const MCSection *Section : Sections) {
2228 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2229 if (List.size() < 2)
2232 // Sort the symbols by offset within the section.
2233 std::sort(List.begin(), List.end(),
2234 [&](const SymbolCU &A, const SymbolCU &B) {
2235 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2236 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2238 // Symbols with no order assigned should be placed at the end.
2239 // (e.g. section end labels)
2247 // If we have no section (e.g. common), just write out
2248 // individual spans for each symbol.
2250 for (const SymbolCU &Cur : List) {
2252 Span.Start = Cur.Sym;
2255 Spans[Cur.CU].push_back(Span);
2258 // Build spans between each label.
2259 const MCSymbol *StartSym = List[0].Sym;
2260 for (size_t n = 1, e = List.size(); n < e; n++) {
2261 const SymbolCU &Prev = List[n - 1];
2262 const SymbolCU &Cur = List[n];
2264 // Try and build the longest span we can within the same CU.
2265 if (Cur.CU != Prev.CU) {
2267 Span.Start = StartSym;
2269 Spans[Prev.CU].push_back(Span);
2276 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2278 // Build a list of CUs used.
2279 std::vector<DwarfCompileUnit *> CUs;
2280 for (const auto &it : Spans) {
2281 DwarfCompileUnit *CU = it.first;
2285 // Sort the CU list (again, to ensure consistent output order).
2286 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2287 return A->getUniqueID() < B->getUniqueID();
2290 // Emit an arange table for each CU we used.
2291 for (DwarfCompileUnit *CU : CUs) {
2292 std::vector<ArangeSpan> &List = Spans[CU];
2294 // Emit size of content not including length itself.
2295 unsigned ContentSize =
2296 sizeof(int16_t) + // DWARF ARange version number
2297 sizeof(int32_t) + // Offset of CU in the .debug_info section
2298 sizeof(int8_t) + // Pointer Size (in bytes)
2299 sizeof(int8_t); // Segment Size (in bytes)
2301 unsigned TupleSize = PtrSize * 2;
2303 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2305 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2307 ContentSize += Padding;
2308 ContentSize += (List.size() + 1) * TupleSize;
2310 // For each compile unit, write the list of spans it covers.
2311 Asm->OutStreamer.AddComment("Length of ARange Set");
2312 Asm->EmitInt32(ContentSize);
2313 Asm->OutStreamer.AddComment("DWARF Arange version number");
2314 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2315 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2316 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2317 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2318 Asm->EmitInt8(PtrSize);
2319 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2322 Asm->OutStreamer.EmitFill(Padding, 0xff);
2324 for (const ArangeSpan &Span : List) {
2325 Asm->EmitLabelReference(Span.Start, PtrSize);
2327 // Calculate the size as being from the span start to it's end.
2329 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2331 // For symbols without an end marker (e.g. common), we
2332 // write a single arange entry containing just that one symbol.
2333 uint64_t Size = SymSize[Span.Start];
2337 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2341 Asm->OutStreamer.AddComment("ARange terminator");
2342 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2343 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2347 // Emit visible names into a debug ranges section.
2348 void DwarfDebug::emitDebugRanges() {
2349 // Start the dwarf ranges section.
2350 Asm->OutStreamer.SwitchSection(
2351 Asm->getObjFileLowering().getDwarfRangesSection());
2353 // Size for our labels.
2354 unsigned char Size = Asm->getDataLayout().getPointerSize();
2356 // Grab the specific ranges for the compile units in the module.
2357 for (const auto &I : CUMap) {
2358 DwarfCompileUnit *TheCU = I.second;
2360 // Emit a symbol so we can find the beginning of our ranges.
2361 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2363 // Iterate over the misc ranges for the compile units in the module.
2364 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2365 // Emit our symbol so we can find the beginning of the range.
2366 Asm->OutStreamer.EmitLabel(List.getSym());
2368 for (const RangeSpan &Range : List.getRanges()) {
2369 const MCSymbol *Begin = Range.getStart();
2370 const MCSymbol *End = Range.getEnd();
2371 assert(Begin && "Range without a begin symbol?");
2372 assert(End && "Range without an end symbol?");
2373 if (TheCU->getRanges().size() == 1) {
2374 // Grab the begin symbol from the first range as our base.
2375 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2376 Asm->EmitLabelDifference(Begin, Base, Size);
2377 Asm->EmitLabelDifference(End, Base, Size);
2379 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2380 Asm->OutStreamer.EmitSymbolValue(End, Size);
2384 // And terminate the list with two 0 values.
2385 Asm->OutStreamer.EmitIntValue(0, Size);
2386 Asm->OutStreamer.EmitIntValue(0, Size);
2389 // Now emit a range for the CU itself.
2390 if (TheCU->getRanges().size() > 1) {
2391 Asm->OutStreamer.EmitLabel(
2392 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2393 for (const RangeSpan &Range : TheCU->getRanges()) {
2394 const MCSymbol *Begin = Range.getStart();
2395 const MCSymbol *End = Range.getEnd();
2396 assert(Begin && "Range without a begin symbol?");
2397 assert(End && "Range without an end symbol?");
2398 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2399 Asm->OutStreamer.EmitSymbolValue(End, Size);
2401 // And terminate the list with two 0 values.
2402 Asm->OutStreamer.EmitIntValue(0, Size);
2403 Asm->OutStreamer.EmitIntValue(0, Size);
2408 // DWARF5 Experimental Separate Dwarf emitters.
2410 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2411 std::unique_ptr<DwarfUnit> NewU) {
2412 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2413 U.getCUNode().getSplitDebugFilename());
2415 if (!CompilationDir.empty())
2416 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2418 addGnuPubAttributes(*NewU, Die);
2420 SkeletonHolder.addUnit(std::move(NewU));
2423 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2424 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2425 // DW_AT_addr_base, DW_AT_ranges_base.
2426 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2428 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2429 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2430 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2431 DwarfCompileUnit &NewCU = *OwnedUnit;
2432 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2433 DwarfInfoSectionSym);
2435 NewCU.initStmtList(DwarfLineSectionSym);
2437 initSkeletonUnit(CU, *Die, std::move(OwnedUnit));
2442 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2444 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2445 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2446 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2448 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2449 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2450 this, &SkeletonHolder);
2451 DwarfTypeUnit &NewTU = *OwnedUnit;
2452 NewTU.setTypeSignature(TU.getTypeSignature());
2453 NewTU.setType(nullptr);
2455 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2457 initSkeletonUnit(TU, *Die, std::move(OwnedUnit));
2461 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2462 // compile units that would normally be in debug_info.
2463 void DwarfDebug::emitDebugInfoDWO() {
2464 assert(useSplitDwarf() && "No split dwarf debug info?");
2465 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2466 // emit relocations into the dwo file.
2467 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2470 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2471 // abbreviations for the .debug_info.dwo section.
2472 void DwarfDebug::emitDebugAbbrevDWO() {
2473 assert(useSplitDwarf() && "No split dwarf?");
2474 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2477 void DwarfDebug::emitDebugLineDWO() {
2478 assert(useSplitDwarf() && "No split dwarf?");
2479 Asm->OutStreamer.SwitchSection(
2480 Asm->getObjFileLowering().getDwarfLineDWOSection());
2481 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2484 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2485 // string section and is identical in format to traditional .debug_str
2487 void DwarfDebug::emitDebugStrDWO() {
2488 assert(useSplitDwarf() && "No split dwarf?");
2489 const MCSection *OffSec =
2490 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2491 const MCSymbol *StrSym = DwarfStrSectionSym;
2492 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2496 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2497 if (!useSplitDwarf())
2500 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2501 return &SplitTypeUnitFileTable;
2504 static uint64_t makeTypeSignature(StringRef Identifier) {
2506 Hash.update(Identifier);
2507 // ... take the least significant 8 bytes and return those. Our MD5
2508 // implementation always returns its results in little endian, swap bytes
2510 MD5::MD5Result Result;
2512 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2515 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2516 StringRef Identifier, DIE &RefDie,
2517 DICompositeType CTy) {
2518 // Fast path if we're building some type units and one has already used the
2519 // address pool we know we're going to throw away all this work anyway, so
2520 // don't bother building dependent types.
2521 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2524 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2526 CU.addDIETypeSignature(RefDie, *TU);
2530 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2531 AddrPool.resetUsedFlag();
2533 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2535 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2536 this, &InfoHolder, getDwoLineTable(CU));
2537 DwarfTypeUnit &NewTU = *OwnedUnit;
2539 TypeUnitsUnderConstruction.push_back(std::make_pair(std::move(OwnedUnit), CTy));
2541 NewTU.addUInt(*UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2544 uint64_t Signature = makeTypeSignature(Identifier);
2545 NewTU.setTypeSignature(Signature);
2547 if (!useSplitDwarf())
2548 CU.applyStmtList(*UnitDie);
2552 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2553 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2555 NewTU.setType(NewTU.createTypeDIE(CTy));
2558 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2559 TypeUnitsUnderConstruction.clear();
2561 // Types referencing entries in the address table cannot be placed in type
2563 if (AddrPool.hasBeenUsed()) {
2565 // Remove all the types built while building this type.
2566 // This is pessimistic as some of these types might not be dependent on
2567 // the type that used an address.
2568 for (const auto &TU : TypeUnitsToAdd)
2569 DwarfTypeUnits.erase(TU.second);
2571 // Construct this type in the CU directly.
2572 // This is inefficient because all the dependent types will be rebuilt
2573 // from scratch, including building them in type units, discovering that
2574 // they depend on addresses, throwing them out and rebuilding them.
2575 CU.constructTypeDIE(RefDie, CTy);
2579 // If the type wasn't dependent on fission addresses, finish adding the type
2580 // and all its dependent types.
2581 for (auto &TU : TypeUnitsToAdd) {
2582 if (useSplitDwarf())
2583 TU.first->setSkeleton(constructSkeletonTU(*TU.first));
2584 InfoHolder.addUnit(std::move(TU.first));
2587 CU.addDIETypeSignature(RefDie, NewTU);
2590 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2591 MCSymbol *Begin, MCSymbol *End) {
2592 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2593 if (DwarfVersion < 4)
2594 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2596 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2599 // Accelerator table mutators - add each name along with its companion
2600 // DIE to the proper table while ensuring that the name that we're going
2601 // to reference is in the string table. We do this since the names we
2602 // add may not only be identical to the names in the DIE.
2603 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2604 if (!useDwarfAccelTables())
2606 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2610 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2611 if (!useDwarfAccelTables())
2613 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2617 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2618 if (!useDwarfAccelTables())
2620 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2624 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2625 if (!useDwarfAccelTables())
2627 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),