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.
424 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
425 LexicalScope *Scope) {
426 if (isLexicalScopeDIENull(Scope))
429 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
430 if (Scope->isAbstractScope())
433 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
435 // If we have multiple ranges, emit them into the range section.
436 if (ScopeRanges.size() > 1) {
437 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
441 // Construct the address range for this DIE.
442 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
443 MCSymbol *Start = getLabelBeforeInsn(RI->first);
444 MCSymbol *End = getLabelAfterInsn(RI->second);
445 assert(End && "End label should not be null!");
447 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
448 assert(End->isDefined() && "Invalid end label for an inlined scope!");
450 attachLowHighPC(TheCU, *ScopeDIE, Start, End);
455 // This scope represents inlined body of a function. Construct DIE to
456 // represent this concrete inlined copy of the function.
457 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
458 LexicalScope *Scope) {
459 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
460 assert(!ScopeRanges.empty() &&
461 "LexicalScope does not have instruction markers!");
463 if (!Scope->getScopeNode())
465 DIScope DS(Scope->getScopeNode());
466 DISubprogram InlinedSP = getDISubprogram(DS);
467 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
469 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
473 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
474 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
476 // If we have multiple ranges, emit them into the range section.
477 if (ScopeRanges.size() > 1)
478 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
480 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
481 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
482 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
484 if (!StartLabel || !EndLabel)
485 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
487 assert(StartLabel->isDefined() &&
488 "Invalid starting label for an inlined scope!");
489 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
491 attachLowHighPC(TheCU, *ScopeDIE, StartLabel, EndLabel);
494 InlinedSubprogramDIEs.insert(OriginDIE);
496 // Add the call site information to the DIE.
497 DILocation DL(Scope->getInlinedAt());
498 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
499 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
500 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
502 // Add name to the name table, we do this here because we're guaranteed
503 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
504 addSubprogramNames(InlinedSP, *ScopeDIE);
509 DIE *DwarfDebug::createScopeChildrenDIE(
510 DwarfCompileUnit &TheCU, LexicalScope *Scope,
511 SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
512 DIE *ObjectPointer = nullptr;
514 // Collect arguments for current function.
515 if (LScopes.isCurrentFunctionScope(Scope)) {
516 for (DbgVariable *ArgDV : CurrentFnArguments)
518 std::unique_ptr<DIE> Arg =
519 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope());
521 if (ArgDV->isObjectPointer())
522 ObjectPointer = Arg.get();
523 Children.push_back(std::move(Arg));
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)) {
538 std::unique_ptr<DIE> Variable =
539 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope());
541 Children.push_back(std::move(Variable));
542 if (DV->isObjectPointer())
543 ObjectPointer = Variable.get();
545 for (LexicalScope *LS : Scope->getChildren())
546 if (DIE *Nested = constructScopeDIE(TheCU, LS))
547 Children.push_back(std::unique_ptr<DIE>(Nested));
548 return ObjectPointer;
551 // Construct a DIE for this scope.
552 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
553 LexicalScope *Scope) {
554 if (!Scope || !Scope->getScopeNode())
557 DIScope DS(Scope->getScopeNode());
559 SmallVector<std::unique_ptr<DIE>, 8> Children;
560 DIE *ObjectPointer = nullptr;
561 bool ChildrenCreated = false;
563 // We try to create the scope DIE first, then the children DIEs. This will
564 // avoid creating un-used children then removing them later when we find out
565 // the scope DIE is null.
566 DIE *ScopeDIE = nullptr;
567 if (Scope->getInlinedAt())
568 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
569 else if (DS.isSubprogram()) {
570 ProcessedSPNodes.insert(DS);
571 if (Scope->isAbstractScope()) {
572 ScopeDIE = TheCU.getDIE(DS);
573 // Note down abstract DIE.
575 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
577 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
579 // Early exit when we know the scope DIE is going to be null.
580 if (isLexicalScopeDIENull(Scope))
583 // We create children here when we know the scope DIE is not going to be
584 // null and the children will be added to the scope DIE.
585 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
586 ChildrenCreated = true;
588 // There is no need to emit empty lexical block DIE.
589 std::pair<ImportedEntityMap::const_iterator,
590 ImportedEntityMap::const_iterator> Range =
592 ScopesWithImportedEntities.begin(),
593 ScopesWithImportedEntities.end(),
594 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
596 if (Children.empty() && Range.first == Range.second)
598 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
599 assert(ScopeDIE && "Scope DIE should not be null.");
600 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
602 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
606 assert(Children.empty() &&
607 "We create children only when the scope DIE is not null.");
610 if (!ChildrenCreated)
611 // We create children when the scope DIE is not null.
612 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
615 for (auto &I : Children)
616 ScopeDIE->addChild(std::move(I));
618 if (DS.isSubprogram() && ObjectPointer != nullptr)
619 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
624 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
625 if (!GenerateGnuPubSections)
628 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
631 // Create new DwarfCompileUnit for the given metadata node with tag
632 // DW_TAG_compile_unit.
633 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
634 StringRef FN = DIUnit.getFilename();
635 CompilationDir = DIUnit.getDirectory();
637 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
638 auto OwnedUnit = make_unique<DwarfCompileUnit>(
639 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
640 DwarfCompileUnit &NewCU = *OwnedUnit;
641 InfoHolder.addUnit(std::move(OwnedUnit));
643 // LTO with assembly output shares a single line table amongst multiple CUs.
644 // To avoid the compilation directory being ambiguous, let the line table
645 // explicitly describe the directory of all files, never relying on the
646 // compilation directory.
647 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
648 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
649 NewCU.getUniqueID(), CompilationDir);
651 NewCU.addString(*Die, dwarf::DW_AT_producer, DIUnit.getProducer());
652 NewCU.addUInt(*Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
653 DIUnit.getLanguage());
654 NewCU.addString(*Die, dwarf::DW_AT_name, FN);
656 if (!useSplitDwarf()) {
657 NewCU.initStmtList(DwarfLineSectionSym);
659 // If we're using split dwarf the compilation dir is going to be in the
660 // skeleton CU and so we don't need to duplicate it here.
661 if (!CompilationDir.empty())
662 NewCU.addString(*Die, dwarf::DW_AT_comp_dir, CompilationDir);
664 addGnuPubAttributes(NewCU, *Die);
667 if (DIUnit.isOptimized())
668 NewCU.addFlag(*Die, dwarf::DW_AT_APPLE_optimized);
670 StringRef Flags = DIUnit.getFlags();
672 NewCU.addString(*Die, dwarf::DW_AT_APPLE_flags, Flags);
674 if (unsigned RVer = DIUnit.getRunTimeVersion())
675 NewCU.addUInt(*Die, dwarf::DW_AT_APPLE_major_runtime_vers,
676 dwarf::DW_FORM_data1, RVer);
681 if (useSplitDwarf()) {
682 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
683 DwarfInfoDWOSectionSym);
684 NewCU.setSkeleton(constructSkeletonCU(NewCU));
686 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
687 DwarfInfoSectionSym);
689 CUMap.insert(std::make_pair(DIUnit, &NewCU));
690 CUDieMap.insert(std::make_pair(Die, &NewCU));
694 // Construct subprogram DIE.
695 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
697 // FIXME: We should only call this routine once, however, during LTO if a
698 // program is defined in multiple CUs we could end up calling it out of
699 // beginModule as we walk the CUs.
701 DwarfCompileUnit *&CURef = SPMap[N];
707 if (!SP.isDefinition())
708 // This is a method declaration which will be handled while constructing
712 DIE &SubprogramDie = *TheCU.getOrCreateSubprogramDIE(SP);
714 // Expose as a global name.
715 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
718 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
720 DIImportedEntity Module(N);
721 assert(Module.Verify());
722 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
723 constructImportedEntityDIE(TheCU, Module, D);
726 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
727 const MDNode *N, DIE *Context) {
728 DIImportedEntity Module(N);
729 assert(Module.Verify());
730 return constructImportedEntityDIE(TheCU, Module, Context);
733 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
734 const DIImportedEntity &Module,
736 assert(Module.Verify() &&
737 "Use one of the MDNode * overloads to handle invalid metadata");
738 assert(Context && "Should always have a context for an imported_module");
739 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), *Context, Module);
741 DIDescriptor Entity = resolve(Module.getEntity());
742 if (Entity.isNameSpace())
743 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
744 else if (Entity.isSubprogram())
745 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
746 else if (Entity.isType())
747 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
749 EntityDie = TheCU.getDIE(Entity);
750 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
751 Module.getContext().getFilename(),
752 Module.getContext().getDirectory());
753 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
754 StringRef Name = Module.getName();
756 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
759 // Emit all Dwarf sections that should come prior to the content. Create
760 // global DIEs and emit initial debug info sections. This is invoked by
761 // the target AsmPrinter.
762 void DwarfDebug::beginModule() {
763 if (DisableDebugInfoPrinting)
766 const Module *M = MMI->getModule();
768 // If module has named metadata anchors then use them, otherwise scan the
769 // module using debug info finder to collect debug info.
770 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
773 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
775 // Emit initial sections so we can reference labels later.
778 SingleCU = CU_Nodes->getNumOperands() == 1;
780 for (MDNode *N : CU_Nodes->operands()) {
781 DICompileUnit CUNode(N);
782 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
783 DIArray ImportedEntities = CUNode.getImportedEntities();
784 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
785 ScopesWithImportedEntities.push_back(std::make_pair(
786 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
787 ImportedEntities.getElement(i)));
788 std::sort(ScopesWithImportedEntities.begin(),
789 ScopesWithImportedEntities.end(), less_first());
790 DIArray GVs = CUNode.getGlobalVariables();
791 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
792 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
793 DIArray SPs = CUNode.getSubprograms();
794 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
795 constructSubprogramDIE(CU, SPs.getElement(i));
796 DIArray EnumTypes = CUNode.getEnumTypes();
797 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
798 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
799 DIArray RetainedTypes = CUNode.getRetainedTypes();
800 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
801 DIType Ty(RetainedTypes.getElement(i));
802 // The retained types array by design contains pointers to
803 // MDNodes rather than DIRefs. Unique them here.
804 DIType UniqueTy(resolve(Ty.getRef()));
805 CU.getOrCreateTypeDIE(UniqueTy);
807 // Emit imported_modules last so that the relevant context is already
809 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
810 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
813 // Tell MMI that we have debug info.
814 MMI->setDebugInfoAvailability(true);
816 // Prime section data.
817 SectionMap[Asm->getObjFileLowering().getTextSection()];
820 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
821 void DwarfDebug::computeInlinedDIEs() {
822 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
823 for (DIE *ISP : InlinedSubprogramDIEs)
824 FirstCU->addUInt(*ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
826 for (const auto &AI : AbstractSPDies) {
827 DIE &ISP = *AI.second;
828 if (InlinedSubprogramDIEs.count(&ISP))
830 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
834 // Collect info for variables that were optimized out.
835 void DwarfDebug::collectDeadVariables() {
836 const Module *M = MMI->getModule();
838 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
839 for (MDNode *N : CU_Nodes->operands()) {
840 DICompileUnit TheCU(N);
841 DIArray Subprograms = TheCU.getSubprograms();
842 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
843 DISubprogram SP(Subprograms.getElement(i));
844 if (ProcessedSPNodes.count(SP) != 0)
846 if (!SP.isSubprogram())
848 if (!SP.isDefinition())
850 DIArray Variables = SP.getVariables();
851 if (Variables.getNumElements() == 0)
854 // Construct subprogram DIE and add variables DIEs.
855 DwarfCompileUnit *SPCU =
856 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
857 assert(SPCU && "Unable to find Compile Unit!");
858 // FIXME: See the comment in constructSubprogramDIE about duplicate
860 constructSubprogramDIE(*SPCU, SP);
861 DIE *SPDIE = SPCU->getDIE(SP);
862 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
863 DIVariable DV(Variables.getElement(vi));
864 if (!DV.isVariable())
866 DbgVariable NewVar(DV, nullptr, this);
867 SPDIE->addChild(SPCU->constructVariableDIE(NewVar, false));
874 void DwarfDebug::finalizeModuleInfo() {
875 // Collect info for variables that were optimized out.
876 collectDeadVariables();
878 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
879 computeInlinedDIEs();
881 // Handle anything that needs to be done on a per-unit basis after
882 // all other generation.
883 for (const auto &TheU : getUnits()) {
884 // Emit DW_AT_containing_type attribute to connect types with their
885 // vtable holding type.
886 TheU->constructContainingTypeDIEs();
888 // Add CU specific attributes if we need to add any.
889 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
890 // If we're splitting the dwarf out now that we've got the entire
891 // CU then add the dwo id to it.
892 DwarfCompileUnit *SkCU =
893 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
894 if (useSplitDwarf()) {
895 // Emit a unique identifier for this CU.
896 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
897 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
898 dwarf::DW_FORM_data8, ID);
899 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
900 dwarf::DW_FORM_data8, ID);
902 // We don't keep track of which addresses are used in which CU so this
903 // is a bit pessimistic under LTO.
904 if (!AddrPool.isEmpty())
905 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
906 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
907 DwarfAddrSectionSym);
908 if (!TheU->getRangeLists().empty())
909 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
910 dwarf::DW_AT_GNU_ranges_base,
911 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
914 // If we have code split among multiple sections or non-contiguous
915 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
916 // remain in the .o file, otherwise add a DW_AT_low_pc.
917 // FIXME: We should use ranges allow reordering of code ala
918 // .subsections_via_symbols in mach-o. This would mean turning on
919 // ranges for all subprogram DIEs for mach-o.
920 DwarfCompileUnit &U =
921 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
922 unsigned NumRanges = TheU->getRanges().size();
925 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
926 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
927 DwarfDebugRangeSectionSym);
929 // A DW_AT_low_pc attribute may also be specified in combination with
930 // DW_AT_ranges to specify the default base address for use in
931 // location lists (see Section 2.6.2) and range lists (see Section
933 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
936 RangeSpan &Range = TheU->getRanges().back();
937 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
939 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
946 // Compute DIE offsets and sizes.
947 InfoHolder.computeSizeAndOffsets();
949 SkeletonHolder.computeSizeAndOffsets();
952 void DwarfDebug::endSections() {
953 // Filter labels by section.
954 for (const SymbolCU &SCU : ArangeLabels) {
955 if (SCU.Sym->isInSection()) {
956 // Make a note of this symbol and it's section.
957 const MCSection *Section = &SCU.Sym->getSection();
958 if (!Section->getKind().isMetadata())
959 SectionMap[Section].push_back(SCU);
961 // Some symbols (e.g. common/bss on mach-o) can have no section but still
962 // appear in the output. This sucks as we rely on sections to build
963 // arange spans. We can do it without, but it's icky.
964 SectionMap[nullptr].push_back(SCU);
968 // Build a list of sections used.
969 std::vector<const MCSection *> Sections;
970 for (const auto &it : SectionMap) {
971 const MCSection *Section = it.first;
972 Sections.push_back(Section);
975 // Sort the sections into order.
976 // This is only done to ensure consistent output order across different runs.
977 std::sort(Sections.begin(), Sections.end(), SectionSort);
979 // Add terminating symbols for each section.
980 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
981 const MCSection *Section = Sections[ID];
982 MCSymbol *Sym = nullptr;
985 // We can't call MCSection::getLabelEndName, as it's only safe to do so
986 // if we know the section name up-front. For user-created sections, the
987 // resulting label may not be valid to use as a label. (section names can
988 // use a greater set of characters on some systems)
989 Sym = Asm->GetTempSymbol("debug_end", ID);
990 Asm->OutStreamer.SwitchSection(Section);
991 Asm->OutStreamer.EmitLabel(Sym);
994 // Insert a final terminator.
995 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
999 // Emit all Dwarf sections that should come after the content.
1000 void DwarfDebug::endModule() {
1007 // End any existing sections.
1008 // TODO: Does this need to happen?
1011 // Finalize the debug info for the module.
1012 finalizeModuleInfo();
1016 // Emit all the DIEs into a debug info section.
1019 // Corresponding abbreviations into a abbrev section.
1020 emitAbbreviations();
1022 // Emit info into a debug aranges section.
1023 if (GenerateARangeSection)
1026 // Emit info into a debug ranges section.
1029 if (useSplitDwarf()) {
1032 emitDebugAbbrevDWO();
1034 // Emit DWO addresses.
1035 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1038 // Emit info into a debug loc section.
1041 // Emit info into the dwarf accelerator table sections.
1042 if (useDwarfAccelTables()) {
1045 emitAccelNamespaces();
1049 // Emit the pubnames and pubtypes sections if requested.
1050 if (HasDwarfPubSections) {
1051 emitDebugPubNames(GenerateGnuPubSections);
1052 emitDebugPubTypes(GenerateGnuPubSections);
1058 // Reset these for the next Module if we have one.
1062 // Find abstract variable, if any, associated with Var.
1063 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1064 DebugLoc ScopeLoc) {
1065 LLVMContext &Ctx = DV->getContext();
1066 // More then one inlined variable corresponds to one abstract variable.
1067 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1068 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1070 return AbsDbgVariable;
1072 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1076 AbsDbgVariable = new DbgVariable(Var, nullptr, this);
1077 addScopeVariable(Scope, AbsDbgVariable);
1078 AbstractVariables[Var] = AbsDbgVariable;
1079 return AbsDbgVariable;
1082 // If Var is a current function argument then add it to CurrentFnArguments list.
1083 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1084 if (!LScopes.isCurrentFunctionScope(Scope))
1086 DIVariable DV = Var->getVariable();
1087 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1089 unsigned ArgNo = DV.getArgNumber();
1093 size_t Size = CurrentFnArguments.size();
1095 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1096 // llvm::Function argument size is not good indicator of how many
1097 // arguments does the function have at source level.
1099 CurrentFnArguments.resize(ArgNo * 2);
1100 CurrentFnArguments[ArgNo - 1] = Var;
1104 // Collect variable information from side table maintained by MMI.
1105 void DwarfDebug::collectVariableInfoFromMMITable(
1106 SmallPtrSet<const MDNode *, 16> &Processed) {
1107 for (const auto &VI : MMI->getVariableDbgInfo()) {
1110 Processed.insert(VI.Var);
1111 DIVariable DV(VI.Var);
1112 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1114 // If variable scope is not found then skip this variable.
1118 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1119 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1120 RegVar->setFrameIndex(VI.Slot);
1121 if (!addCurrentFnArgument(RegVar, Scope))
1122 addScopeVariable(Scope, RegVar);
1124 AbsDbgVariable->setFrameIndex(VI.Slot);
1128 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1130 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1131 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1132 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1133 MI->getOperand(0).getReg() &&
1134 (MI->getOperand(1).isImm() ||
1135 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1138 // Get .debug_loc entry for the instruction range starting at MI.
1139 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1140 const MCSymbol *FLabel,
1141 const MCSymbol *SLabel,
1142 const MachineInstr *MI,
1143 DwarfCompileUnit *Unit) {
1144 const MDNode *Var = MI->getDebugVariable();
1146 assert(MI->getNumOperands() == 3);
1147 if (MI->getOperand(0).isReg()) {
1148 MachineLocation MLoc;
1149 // If the second operand is an immediate, this is a
1150 // register-indirect address.
1151 if (!MI->getOperand(1).isImm())
1152 MLoc.set(MI->getOperand(0).getReg());
1154 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1155 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1157 if (MI->getOperand(0).isImm())
1158 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1159 if (MI->getOperand(0).isFPImm())
1160 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1162 if (MI->getOperand(0).isCImm())
1163 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1166 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1169 // Find variables for each lexical scope.
1171 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1173 // Grab the variable info that was squirreled away in the MMI side-table.
1174 collectVariableInfoFromMMITable(Processed);
1176 for (const MDNode *Var : UserVariables) {
1177 if (Processed.count(Var))
1180 // History contains relevant DBG_VALUE instructions for Var and instructions
1182 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1183 if (History.empty())
1185 const MachineInstr *MInsn = History.front();
1188 LexicalScope *Scope = nullptr;
1189 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1190 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1191 Scope = LScopes.getCurrentFunctionScope();
1192 else if (MDNode *IA = DV.getInlinedAt())
1193 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1195 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1196 // If variable scope is not found then skip this variable.
1200 Processed.insert(DV);
1201 assert(MInsn->isDebugValue() && "History must begin with debug value");
1202 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1203 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1204 if (!addCurrentFnArgument(RegVar, Scope))
1205 addScopeVariable(Scope, RegVar);
1207 AbsVar->setMInsn(MInsn);
1209 // Simplify ranges that are fully coalesced.
1210 if (History.size() <= 1 ||
1211 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1212 RegVar->setMInsn(MInsn);
1216 // Handle multiple DBG_VALUE instructions describing one variable.
1217 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1219 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1220 DebugLocList &LocList = DotDebugLocEntries.back();
1222 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1223 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1224 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1225 HI = History.begin(),
1228 const MachineInstr *Begin = *HI;
1229 assert(Begin->isDebugValue() && "Invalid History entry");
1231 // Check if DBG_VALUE is truncating a range.
1232 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1233 !Begin->getOperand(0).getReg())
1236 // Compute the range for a register location.
1237 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1238 const MCSymbol *SLabel = nullptr;
1241 // If Begin is the last instruction in History then its value is valid
1242 // until the end of the function.
1243 SLabel = FunctionEndSym;
1245 const MachineInstr *End = HI[1];
1246 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1247 << "\t" << *Begin << "\t" << *End << "\n");
1248 if (End->isDebugValue())
1249 SLabel = getLabelBeforeInsn(End);
1251 // End is a normal instruction clobbering the range.
1252 SLabel = getLabelAfterInsn(End);
1253 assert(SLabel && "Forgot label after clobber instruction");
1258 // The value is valid until the next DBG_VALUE or clobber.
1259 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1260 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1261 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1262 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1263 DebugLoc.push_back(std::move(Loc));
1267 // Collect info for variables that were optimized out.
1268 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1269 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1270 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1271 DIVariable DV(Variables.getElement(i));
1272 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1274 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1275 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1279 // Return Label preceding the instruction.
1280 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1281 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1282 assert(Label && "Didn't insert label before instruction");
1286 // Return Label immediately following the instruction.
1287 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1288 return LabelsAfterInsn.lookup(MI);
1291 // Process beginning of an instruction.
1292 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1295 // Check if source location changes, but ignore DBG_VALUE locations.
1296 if (!MI->isDebugValue()) {
1297 DebugLoc DL = MI->getDebugLoc();
1298 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1301 if (DL == PrologEndLoc) {
1302 Flags |= DWARF2_FLAG_PROLOGUE_END;
1303 PrologEndLoc = DebugLoc();
1305 if (PrologEndLoc.isUnknown())
1306 Flags |= DWARF2_FLAG_IS_STMT;
1308 if (!DL.isUnknown()) {
1309 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1310 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1312 recordSourceLine(0, 0, nullptr, 0);
1316 // Insert labels where requested.
1317 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1318 LabelsBeforeInsn.find(MI);
1321 if (I == LabelsBeforeInsn.end())
1324 // Label already assigned.
1329 PrevLabel = MMI->getContext().CreateTempSymbol();
1330 Asm->OutStreamer.EmitLabel(PrevLabel);
1332 I->second = PrevLabel;
1335 // Process end of an instruction.
1336 void DwarfDebug::endInstruction() {
1338 // Don't create a new label after DBG_VALUE instructions.
1339 // They don't generate code.
1340 if (!CurMI->isDebugValue())
1341 PrevLabel = nullptr;
1343 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1344 LabelsAfterInsn.find(CurMI);
1348 if (I == LabelsAfterInsn.end())
1351 // Label already assigned.
1355 // We need a label after this instruction.
1357 PrevLabel = MMI->getContext().CreateTempSymbol();
1358 Asm->OutStreamer.EmitLabel(PrevLabel);
1360 I->second = PrevLabel;
1363 // Each LexicalScope has first instruction and last instruction to mark
1364 // beginning and end of a scope respectively. Create an inverse map that list
1365 // scopes starts (and ends) with an instruction. One instruction may start (or
1366 // end) multiple scopes. Ignore scopes that are not reachable.
1367 void DwarfDebug::identifyScopeMarkers() {
1368 SmallVector<LexicalScope *, 4> WorkList;
1369 WorkList.push_back(LScopes.getCurrentFunctionScope());
1370 while (!WorkList.empty()) {
1371 LexicalScope *S = WorkList.pop_back_val();
1373 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1374 if (!Children.empty())
1375 WorkList.append(Children.begin(), Children.end());
1377 if (S->isAbstractScope())
1380 for (const InsnRange &R : S->getRanges()) {
1381 assert(R.first && "InsnRange does not have first instruction!");
1382 assert(R.second && "InsnRange does not have second instruction!");
1383 requestLabelBeforeInsn(R.first);
1384 requestLabelAfterInsn(R.second);
1389 // Gather pre-function debug information. Assumes being called immediately
1390 // after the function entry point has been emitted.
1391 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1394 // If there's no debug info for the function we're not going to do anything.
1395 if (!MMI->hasDebugInfo())
1398 // Grab the lexical scopes for the function, if we don't have any of those
1399 // then we're not going to be able to do anything.
1400 LScopes.initialize(*MF);
1401 if (LScopes.empty())
1404 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1406 // Make sure that each lexical scope will have a begin/end label.
1407 identifyScopeMarkers();
1409 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1410 // belongs to so that we add to the correct per-cu line table in the
1412 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1413 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1414 assert(TheCU && "Unable to find compile unit!");
1415 if (Asm->OutStreamer.hasRawTextSupport())
1416 // Use a single line table if we are generating assembly.
1417 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1419 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1421 // Emit a label for the function so that we have a beginning address.
1422 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1423 // Assumes in correct section after the entry point.
1424 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1426 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1427 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1428 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1430 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1432 bool AtBlockEntry = true;
1433 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1435 const MachineInstr *MI = II;
1437 if (MI->isDebugValue()) {
1438 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1440 // Keep track of user variables.
1441 const MDNode *Var = MI->getDebugVariable();
1443 // Variable is in a register, we need to check for clobbers.
1444 if (isDbgValueInDefinedReg(MI))
1445 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1447 // Check the history of this variable.
1448 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1449 if (History.empty()) {
1450 UserVariables.push_back(Var);
1451 // The first mention of a function argument gets the FunctionBeginSym
1452 // label, so arguments are visible when breaking at function entry.
1454 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1455 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1456 LabelsBeforeInsn[MI] = FunctionBeginSym;
1458 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1459 const MachineInstr *Prev = History.back();
1460 if (Prev->isDebugValue()) {
1461 // Coalesce identical entries at the end of History.
1462 if (History.size() >= 2 &&
1463 Prev->isIdenticalTo(History[History.size() - 2])) {
1464 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1465 << "\t" << *Prev << "\t"
1466 << *History[History.size() - 2] << "\n");
1470 // Terminate old register assignments that don't reach MI;
1471 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1472 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1473 isDbgValueInDefinedReg(Prev)) {
1474 // Previous register assignment needs to terminate at the end of
1476 MachineBasicBlock::const_iterator LastMI =
1477 PrevMBB->getLastNonDebugInstr();
1478 if (LastMI == PrevMBB->end()) {
1479 // Drop DBG_VALUE for empty range.
1480 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1481 << "\t" << *Prev << "\n");
1483 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1484 // Terminate after LastMI.
1485 History.push_back(LastMI);
1489 History.push_back(MI);
1491 // Not a DBG_VALUE instruction.
1492 if (!MI->isPosition())
1493 AtBlockEntry = false;
1495 // First known non-DBG_VALUE and non-frame setup location marks
1496 // the beginning of the function body.
1497 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1498 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1499 PrologEndLoc = MI->getDebugLoc();
1501 // Check if the instruction clobbers any registers with debug vars.
1502 for (const MachineOperand &MO : MI->operands()) {
1503 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1505 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1508 const MDNode *Var = LiveUserVar[Reg];
1511 // Reg is now clobbered.
1512 LiveUserVar[Reg] = nullptr;
1514 // Was MD last defined by a DBG_VALUE referring to Reg?
1515 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1516 if (HistI == DbgValues.end())
1518 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1519 if (History.empty())
1521 const MachineInstr *Prev = History.back();
1522 // Sanity-check: Register assignments are terminated at the end of
1524 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1526 // Is the variable still in Reg?
1527 if (!isDbgValueInDefinedReg(Prev) ||
1528 Prev->getOperand(0).getReg() != Reg)
1530 // Var is clobbered. Make sure the next instruction gets a label.
1531 History.push_back(MI);
1538 for (auto &I : DbgValues) {
1539 SmallVectorImpl<const MachineInstr *> &History = I.second;
1540 if (History.empty())
1543 // Make sure the final register assignments are terminated.
1544 const MachineInstr *Prev = History.back();
1545 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1546 const MachineBasicBlock *PrevMBB = Prev->getParent();
1547 MachineBasicBlock::const_iterator LastMI =
1548 PrevMBB->getLastNonDebugInstr();
1549 if (LastMI == PrevMBB->end())
1550 // Drop DBG_VALUE for empty range.
1552 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1553 // Terminate after LastMI.
1554 History.push_back(LastMI);
1557 // Request labels for the full history.
1558 for (const MachineInstr *MI : History) {
1559 if (MI->isDebugValue())
1560 requestLabelBeforeInsn(MI);
1562 requestLabelAfterInsn(MI);
1566 PrevInstLoc = DebugLoc();
1567 PrevLabel = FunctionBeginSym;
1569 // Record beginning of function.
1570 if (!PrologEndLoc.isUnknown()) {
1571 DebugLoc FnStartDL =
1572 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1574 FnStartDL.getLine(), FnStartDL.getCol(),
1575 FnStartDL.getScope(MF->getFunction()->getContext()),
1576 // We'd like to list the prologue as "not statements" but GDB behaves
1577 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1578 DWARF2_FLAG_IS_STMT);
1582 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1583 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1584 DIVariable DV = Var->getVariable();
1585 // Variables with positive arg numbers are parameters.
1586 if (unsigned ArgNum = DV.getArgNumber()) {
1587 // Keep all parameters in order at the start of the variable list to ensure
1588 // function types are correct (no out-of-order parameters)
1590 // This could be improved by only doing it for optimized builds (unoptimized
1591 // builds have the right order to begin with), searching from the back (this
1592 // would catch the unoptimized case quickly), or doing a binary search
1593 // rather than linear search.
1594 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1595 while (I != Vars.end()) {
1596 unsigned CurNum = (*I)->getVariable().getArgNumber();
1597 // A local (non-parameter) variable has been found, insert immediately
1601 // A later indexed parameter has been found, insert immediately before it.
1602 if (CurNum > ArgNum)
1606 Vars.insert(I, Var);
1610 Vars.push_back(Var);
1613 // Gather and emit post-function debug information.
1614 void DwarfDebug::endFunction(const MachineFunction *MF) {
1615 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1616 // though the beginFunction may not be called at all.
1617 // We should handle both cases.
1621 assert(CurFn == MF);
1624 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1625 // If we don't have a lexical scope for this function then there will
1626 // be a hole in the range information. Keep note of this by setting the
1627 // previously used section to nullptr.
1628 PrevSection = nullptr;
1634 // Define end label for subprogram.
1635 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1636 // Assumes in correct section after the entry point.
1637 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1639 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1640 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1642 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1643 collectVariableInfo(ProcessedVars);
1645 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1646 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1648 // Construct abstract scopes.
1649 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1650 DISubprogram SP(AScope->getScopeNode());
1651 if (SP.isSubprogram()) {
1652 // Collect info for variables that were optimized out.
1653 DIArray Variables = SP.getVariables();
1654 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1655 DIVariable DV(Variables.getElement(i));
1656 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1658 // Check that DbgVariable for DV wasn't created earlier, when
1659 // findAbstractVariable() was called for inlined instance of DV.
1660 LLVMContext &Ctx = DV->getContext();
1661 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1662 if (AbstractVariables.lookup(CleanDV))
1664 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1665 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1668 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1669 constructScopeDIE(TheCU, AScope);
1672 DIE &CurFnDIE = *constructScopeDIE(TheCU, FnScope);
1673 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1674 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1676 // Add the range of this function to the list of ranges for the CU.
1677 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1678 TheCU.addRange(std::move(Span));
1679 PrevSection = Asm->getCurrentSection();
1683 for (auto &I : ScopeVariables)
1684 DeleteContainerPointers(I.second);
1685 ScopeVariables.clear();
1686 DeleteContainerPointers(CurrentFnArguments);
1687 UserVariables.clear();
1689 AbstractVariables.clear();
1690 LabelsBeforeInsn.clear();
1691 LabelsAfterInsn.clear();
1692 PrevLabel = nullptr;
1696 // Register a source line with debug info. Returns the unique label that was
1697 // emitted and which provides correspondence to the source line list.
1698 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1703 unsigned Discriminator = 0;
1705 DIDescriptor Scope(S);
1707 if (Scope.isCompileUnit()) {
1708 DICompileUnit CU(S);
1709 Fn = CU.getFilename();
1710 Dir = CU.getDirectory();
1711 } else if (Scope.isFile()) {
1713 Fn = F.getFilename();
1714 Dir = F.getDirectory();
1715 } else if (Scope.isSubprogram()) {
1717 Fn = SP.getFilename();
1718 Dir = SP.getDirectory();
1719 } else if (Scope.isLexicalBlockFile()) {
1720 DILexicalBlockFile DBF(S);
1721 Fn = DBF.getFilename();
1722 Dir = DBF.getDirectory();
1723 } else if (Scope.isLexicalBlock()) {
1724 DILexicalBlock DB(S);
1725 Fn = DB.getFilename();
1726 Dir = DB.getDirectory();
1727 Discriminator = DB.getDiscriminator();
1729 llvm_unreachable("Unexpected scope info");
1731 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1732 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1733 .getOrCreateSourceID(Fn, Dir);
1735 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1739 //===----------------------------------------------------------------------===//
1741 //===----------------------------------------------------------------------===//
1743 // Emit initial Dwarf sections with a label at the start of each one.
1744 void DwarfDebug::emitSectionLabels() {
1745 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1747 // Dwarf sections base addresses.
1748 DwarfInfoSectionSym =
1749 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1750 if (useSplitDwarf())
1751 DwarfInfoDWOSectionSym =
1752 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1753 DwarfAbbrevSectionSym =
1754 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1755 if (useSplitDwarf())
1756 DwarfAbbrevDWOSectionSym = emitSectionSym(
1757 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1758 if (GenerateARangeSection)
1759 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1761 DwarfLineSectionSym =
1762 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1763 if (GenerateGnuPubSections) {
1764 DwarfGnuPubNamesSectionSym =
1765 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1766 DwarfGnuPubTypesSectionSym =
1767 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1768 } else if (HasDwarfPubSections) {
1769 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1770 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1773 DwarfStrSectionSym =
1774 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1775 if (useSplitDwarf()) {
1776 DwarfStrDWOSectionSym =
1777 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1778 DwarfAddrSectionSym =
1779 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1780 DwarfDebugLocSectionSym =
1781 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1783 DwarfDebugLocSectionSym =
1784 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1785 DwarfDebugRangeSectionSym =
1786 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1789 // Recursively emits a debug information entry.
1790 void DwarfDebug::emitDIE(DIE &Die) {
1791 // Get the abbreviation for this DIE.
1792 const DIEAbbrev &Abbrev = Die.getAbbrev();
1794 // Emit the code (index) for the abbreviation.
1795 if (Asm->isVerbose())
1796 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1797 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1798 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1799 dwarf::TagString(Abbrev.getTag()));
1800 Asm->EmitULEB128(Abbrev.getNumber());
1802 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1803 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1805 // Emit the DIE attribute values.
1806 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1807 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1808 dwarf::Form Form = AbbrevData[i].getForm();
1809 assert(Form && "Too many attributes for DIE (check abbreviation)");
1811 if (Asm->isVerbose()) {
1812 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1813 if (Attr == dwarf::DW_AT_accessibility)
1814 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1815 cast<DIEInteger>(Values[i])->getValue()));
1818 // Emit an attribute using the defined form.
1819 Values[i]->EmitValue(Asm, Form);
1822 // Emit the DIE children if any.
1823 if (Abbrev.hasChildren()) {
1824 for (auto &Child : Die.getChildren())
1827 Asm->OutStreamer.AddComment("End Of Children Mark");
1832 // Emit the debug info section.
1833 void DwarfDebug::emitDebugInfo() {
1834 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1836 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1839 // Emit the abbreviation section.
1840 void DwarfDebug::emitAbbreviations() {
1841 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1843 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1846 // Emit the last address of the section and the end of the line matrix.
1847 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1848 // Define last address of section.
1849 Asm->OutStreamer.AddComment("Extended Op");
1852 Asm->OutStreamer.AddComment("Op size");
1853 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1854 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1855 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1857 Asm->OutStreamer.AddComment("Section end label");
1859 Asm->OutStreamer.EmitSymbolValue(
1860 Asm->GetTempSymbol("section_end", SectionEnd),
1861 Asm->getDataLayout().getPointerSize());
1863 // Mark end of matrix.
1864 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1870 // Emit visible names into a hashed accelerator table section.
1871 void DwarfDebug::emitAccelNames() {
1872 AccelNames.FinalizeTable(Asm, "Names");
1873 Asm->OutStreamer.SwitchSection(
1874 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1875 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1876 Asm->OutStreamer.EmitLabel(SectionBegin);
1878 // Emit the full data.
1879 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1882 // Emit objective C classes and categories into a hashed accelerator table
1884 void DwarfDebug::emitAccelObjC() {
1885 AccelObjC.FinalizeTable(Asm, "ObjC");
1886 Asm->OutStreamer.SwitchSection(
1887 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1888 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1889 Asm->OutStreamer.EmitLabel(SectionBegin);
1891 // Emit the full data.
1892 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1895 // Emit namespace dies into a hashed accelerator table.
1896 void DwarfDebug::emitAccelNamespaces() {
1897 AccelNamespace.FinalizeTable(Asm, "namespac");
1898 Asm->OutStreamer.SwitchSection(
1899 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1900 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1901 Asm->OutStreamer.EmitLabel(SectionBegin);
1903 // Emit the full data.
1904 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1907 // Emit type dies into a hashed accelerator table.
1908 void DwarfDebug::emitAccelTypes() {
1910 AccelTypes.FinalizeTable(Asm, "types");
1911 Asm->OutStreamer.SwitchSection(
1912 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1913 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1914 Asm->OutStreamer.EmitLabel(SectionBegin);
1916 // Emit the full data.
1917 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1920 // Public name handling.
1921 // The format for the various pubnames:
1923 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1924 // for the DIE that is named.
1926 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1927 // into the CU and the index value is computed according to the type of value
1928 // for the DIE that is named.
1930 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1931 // it's the offset within the debug_info/debug_types dwo section, however, the
1932 // reference in the pubname header doesn't change.
1934 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1935 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1937 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1939 // We could have a specification DIE that has our most of our knowledge,
1940 // look for that now.
1941 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1943 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1944 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1945 Linkage = dwarf::GIEL_EXTERNAL;
1946 } else if (Die->findAttribute(dwarf::DW_AT_external))
1947 Linkage = dwarf::GIEL_EXTERNAL;
1949 switch (Die->getTag()) {
1950 case dwarf::DW_TAG_class_type:
1951 case dwarf::DW_TAG_structure_type:
1952 case dwarf::DW_TAG_union_type:
1953 case dwarf::DW_TAG_enumeration_type:
1954 return dwarf::PubIndexEntryDescriptor(
1955 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1956 ? dwarf::GIEL_STATIC
1957 : dwarf::GIEL_EXTERNAL);
1958 case dwarf::DW_TAG_typedef:
1959 case dwarf::DW_TAG_base_type:
1960 case dwarf::DW_TAG_subrange_type:
1961 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1962 case dwarf::DW_TAG_namespace:
1963 return dwarf::GIEK_TYPE;
1964 case dwarf::DW_TAG_subprogram:
1965 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1966 case dwarf::DW_TAG_constant:
1967 case dwarf::DW_TAG_variable:
1968 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1969 case dwarf::DW_TAG_enumerator:
1970 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1971 dwarf::GIEL_STATIC);
1973 return dwarf::GIEK_NONE;
1977 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1979 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1980 const MCSection *PSec =
1981 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1982 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1984 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1987 void DwarfDebug::emitDebugPubSection(
1988 bool GnuStyle, const MCSection *PSec, StringRef Name,
1989 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1990 for (const auto &NU : CUMap) {
1991 DwarfCompileUnit *TheU = NU.second;
1993 const auto &Globals = (TheU->*Accessor)();
1995 if (Globals.empty())
1998 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2000 unsigned ID = TheU->getUniqueID();
2002 // Start the dwarf pubnames section.
2003 Asm->OutStreamer.SwitchSection(PSec);
2006 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2007 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2008 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2009 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2011 Asm->OutStreamer.EmitLabel(BeginLabel);
2013 Asm->OutStreamer.AddComment("DWARF Version");
2014 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2016 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2017 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2019 Asm->OutStreamer.AddComment("Compilation Unit Length");
2020 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2022 // Emit the pubnames for this compilation unit.
2023 for (const auto &GI : Globals) {
2024 const char *Name = GI.getKeyData();
2025 const DIE *Entity = GI.second;
2027 Asm->OutStreamer.AddComment("DIE offset");
2028 Asm->EmitInt32(Entity->getOffset());
2031 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2032 Asm->OutStreamer.AddComment(
2033 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2034 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2035 Asm->EmitInt8(Desc.toBits());
2038 Asm->OutStreamer.AddComment("External Name");
2039 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2042 Asm->OutStreamer.AddComment("End Mark");
2044 Asm->OutStreamer.EmitLabel(EndLabel);
2048 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2049 const MCSection *PSec =
2050 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2051 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2053 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2056 // Emit visible names into a debug str section.
2057 void DwarfDebug::emitDebugStr() {
2058 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2059 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2062 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2063 const DebugLocEntry &Entry) {
2064 DIVariable DV(Entry.getVariable());
2065 if (Entry.isInt()) {
2066 DIBasicType BTy(resolve(DV.getType()));
2067 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2068 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2069 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2070 Streamer.EmitSLEB128(Entry.getInt());
2072 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2073 Streamer.EmitULEB128(Entry.getInt());
2075 } else if (Entry.isLocation()) {
2076 MachineLocation Loc = Entry.getLoc();
2077 if (!DV.hasComplexAddress())
2079 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2081 // Complex address entry.
2082 unsigned N = DV.getNumAddrElements();
2084 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2085 if (Loc.getOffset()) {
2087 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2088 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2089 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2090 Streamer.EmitSLEB128(DV.getAddrElement(1));
2092 // If first address element is OpPlus then emit
2093 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2094 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2095 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2099 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2102 // Emit remaining complex address elements.
2103 for (; i < N; ++i) {
2104 uint64_t Element = DV.getAddrElement(i);
2105 if (Element == DIBuilder::OpPlus) {
2106 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2107 Streamer.EmitULEB128(DV.getAddrElement(++i));
2108 } else if (Element == DIBuilder::OpDeref) {
2110 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2112 llvm_unreachable("unknown Opcode found in complex address");
2116 // else ... ignore constant fp. There is not any good way to
2117 // to represent them here in dwarf.
2121 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2122 Asm->OutStreamer.AddComment("Loc expr size");
2123 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2124 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2125 Asm->EmitLabelDifference(end, begin, 2);
2126 Asm->OutStreamer.EmitLabel(begin);
2128 APByteStreamer Streamer(*Asm);
2129 emitDebugLocEntry(Streamer, Entry);
2131 Asm->OutStreamer.EmitLabel(end);
2134 // Emit locations into the debug loc section.
2135 void DwarfDebug::emitDebugLoc() {
2136 // Start the dwarf loc section.
2137 Asm->OutStreamer.SwitchSection(
2138 Asm->getObjFileLowering().getDwarfLocSection());
2139 unsigned char Size = Asm->getDataLayout().getPointerSize();
2140 for (const auto &DebugLoc : DotDebugLocEntries) {
2141 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2142 for (const auto &Entry : DebugLoc.List) {
2143 // Set up the range. This range is relative to the entry point of the
2144 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2145 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2146 const DwarfCompileUnit *CU = Entry.getCU();
2147 if (CU->getRanges().size() == 1) {
2148 // Grab the begin symbol from the first range as our base.
2149 const MCSymbol *Base = CU->getRanges()[0].getStart();
2150 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2151 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2153 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2154 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2157 emitDebugLocEntryLocation(Entry);
2159 Asm->OutStreamer.EmitIntValue(0, Size);
2160 Asm->OutStreamer.EmitIntValue(0, Size);
2164 void DwarfDebug::emitDebugLocDWO() {
2165 Asm->OutStreamer.SwitchSection(
2166 Asm->getObjFileLowering().getDwarfLocDWOSection());
2167 for (const auto &DebugLoc : DotDebugLocEntries) {
2168 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2169 for (const auto &Entry : DebugLoc.List) {
2170 // Just always use start_length for now - at least that's one address
2171 // rather than two. We could get fancier and try to, say, reuse an
2172 // address we know we've emitted elsewhere (the start of the function?
2173 // The start of the CU or CU subrange that encloses this range?)
2174 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2175 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2176 Asm->EmitULEB128(idx);
2177 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2179 emitDebugLocEntryLocation(Entry);
2181 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2186 const MCSymbol *Start, *End;
2189 // Emit a debug aranges section, containing a CU lookup for any
2190 // address we can tie back to a CU.
2191 void DwarfDebug::emitDebugARanges() {
2192 // Start the dwarf aranges section.
2193 Asm->OutStreamer.SwitchSection(
2194 Asm->getObjFileLowering().getDwarfARangesSection());
2196 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2200 // Build a list of sections used.
2201 std::vector<const MCSection *> Sections;
2202 for (const auto &it : SectionMap) {
2203 const MCSection *Section = it.first;
2204 Sections.push_back(Section);
2207 // Sort the sections into order.
2208 // This is only done to ensure consistent output order across different runs.
2209 std::sort(Sections.begin(), Sections.end(), SectionSort);
2211 // Build a set of address spans, sorted by CU.
2212 for (const MCSection *Section : Sections) {
2213 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2214 if (List.size() < 2)
2217 // Sort the symbols by offset within the section.
2218 std::sort(List.begin(), List.end(),
2219 [&](const SymbolCU &A, const SymbolCU &B) {
2220 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2221 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2223 // Symbols with no order assigned should be placed at the end.
2224 // (e.g. section end labels)
2232 // If we have no section (e.g. common), just write out
2233 // individual spans for each symbol.
2235 for (const SymbolCU &Cur : List) {
2237 Span.Start = Cur.Sym;
2240 Spans[Cur.CU].push_back(Span);
2243 // Build spans between each label.
2244 const MCSymbol *StartSym = List[0].Sym;
2245 for (size_t n = 1, e = List.size(); n < e; n++) {
2246 const SymbolCU &Prev = List[n - 1];
2247 const SymbolCU &Cur = List[n];
2249 // Try and build the longest span we can within the same CU.
2250 if (Cur.CU != Prev.CU) {
2252 Span.Start = StartSym;
2254 Spans[Prev.CU].push_back(Span);
2261 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2263 // Build a list of CUs used.
2264 std::vector<DwarfCompileUnit *> CUs;
2265 for (const auto &it : Spans) {
2266 DwarfCompileUnit *CU = it.first;
2270 // Sort the CU list (again, to ensure consistent output order).
2271 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2272 return A->getUniqueID() < B->getUniqueID();
2275 // Emit an arange table for each CU we used.
2276 for (DwarfCompileUnit *CU : CUs) {
2277 std::vector<ArangeSpan> &List = Spans[CU];
2279 // Emit size of content not including length itself.
2280 unsigned ContentSize =
2281 sizeof(int16_t) + // DWARF ARange version number
2282 sizeof(int32_t) + // Offset of CU in the .debug_info section
2283 sizeof(int8_t) + // Pointer Size (in bytes)
2284 sizeof(int8_t); // Segment Size (in bytes)
2286 unsigned TupleSize = PtrSize * 2;
2288 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2290 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2292 ContentSize += Padding;
2293 ContentSize += (List.size() + 1) * TupleSize;
2295 // For each compile unit, write the list of spans it covers.
2296 Asm->OutStreamer.AddComment("Length of ARange Set");
2297 Asm->EmitInt32(ContentSize);
2298 Asm->OutStreamer.AddComment("DWARF Arange version number");
2299 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2300 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2301 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2302 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2303 Asm->EmitInt8(PtrSize);
2304 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2307 Asm->OutStreamer.EmitFill(Padding, 0xff);
2309 for (const ArangeSpan &Span : List) {
2310 Asm->EmitLabelReference(Span.Start, PtrSize);
2312 // Calculate the size as being from the span start to it's end.
2314 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2316 // For symbols without an end marker (e.g. common), we
2317 // write a single arange entry containing just that one symbol.
2318 uint64_t Size = SymSize[Span.Start];
2322 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2326 Asm->OutStreamer.AddComment("ARange terminator");
2327 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2328 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2332 // Emit visible names into a debug ranges section.
2333 void DwarfDebug::emitDebugRanges() {
2334 // Start the dwarf ranges section.
2335 Asm->OutStreamer.SwitchSection(
2336 Asm->getObjFileLowering().getDwarfRangesSection());
2338 // Size for our labels.
2339 unsigned char Size = Asm->getDataLayout().getPointerSize();
2341 // Grab the specific ranges for the compile units in the module.
2342 for (const auto &I : CUMap) {
2343 DwarfCompileUnit *TheCU = I.second;
2345 // Emit a symbol so we can find the beginning of our ranges.
2346 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2348 // Iterate over the misc ranges for the compile units in the module.
2349 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2350 // Emit our symbol so we can find the beginning of the range.
2351 Asm->OutStreamer.EmitLabel(List.getSym());
2353 for (const RangeSpan &Range : List.getRanges()) {
2354 const MCSymbol *Begin = Range.getStart();
2355 const MCSymbol *End = Range.getEnd();
2356 assert(Begin && "Range without a begin symbol?");
2357 assert(End && "Range without an end symbol?");
2358 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2359 Asm->OutStreamer.EmitSymbolValue(End, Size);
2362 // And terminate the list with two 0 values.
2363 Asm->OutStreamer.EmitIntValue(0, Size);
2364 Asm->OutStreamer.EmitIntValue(0, Size);
2367 // Now emit a range for the CU itself.
2368 if (TheCU->getRanges().size() > 1) {
2369 Asm->OutStreamer.EmitLabel(
2370 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2371 for (const RangeSpan &Range : TheCU->getRanges()) {
2372 const MCSymbol *Begin = Range.getStart();
2373 const MCSymbol *End = Range.getEnd();
2374 assert(Begin && "Range without a begin symbol?");
2375 assert(End && "Range without an end symbol?");
2376 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2377 Asm->OutStreamer.EmitSymbolValue(End, Size);
2379 // And terminate the list with two 0 values.
2380 Asm->OutStreamer.EmitIntValue(0, Size);
2381 Asm->OutStreamer.EmitIntValue(0, Size);
2386 // DWARF5 Experimental Separate Dwarf emitters.
2388 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2389 std::unique_ptr<DwarfUnit> NewU) {
2390 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2391 U.getCUNode().getSplitDebugFilename());
2393 if (!CompilationDir.empty())
2394 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2396 addGnuPubAttributes(*NewU, Die);
2398 SkeletonHolder.addUnit(std::move(NewU));
2401 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2402 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2403 // DW_AT_addr_base, DW_AT_ranges_base.
2404 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2406 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2407 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2408 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2409 DwarfCompileUnit &NewCU = *OwnedUnit;
2410 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2411 DwarfInfoSectionSym);
2413 NewCU.initStmtList(DwarfLineSectionSym);
2415 initSkeletonUnit(CU, *Die, std::move(OwnedUnit));
2420 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2422 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2423 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2424 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2426 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2427 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2428 this, &SkeletonHolder);
2429 DwarfTypeUnit &NewTU = *OwnedUnit;
2430 NewTU.setTypeSignature(TU.getTypeSignature());
2431 NewTU.setType(nullptr);
2433 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2435 initSkeletonUnit(TU, *Die, std::move(OwnedUnit));
2439 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2440 // compile units that would normally be in debug_info.
2441 void DwarfDebug::emitDebugInfoDWO() {
2442 assert(useSplitDwarf() && "No split dwarf debug info?");
2443 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2444 // emit relocations into the dwo file.
2445 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2448 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2449 // abbreviations for the .debug_info.dwo section.
2450 void DwarfDebug::emitDebugAbbrevDWO() {
2451 assert(useSplitDwarf() && "No split dwarf?");
2452 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2455 void DwarfDebug::emitDebugLineDWO() {
2456 assert(useSplitDwarf() && "No split dwarf?");
2457 Asm->OutStreamer.SwitchSection(
2458 Asm->getObjFileLowering().getDwarfLineDWOSection());
2459 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2462 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2463 // string section and is identical in format to traditional .debug_str
2465 void DwarfDebug::emitDebugStrDWO() {
2466 assert(useSplitDwarf() && "No split dwarf?");
2467 const MCSection *OffSec =
2468 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2469 const MCSymbol *StrSym = DwarfStrSectionSym;
2470 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2474 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2475 if (!useSplitDwarf())
2478 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2479 return &SplitTypeUnitFileTable;
2482 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2483 StringRef Identifier, DIE &RefDie,
2484 DICompositeType CTy) {
2485 // Flag the type unit reference as a declaration so that if it contains
2486 // members (implicit special members, static data member definitions, member
2487 // declarations for definitions in this CU, etc) consumers don't get confused
2488 // and think this is a full definition.
2489 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2491 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2493 CU.addDIETypeSignature(RefDie, *TU);
2497 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2499 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2500 this, &InfoHolder, getDwoLineTable(CU));
2501 DwarfTypeUnit &NewTU = *OwnedUnit;
2503 InfoHolder.addUnit(std::move(OwnedUnit));
2505 NewTU.addUInt(*UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2509 Hash.update(Identifier);
2510 // ... take the least significant 8 bytes and return those. Our MD5
2511 // implementation always returns its results in little endian, swap bytes
2513 MD5::MD5Result Result;
2515 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2516 NewTU.setTypeSignature(Signature);
2517 if (useSplitDwarf())
2518 NewTU.setSkeleton(constructSkeletonTU(NewTU));
2520 CU.applyStmtList(*UnitDie);
2522 NewTU.setType(NewTU.createTypeDIE(CTy));
2526 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2527 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2529 CU.addDIETypeSignature(RefDie, NewTU);
2532 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2533 MCSymbol *Begin, MCSymbol *End) {
2534 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2535 if (DwarfVersion < 4)
2536 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2538 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2541 // Accelerator table mutators - add each name along with its companion
2542 // DIE to the proper table while ensuring that the name that we're going
2543 // to reference is in the string table. We do this since the names we
2544 // add may not only be identical to the names in the DIE.
2545 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2546 if (!useDwarfAccelTables())
2548 InfoHolder.getStringPoolEntry(Name);
2549 AccelNames.AddName(Name, &Die);
2552 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2553 if (!useDwarfAccelTables())
2555 InfoHolder.getStringPoolEntry(Name);
2556 AccelObjC.AddName(Name, &Die);
2559 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2560 if (!useDwarfAccelTables())
2562 InfoHolder.getStringPoolEntry(Name);
2563 AccelNamespace.AddName(Name, &Die);
2566 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2567 if (!useDwarfAccelTables())
2569 InfoHolder.getStringPoolEntry(Name);
2570 AccelTypes.AddName(Name, &Die, Flags);