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)
519 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope()));
520 if (ArgDV->isObjectPointer())
521 ObjectPointer = Children.back().get();
524 // If this is a variadic function, add an unspecified parameter.
525 DISubprogram SP(Scope->getScopeNode());
526 DIArray FnArgs = SP.getType().getTypeArray();
527 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
528 .isUnspecifiedParameter()) {
530 make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
534 // Collect lexical scope children first.
535 for (DbgVariable *DV : ScopeVariables.lookup(Scope)) {
537 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope()));
538 if (DV->isObjectPointer())
539 ObjectPointer = Children.back().get();
541 for (LexicalScope *LS : Scope->getChildren())
542 if (DIE *Nested = constructScopeDIE(TheCU, LS))
543 Children.push_back(std::unique_ptr<DIE>(Nested));
544 return ObjectPointer;
547 // Construct a DIE for this scope.
548 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
549 LexicalScope *Scope) {
550 if (!Scope || !Scope->getScopeNode())
553 DIScope DS(Scope->getScopeNode());
555 SmallVector<std::unique_ptr<DIE>, 8> Children;
556 DIE *ObjectPointer = nullptr;
557 bool ChildrenCreated = false;
559 // We try to create the scope DIE first, then the children DIEs. This will
560 // avoid creating un-used children then removing them later when we find out
561 // the scope DIE is null.
562 DIE *ScopeDIE = nullptr;
563 if (Scope->getInlinedAt())
564 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
565 else if (DS.isSubprogram()) {
566 ProcessedSPNodes.insert(DS);
567 if (Scope->isAbstractScope()) {
568 ScopeDIE = TheCU.getDIE(DS);
569 // Note down abstract DIE.
571 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
573 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
575 // Early exit when we know the scope DIE is going to be null.
576 if (isLexicalScopeDIENull(Scope))
579 // We create children here when we know the scope DIE is not going to be
580 // null and the children will be added to the scope DIE.
581 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
582 ChildrenCreated = true;
584 // There is no need to emit empty lexical block DIE.
585 std::pair<ImportedEntityMap::const_iterator,
586 ImportedEntityMap::const_iterator> Range =
588 ScopesWithImportedEntities.begin(),
589 ScopesWithImportedEntities.end(),
590 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
592 if (Children.empty() && Range.first == Range.second)
594 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
595 assert(ScopeDIE && "Scope DIE should not be null.");
596 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
598 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
602 assert(Children.empty() &&
603 "We create children only when the scope DIE is not null.");
606 if (!ChildrenCreated)
607 // We create children when the scope DIE is not null.
608 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
611 for (auto &I : Children)
612 ScopeDIE->addChild(std::move(I));
614 if (DS.isSubprogram() && ObjectPointer != nullptr)
615 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
620 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
621 if (!GenerateGnuPubSections)
624 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
627 // Create new DwarfCompileUnit for the given metadata node with tag
628 // DW_TAG_compile_unit.
629 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
630 StringRef FN = DIUnit.getFilename();
631 CompilationDir = DIUnit.getDirectory();
633 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
634 auto OwnedUnit = make_unique<DwarfCompileUnit>(
635 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
636 DwarfCompileUnit &NewCU = *OwnedUnit;
637 InfoHolder.addUnit(std::move(OwnedUnit));
639 // LTO with assembly output shares a single line table amongst multiple CUs.
640 // To avoid the compilation directory being ambiguous, let the line table
641 // explicitly describe the directory of all files, never relying on the
642 // compilation directory.
643 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
644 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
645 NewCU.getUniqueID(), CompilationDir);
647 NewCU.addString(*Die, dwarf::DW_AT_producer, DIUnit.getProducer());
648 NewCU.addUInt(*Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
649 DIUnit.getLanguage());
650 NewCU.addString(*Die, dwarf::DW_AT_name, FN);
652 if (!useSplitDwarf()) {
653 NewCU.initStmtList(DwarfLineSectionSym);
655 // If we're using split dwarf the compilation dir is going to be in the
656 // skeleton CU and so we don't need to duplicate it here.
657 if (!CompilationDir.empty())
658 NewCU.addString(*Die, dwarf::DW_AT_comp_dir, CompilationDir);
660 addGnuPubAttributes(NewCU, *Die);
663 if (DIUnit.isOptimized())
664 NewCU.addFlag(*Die, dwarf::DW_AT_APPLE_optimized);
666 StringRef Flags = DIUnit.getFlags();
668 NewCU.addString(*Die, dwarf::DW_AT_APPLE_flags, Flags);
670 if (unsigned RVer = DIUnit.getRunTimeVersion())
671 NewCU.addUInt(*Die, dwarf::DW_AT_APPLE_major_runtime_vers,
672 dwarf::DW_FORM_data1, RVer);
677 if (useSplitDwarf()) {
678 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
679 DwarfInfoDWOSectionSym);
680 NewCU.setSkeleton(constructSkeletonCU(NewCU));
682 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
683 DwarfInfoSectionSym);
685 CUMap.insert(std::make_pair(DIUnit, &NewCU));
686 CUDieMap.insert(std::make_pair(Die, &NewCU));
690 // Construct subprogram DIE.
691 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
693 // FIXME: We should only call this routine once, however, during LTO if a
694 // program is defined in multiple CUs we could end up calling it out of
695 // beginModule as we walk the CUs.
697 DwarfCompileUnit *&CURef = SPMap[N];
703 if (!SP.isDefinition())
704 // This is a method declaration which will be handled while constructing
708 DIE &SubprogramDie = *TheCU.getOrCreateSubprogramDIE(SP);
710 // Expose as a global name.
711 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
714 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
716 DIImportedEntity Module(N);
717 assert(Module.Verify());
718 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
719 constructImportedEntityDIE(TheCU, Module, D);
722 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
723 const MDNode *N, DIE *Context) {
724 DIImportedEntity Module(N);
725 assert(Module.Verify());
726 return constructImportedEntityDIE(TheCU, Module, Context);
729 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
730 const DIImportedEntity &Module,
732 assert(Module.Verify() &&
733 "Use one of the MDNode * overloads to handle invalid metadata");
734 assert(Context && "Should always have a context for an imported_module");
735 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), *Context, Module);
737 DIDescriptor Entity = resolve(Module.getEntity());
738 if (Entity.isNameSpace())
739 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
740 else if (Entity.isSubprogram())
741 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
742 else if (Entity.isType())
743 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
745 EntityDie = TheCU.getDIE(Entity);
746 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
747 Module.getContext().getFilename(),
748 Module.getContext().getDirectory());
749 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
750 StringRef Name = Module.getName();
752 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
755 // Emit all Dwarf sections that should come prior to the content. Create
756 // global DIEs and emit initial debug info sections. This is invoked by
757 // the target AsmPrinter.
758 void DwarfDebug::beginModule() {
759 if (DisableDebugInfoPrinting)
762 const Module *M = MMI->getModule();
764 // If module has named metadata anchors then use them, otherwise scan the
765 // module using debug info finder to collect debug info.
766 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
769 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
771 // Emit initial sections so we can reference labels later.
774 SingleCU = CU_Nodes->getNumOperands() == 1;
776 for (MDNode *N : CU_Nodes->operands()) {
777 DICompileUnit CUNode(N);
778 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
779 DIArray ImportedEntities = CUNode.getImportedEntities();
780 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
781 ScopesWithImportedEntities.push_back(std::make_pair(
782 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
783 ImportedEntities.getElement(i)));
784 std::sort(ScopesWithImportedEntities.begin(),
785 ScopesWithImportedEntities.end(), less_first());
786 DIArray GVs = CUNode.getGlobalVariables();
787 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
788 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
789 DIArray SPs = CUNode.getSubprograms();
790 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
791 constructSubprogramDIE(CU, SPs.getElement(i));
792 DIArray EnumTypes = CUNode.getEnumTypes();
793 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
794 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
795 DIArray RetainedTypes = CUNode.getRetainedTypes();
796 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
797 DIType Ty(RetainedTypes.getElement(i));
798 // The retained types array by design contains pointers to
799 // MDNodes rather than DIRefs. Unique them here.
800 DIType UniqueTy(resolve(Ty.getRef()));
801 CU.getOrCreateTypeDIE(UniqueTy);
803 // Emit imported_modules last so that the relevant context is already
805 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
806 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
809 // Tell MMI that we have debug info.
810 MMI->setDebugInfoAvailability(true);
812 // Prime section data.
813 SectionMap[Asm->getObjFileLowering().getTextSection()];
816 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
817 void DwarfDebug::computeInlinedDIEs() {
818 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
819 for (DIE *ISP : InlinedSubprogramDIEs)
820 FirstCU->addUInt(*ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
822 for (const auto &AI : AbstractSPDies) {
823 DIE &ISP = *AI.second;
824 if (InlinedSubprogramDIEs.count(&ISP))
826 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
830 // Collect info for variables that were optimized out.
831 void DwarfDebug::collectDeadVariables() {
832 const Module *M = MMI->getModule();
834 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
835 for (MDNode *N : CU_Nodes->operands()) {
836 DICompileUnit TheCU(N);
837 DIArray Subprograms = TheCU.getSubprograms();
838 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
839 DISubprogram SP(Subprograms.getElement(i));
840 if (ProcessedSPNodes.count(SP) != 0)
842 if (!SP.isSubprogram())
844 if (!SP.isDefinition())
846 DIArray Variables = SP.getVariables();
847 if (Variables.getNumElements() == 0)
850 // Construct subprogram DIE and add variables DIEs.
851 DwarfCompileUnit *SPCU =
852 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
853 assert(SPCU && "Unable to find Compile Unit!");
854 // FIXME: See the comment in constructSubprogramDIE about duplicate
856 constructSubprogramDIE(*SPCU, SP);
857 DIE *SPDIE = SPCU->getDIE(SP);
858 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
859 DIVariable DV(Variables.getElement(vi));
860 if (!DV.isVariable())
862 DbgVariable NewVar(DV, nullptr, this);
863 SPDIE->addChild(SPCU->constructVariableDIE(NewVar, false));
870 void DwarfDebug::finalizeModuleInfo() {
871 // Collect info for variables that were optimized out.
872 collectDeadVariables();
874 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
875 computeInlinedDIEs();
877 // Handle anything that needs to be done on a per-unit basis after
878 // all other generation.
879 for (const auto &TheU : getUnits()) {
880 // Emit DW_AT_containing_type attribute to connect types with their
881 // vtable holding type.
882 TheU->constructContainingTypeDIEs();
884 // Add CU specific attributes if we need to add any.
885 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
886 // If we're splitting the dwarf out now that we've got the entire
887 // CU then add the dwo id to it.
888 DwarfCompileUnit *SkCU =
889 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
890 if (useSplitDwarf()) {
891 // Emit a unique identifier for this CU.
892 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
893 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
894 dwarf::DW_FORM_data8, ID);
895 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
896 dwarf::DW_FORM_data8, ID);
898 // We don't keep track of which addresses are used in which CU so this
899 // is a bit pessimistic under LTO.
900 if (!AddrPool.isEmpty())
901 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
902 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
903 DwarfAddrSectionSym);
904 if (!TheU->getRangeLists().empty())
905 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
906 dwarf::DW_AT_GNU_ranges_base,
907 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
910 // If we have code split among multiple sections or non-contiguous
911 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
912 // remain in the .o file, otherwise add a DW_AT_low_pc.
913 // FIXME: We should use ranges allow reordering of code ala
914 // .subsections_via_symbols in mach-o. This would mean turning on
915 // ranges for all subprogram DIEs for mach-o.
916 DwarfCompileUnit &U =
917 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
918 unsigned NumRanges = TheU->getRanges().size();
921 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
922 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
923 DwarfDebugRangeSectionSym);
925 // A DW_AT_low_pc attribute may also be specified in combination with
926 // DW_AT_ranges to specify the default base address for use in
927 // location lists (see Section 2.6.2) and range lists (see Section
929 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
932 RangeSpan &Range = TheU->getRanges().back();
933 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
935 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
942 // Compute DIE offsets and sizes.
943 InfoHolder.computeSizeAndOffsets();
945 SkeletonHolder.computeSizeAndOffsets();
948 void DwarfDebug::endSections() {
949 // Filter labels by section.
950 for (const SymbolCU &SCU : ArangeLabels) {
951 if (SCU.Sym->isInSection()) {
952 // Make a note of this symbol and it's section.
953 const MCSection *Section = &SCU.Sym->getSection();
954 if (!Section->getKind().isMetadata())
955 SectionMap[Section].push_back(SCU);
957 // Some symbols (e.g. common/bss on mach-o) can have no section but still
958 // appear in the output. This sucks as we rely on sections to build
959 // arange spans. We can do it without, but it's icky.
960 SectionMap[nullptr].push_back(SCU);
964 // Build a list of sections used.
965 std::vector<const MCSection *> Sections;
966 for (const auto &it : SectionMap) {
967 const MCSection *Section = it.first;
968 Sections.push_back(Section);
971 // Sort the sections into order.
972 // This is only done to ensure consistent output order across different runs.
973 std::sort(Sections.begin(), Sections.end(), SectionSort);
975 // Add terminating symbols for each section.
976 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
977 const MCSection *Section = Sections[ID];
978 MCSymbol *Sym = nullptr;
981 // We can't call MCSection::getLabelEndName, as it's only safe to do so
982 // if we know the section name up-front. For user-created sections, the
983 // resulting label may not be valid to use as a label. (section names can
984 // use a greater set of characters on some systems)
985 Sym = Asm->GetTempSymbol("debug_end", ID);
986 Asm->OutStreamer.SwitchSection(Section);
987 Asm->OutStreamer.EmitLabel(Sym);
990 // Insert a final terminator.
991 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
995 // Emit all Dwarf sections that should come after the content.
996 void DwarfDebug::endModule() {
1003 // End any existing sections.
1004 // TODO: Does this need to happen?
1007 // Finalize the debug info for the module.
1008 finalizeModuleInfo();
1012 // Emit all the DIEs into a debug info section.
1015 // Corresponding abbreviations into a abbrev section.
1016 emitAbbreviations();
1018 // Emit info into a debug aranges section.
1019 if (GenerateARangeSection)
1022 // Emit info into a debug ranges section.
1025 if (useSplitDwarf()) {
1028 emitDebugAbbrevDWO();
1030 // Emit DWO addresses.
1031 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1034 // Emit info into a debug loc section.
1037 // Emit info into the dwarf accelerator table sections.
1038 if (useDwarfAccelTables()) {
1041 emitAccelNamespaces();
1045 // Emit the pubnames and pubtypes sections if requested.
1046 if (HasDwarfPubSections) {
1047 emitDebugPubNames(GenerateGnuPubSections);
1048 emitDebugPubTypes(GenerateGnuPubSections);
1054 // Reset these for the next Module if we have one.
1058 // Find abstract variable, if any, associated with Var.
1059 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1060 DebugLoc ScopeLoc) {
1061 LLVMContext &Ctx = DV->getContext();
1062 // More then one inlined variable corresponds to one abstract variable.
1063 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1064 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1066 return AbsDbgVariable;
1068 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1072 AbsDbgVariable = new DbgVariable(Var, nullptr, this);
1073 addScopeVariable(Scope, AbsDbgVariable);
1074 AbstractVariables[Var] = AbsDbgVariable;
1075 return AbsDbgVariable;
1078 // If Var is a current function argument then add it to CurrentFnArguments list.
1079 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1080 if (!LScopes.isCurrentFunctionScope(Scope))
1082 DIVariable DV = Var->getVariable();
1083 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1085 unsigned ArgNo = DV.getArgNumber();
1089 size_t Size = CurrentFnArguments.size();
1091 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1092 // llvm::Function argument size is not good indicator of how many
1093 // arguments does the function have at source level.
1095 CurrentFnArguments.resize(ArgNo * 2);
1096 CurrentFnArguments[ArgNo - 1] = Var;
1100 // Collect variable information from side table maintained by MMI.
1101 void DwarfDebug::collectVariableInfoFromMMITable(
1102 SmallPtrSet<const MDNode *, 16> &Processed) {
1103 for (const auto &VI : MMI->getVariableDbgInfo()) {
1106 Processed.insert(VI.Var);
1107 DIVariable DV(VI.Var);
1108 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1110 // If variable scope is not found then skip this variable.
1114 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1115 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1116 RegVar->setFrameIndex(VI.Slot);
1117 if (!addCurrentFnArgument(RegVar, Scope))
1118 addScopeVariable(Scope, RegVar);
1120 AbsDbgVariable->setFrameIndex(VI.Slot);
1124 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1126 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1127 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1128 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1129 MI->getOperand(0).getReg() &&
1130 (MI->getOperand(1).isImm() ||
1131 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1134 // Get .debug_loc entry for the instruction range starting at MI.
1135 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1136 const MCSymbol *FLabel,
1137 const MCSymbol *SLabel,
1138 const MachineInstr *MI,
1139 DwarfCompileUnit *Unit) {
1140 const MDNode *Var = MI->getDebugVariable();
1142 assert(MI->getNumOperands() == 3);
1143 if (MI->getOperand(0).isReg()) {
1144 MachineLocation MLoc;
1145 // If the second operand is an immediate, this is a
1146 // register-indirect address.
1147 if (!MI->getOperand(1).isImm())
1148 MLoc.set(MI->getOperand(0).getReg());
1150 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1151 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1153 if (MI->getOperand(0).isImm())
1154 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1155 if (MI->getOperand(0).isFPImm())
1156 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1158 if (MI->getOperand(0).isCImm())
1159 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1162 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1165 // Find variables for each lexical scope.
1167 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1169 // Grab the variable info that was squirreled away in the MMI side-table.
1170 collectVariableInfoFromMMITable(Processed);
1172 for (const MDNode *Var : UserVariables) {
1173 if (Processed.count(Var))
1176 // History contains relevant DBG_VALUE instructions for Var and instructions
1178 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1179 if (History.empty())
1181 const MachineInstr *MInsn = History.front();
1184 LexicalScope *Scope = nullptr;
1185 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1186 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1187 Scope = LScopes.getCurrentFunctionScope();
1188 else if (MDNode *IA = DV.getInlinedAt())
1189 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1191 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1192 // If variable scope is not found then skip this variable.
1196 Processed.insert(DV);
1197 assert(MInsn->isDebugValue() && "History must begin with debug value");
1198 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1199 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1200 if (!addCurrentFnArgument(RegVar, Scope))
1201 addScopeVariable(Scope, RegVar);
1203 AbsVar->setMInsn(MInsn);
1205 // Simplify ranges that are fully coalesced.
1206 if (History.size() <= 1 ||
1207 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1208 RegVar->setMInsn(MInsn);
1212 // Handle multiple DBG_VALUE instructions describing one variable.
1213 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1215 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1216 DebugLocList &LocList = DotDebugLocEntries.back();
1218 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1219 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1220 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1221 HI = History.begin(),
1224 const MachineInstr *Begin = *HI;
1225 assert(Begin->isDebugValue() && "Invalid History entry");
1227 // Check if DBG_VALUE is truncating a range.
1228 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1229 !Begin->getOperand(0).getReg())
1232 // Compute the range for a register location.
1233 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1234 const MCSymbol *SLabel = nullptr;
1237 // If Begin is the last instruction in History then its value is valid
1238 // until the end of the function.
1239 SLabel = FunctionEndSym;
1241 const MachineInstr *End = HI[1];
1242 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1243 << "\t" << *Begin << "\t" << *End << "\n");
1244 if (End->isDebugValue())
1245 SLabel = getLabelBeforeInsn(End);
1247 // End is a normal instruction clobbering the range.
1248 SLabel = getLabelAfterInsn(End);
1249 assert(SLabel && "Forgot label after clobber instruction");
1254 // The value is valid until the next DBG_VALUE or clobber.
1255 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1256 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1257 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1258 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1259 DebugLoc.push_back(std::move(Loc));
1263 // Collect info for variables that were optimized out.
1264 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1265 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1266 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1267 DIVariable DV(Variables.getElement(i));
1268 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1270 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1271 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1275 // Return Label preceding the instruction.
1276 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1277 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1278 assert(Label && "Didn't insert label before instruction");
1282 // Return Label immediately following the instruction.
1283 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1284 return LabelsAfterInsn.lookup(MI);
1287 // Process beginning of an instruction.
1288 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1291 // Check if source location changes, but ignore DBG_VALUE locations.
1292 if (!MI->isDebugValue()) {
1293 DebugLoc DL = MI->getDebugLoc();
1294 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1297 if (DL == PrologEndLoc) {
1298 Flags |= DWARF2_FLAG_PROLOGUE_END;
1299 PrologEndLoc = DebugLoc();
1301 if (PrologEndLoc.isUnknown())
1302 Flags |= DWARF2_FLAG_IS_STMT;
1304 if (!DL.isUnknown()) {
1305 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1306 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1308 recordSourceLine(0, 0, nullptr, 0);
1312 // Insert labels where requested.
1313 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1314 LabelsBeforeInsn.find(MI);
1317 if (I == LabelsBeforeInsn.end())
1320 // Label already assigned.
1325 PrevLabel = MMI->getContext().CreateTempSymbol();
1326 Asm->OutStreamer.EmitLabel(PrevLabel);
1328 I->second = PrevLabel;
1331 // Process end of an instruction.
1332 void DwarfDebug::endInstruction() {
1334 // Don't create a new label after DBG_VALUE instructions.
1335 // They don't generate code.
1336 if (!CurMI->isDebugValue())
1337 PrevLabel = nullptr;
1339 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1340 LabelsAfterInsn.find(CurMI);
1344 if (I == LabelsAfterInsn.end())
1347 // Label already assigned.
1351 // We need a label after this instruction.
1353 PrevLabel = MMI->getContext().CreateTempSymbol();
1354 Asm->OutStreamer.EmitLabel(PrevLabel);
1356 I->second = PrevLabel;
1359 // Each LexicalScope has first instruction and last instruction to mark
1360 // beginning and end of a scope respectively. Create an inverse map that list
1361 // scopes starts (and ends) with an instruction. One instruction may start (or
1362 // end) multiple scopes. Ignore scopes that are not reachable.
1363 void DwarfDebug::identifyScopeMarkers() {
1364 SmallVector<LexicalScope *, 4> WorkList;
1365 WorkList.push_back(LScopes.getCurrentFunctionScope());
1366 while (!WorkList.empty()) {
1367 LexicalScope *S = WorkList.pop_back_val();
1369 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1370 if (!Children.empty())
1371 WorkList.append(Children.begin(), Children.end());
1373 if (S->isAbstractScope())
1376 for (const InsnRange &R : S->getRanges()) {
1377 assert(R.first && "InsnRange does not have first instruction!");
1378 assert(R.second && "InsnRange does not have second instruction!");
1379 requestLabelBeforeInsn(R.first);
1380 requestLabelAfterInsn(R.second);
1385 // Gather pre-function debug information. Assumes being called immediately
1386 // after the function entry point has been emitted.
1387 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1390 // If there's no debug info for the function we're not going to do anything.
1391 if (!MMI->hasDebugInfo())
1394 // Grab the lexical scopes for the function, if we don't have any of those
1395 // then we're not going to be able to do anything.
1396 LScopes.initialize(*MF);
1397 if (LScopes.empty())
1400 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1402 // Make sure that each lexical scope will have a begin/end label.
1403 identifyScopeMarkers();
1405 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1406 // belongs to so that we add to the correct per-cu line table in the
1408 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1409 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1410 assert(TheCU && "Unable to find compile unit!");
1411 if (Asm->OutStreamer.hasRawTextSupport())
1412 // Use a single line table if we are generating assembly.
1413 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1415 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1417 // Emit a label for the function so that we have a beginning address.
1418 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1419 // Assumes in correct section after the entry point.
1420 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1422 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1423 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1424 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1426 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1428 bool AtBlockEntry = true;
1429 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1431 const MachineInstr *MI = II;
1433 if (MI->isDebugValue()) {
1434 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1436 // Keep track of user variables.
1437 const MDNode *Var = MI->getDebugVariable();
1439 // Variable is in a register, we need to check for clobbers.
1440 if (isDbgValueInDefinedReg(MI))
1441 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1443 // Check the history of this variable.
1444 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1445 if (History.empty()) {
1446 UserVariables.push_back(Var);
1447 // The first mention of a function argument gets the FunctionBeginSym
1448 // label, so arguments are visible when breaking at function entry.
1450 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1451 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1452 LabelsBeforeInsn[MI] = FunctionBeginSym;
1454 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1455 const MachineInstr *Prev = History.back();
1456 if (Prev->isDebugValue()) {
1457 // Coalesce identical entries at the end of History.
1458 if (History.size() >= 2 &&
1459 Prev->isIdenticalTo(History[History.size() - 2])) {
1460 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1461 << "\t" << *Prev << "\t"
1462 << *History[History.size() - 2] << "\n");
1466 // Terminate old register assignments that don't reach MI;
1467 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1468 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1469 isDbgValueInDefinedReg(Prev)) {
1470 // Previous register assignment needs to terminate at the end of
1472 MachineBasicBlock::const_iterator LastMI =
1473 PrevMBB->getLastNonDebugInstr();
1474 if (LastMI == PrevMBB->end()) {
1475 // Drop DBG_VALUE for empty range.
1476 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1477 << "\t" << *Prev << "\n");
1479 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1480 // Terminate after LastMI.
1481 History.push_back(LastMI);
1485 History.push_back(MI);
1487 // Not a DBG_VALUE instruction.
1488 if (!MI->isPosition())
1489 AtBlockEntry = false;
1491 // First known non-DBG_VALUE and non-frame setup location marks
1492 // the beginning of the function body.
1493 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1494 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1495 PrologEndLoc = MI->getDebugLoc();
1497 // Check if the instruction clobbers any registers with debug vars.
1498 for (const MachineOperand &MO : MI->operands()) {
1499 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1501 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1504 const MDNode *Var = LiveUserVar[Reg];
1507 // Reg is now clobbered.
1508 LiveUserVar[Reg] = nullptr;
1510 // Was MD last defined by a DBG_VALUE referring to Reg?
1511 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1512 if (HistI == DbgValues.end())
1514 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1515 if (History.empty())
1517 const MachineInstr *Prev = History.back();
1518 // Sanity-check: Register assignments are terminated at the end of
1520 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1522 // Is the variable still in Reg?
1523 if (!isDbgValueInDefinedReg(Prev) ||
1524 Prev->getOperand(0).getReg() != Reg)
1526 // Var is clobbered. Make sure the next instruction gets a label.
1527 History.push_back(MI);
1534 for (auto &I : DbgValues) {
1535 SmallVectorImpl<const MachineInstr *> &History = I.second;
1536 if (History.empty())
1539 // Make sure the final register assignments are terminated.
1540 const MachineInstr *Prev = History.back();
1541 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1542 const MachineBasicBlock *PrevMBB = Prev->getParent();
1543 MachineBasicBlock::const_iterator LastMI =
1544 PrevMBB->getLastNonDebugInstr();
1545 if (LastMI == PrevMBB->end())
1546 // Drop DBG_VALUE for empty range.
1548 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1549 // Terminate after LastMI.
1550 History.push_back(LastMI);
1553 // Request labels for the full history.
1554 for (const MachineInstr *MI : History) {
1555 if (MI->isDebugValue())
1556 requestLabelBeforeInsn(MI);
1558 requestLabelAfterInsn(MI);
1562 PrevInstLoc = DebugLoc();
1563 PrevLabel = FunctionBeginSym;
1565 // Record beginning of function.
1566 if (!PrologEndLoc.isUnknown()) {
1567 DebugLoc FnStartDL =
1568 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1570 FnStartDL.getLine(), FnStartDL.getCol(),
1571 FnStartDL.getScope(MF->getFunction()->getContext()),
1572 // We'd like to list the prologue as "not statements" but GDB behaves
1573 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1574 DWARF2_FLAG_IS_STMT);
1578 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1579 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1580 DIVariable DV = Var->getVariable();
1581 // Variables with positive arg numbers are parameters.
1582 if (unsigned ArgNum = DV.getArgNumber()) {
1583 // Keep all parameters in order at the start of the variable list to ensure
1584 // function types are correct (no out-of-order parameters)
1586 // This could be improved by only doing it for optimized builds (unoptimized
1587 // builds have the right order to begin with), searching from the back (this
1588 // would catch the unoptimized case quickly), or doing a binary search
1589 // rather than linear search.
1590 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1591 while (I != Vars.end()) {
1592 unsigned CurNum = (*I)->getVariable().getArgNumber();
1593 // A local (non-parameter) variable has been found, insert immediately
1597 // A later indexed parameter has been found, insert immediately before it.
1598 if (CurNum > ArgNum)
1602 Vars.insert(I, Var);
1606 Vars.push_back(Var);
1609 // Gather and emit post-function debug information.
1610 void DwarfDebug::endFunction(const MachineFunction *MF) {
1611 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1612 // though the beginFunction may not be called at all.
1613 // We should handle both cases.
1617 assert(CurFn == MF);
1620 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1621 // If we don't have a lexical scope for this function then there will
1622 // be a hole in the range information. Keep note of this by setting the
1623 // previously used section to nullptr.
1624 PrevSection = nullptr;
1630 // Define end label for subprogram.
1631 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1632 // Assumes in correct section after the entry point.
1633 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1635 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1636 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1638 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1639 collectVariableInfo(ProcessedVars);
1641 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1642 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1644 // Construct abstract scopes.
1645 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1646 DISubprogram SP(AScope->getScopeNode());
1647 if (SP.isSubprogram()) {
1648 // Collect info for variables that were optimized out.
1649 DIArray Variables = SP.getVariables();
1650 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1651 DIVariable DV(Variables.getElement(i));
1652 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1654 // Check that DbgVariable for DV wasn't created earlier, when
1655 // findAbstractVariable() was called for inlined instance of DV.
1656 LLVMContext &Ctx = DV->getContext();
1657 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1658 if (AbstractVariables.lookup(CleanDV))
1660 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1661 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1664 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1665 constructScopeDIE(TheCU, AScope);
1668 DIE &CurFnDIE = *constructScopeDIE(TheCU, FnScope);
1669 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1670 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1672 // Add the range of this function to the list of ranges for the CU.
1673 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1674 TheCU.addRange(std::move(Span));
1675 PrevSection = Asm->getCurrentSection();
1679 for (auto &I : ScopeVariables)
1680 DeleteContainerPointers(I.second);
1681 ScopeVariables.clear();
1682 DeleteContainerPointers(CurrentFnArguments);
1683 UserVariables.clear();
1685 AbstractVariables.clear();
1686 LabelsBeforeInsn.clear();
1687 LabelsAfterInsn.clear();
1688 PrevLabel = nullptr;
1692 // Register a source line with debug info. Returns the unique label that was
1693 // emitted and which provides correspondence to the source line list.
1694 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1699 unsigned Discriminator = 0;
1701 DIDescriptor Scope(S);
1703 if (Scope.isCompileUnit()) {
1704 DICompileUnit CU(S);
1705 Fn = CU.getFilename();
1706 Dir = CU.getDirectory();
1707 } else if (Scope.isFile()) {
1709 Fn = F.getFilename();
1710 Dir = F.getDirectory();
1711 } else if (Scope.isSubprogram()) {
1713 Fn = SP.getFilename();
1714 Dir = SP.getDirectory();
1715 } else if (Scope.isLexicalBlockFile()) {
1716 DILexicalBlockFile DBF(S);
1717 Fn = DBF.getFilename();
1718 Dir = DBF.getDirectory();
1719 } else if (Scope.isLexicalBlock()) {
1720 DILexicalBlock DB(S);
1721 Fn = DB.getFilename();
1722 Dir = DB.getDirectory();
1723 Discriminator = DB.getDiscriminator();
1725 llvm_unreachable("Unexpected scope info");
1727 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1728 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1729 .getOrCreateSourceID(Fn, Dir);
1731 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1735 //===----------------------------------------------------------------------===//
1737 //===----------------------------------------------------------------------===//
1739 // Emit initial Dwarf sections with a label at the start of each one.
1740 void DwarfDebug::emitSectionLabels() {
1741 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1743 // Dwarf sections base addresses.
1744 DwarfInfoSectionSym =
1745 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1746 if (useSplitDwarf())
1747 DwarfInfoDWOSectionSym =
1748 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1749 DwarfAbbrevSectionSym =
1750 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1751 if (useSplitDwarf())
1752 DwarfAbbrevDWOSectionSym = emitSectionSym(
1753 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1754 if (GenerateARangeSection)
1755 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1757 DwarfLineSectionSym =
1758 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1759 if (GenerateGnuPubSections) {
1760 DwarfGnuPubNamesSectionSym =
1761 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1762 DwarfGnuPubTypesSectionSym =
1763 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1764 } else if (HasDwarfPubSections) {
1765 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1766 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1769 DwarfStrSectionSym =
1770 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1771 if (useSplitDwarf()) {
1772 DwarfStrDWOSectionSym =
1773 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1774 DwarfAddrSectionSym =
1775 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1776 DwarfDebugLocSectionSym =
1777 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1779 DwarfDebugLocSectionSym =
1780 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1781 DwarfDebugRangeSectionSym =
1782 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1785 // Recursively emits a debug information entry.
1786 void DwarfDebug::emitDIE(DIE &Die) {
1787 // Get the abbreviation for this DIE.
1788 const DIEAbbrev &Abbrev = Die.getAbbrev();
1790 // Emit the code (index) for the abbreviation.
1791 if (Asm->isVerbose())
1792 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1793 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1794 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1795 dwarf::TagString(Abbrev.getTag()));
1796 Asm->EmitULEB128(Abbrev.getNumber());
1798 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1799 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1801 // Emit the DIE attribute values.
1802 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1803 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1804 dwarf::Form Form = AbbrevData[i].getForm();
1805 assert(Form && "Too many attributes for DIE (check abbreviation)");
1807 if (Asm->isVerbose()) {
1808 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1809 if (Attr == dwarf::DW_AT_accessibility)
1810 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1811 cast<DIEInteger>(Values[i])->getValue()));
1814 // Emit an attribute using the defined form.
1815 Values[i]->EmitValue(Asm, Form);
1818 // Emit the DIE children if any.
1819 if (Abbrev.hasChildren()) {
1820 for (auto &Child : Die.getChildren())
1823 Asm->OutStreamer.AddComment("End Of Children Mark");
1828 // Emit the debug info section.
1829 void DwarfDebug::emitDebugInfo() {
1830 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1832 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1835 // Emit the abbreviation section.
1836 void DwarfDebug::emitAbbreviations() {
1837 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1839 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1842 // Emit the last address of the section and the end of the line matrix.
1843 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1844 // Define last address of section.
1845 Asm->OutStreamer.AddComment("Extended Op");
1848 Asm->OutStreamer.AddComment("Op size");
1849 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1850 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1851 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1853 Asm->OutStreamer.AddComment("Section end label");
1855 Asm->OutStreamer.EmitSymbolValue(
1856 Asm->GetTempSymbol("section_end", SectionEnd),
1857 Asm->getDataLayout().getPointerSize());
1859 // Mark end of matrix.
1860 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1866 // Emit visible names into a hashed accelerator table section.
1867 void DwarfDebug::emitAccelNames() {
1868 AccelNames.FinalizeTable(Asm, "Names");
1869 Asm->OutStreamer.SwitchSection(
1870 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1871 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1872 Asm->OutStreamer.EmitLabel(SectionBegin);
1874 // Emit the full data.
1875 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1878 // Emit objective C classes and categories into a hashed accelerator table
1880 void DwarfDebug::emitAccelObjC() {
1881 AccelObjC.FinalizeTable(Asm, "ObjC");
1882 Asm->OutStreamer.SwitchSection(
1883 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1884 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1885 Asm->OutStreamer.EmitLabel(SectionBegin);
1887 // Emit the full data.
1888 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1891 // Emit namespace dies into a hashed accelerator table.
1892 void DwarfDebug::emitAccelNamespaces() {
1893 AccelNamespace.FinalizeTable(Asm, "namespac");
1894 Asm->OutStreamer.SwitchSection(
1895 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1896 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1897 Asm->OutStreamer.EmitLabel(SectionBegin);
1899 // Emit the full data.
1900 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1903 // Emit type dies into a hashed accelerator table.
1904 void DwarfDebug::emitAccelTypes() {
1906 AccelTypes.FinalizeTable(Asm, "types");
1907 Asm->OutStreamer.SwitchSection(
1908 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1909 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1910 Asm->OutStreamer.EmitLabel(SectionBegin);
1912 // Emit the full data.
1913 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1916 // Public name handling.
1917 // The format for the various pubnames:
1919 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1920 // for the DIE that is named.
1922 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1923 // into the CU and the index value is computed according to the type of value
1924 // for the DIE that is named.
1926 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1927 // it's the offset within the debug_info/debug_types dwo section, however, the
1928 // reference in the pubname header doesn't change.
1930 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1931 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1933 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1935 // We could have a specification DIE that has our most of our knowledge,
1936 // look for that now.
1937 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1939 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1940 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1941 Linkage = dwarf::GIEL_EXTERNAL;
1942 } else if (Die->findAttribute(dwarf::DW_AT_external))
1943 Linkage = dwarf::GIEL_EXTERNAL;
1945 switch (Die->getTag()) {
1946 case dwarf::DW_TAG_class_type:
1947 case dwarf::DW_TAG_structure_type:
1948 case dwarf::DW_TAG_union_type:
1949 case dwarf::DW_TAG_enumeration_type:
1950 return dwarf::PubIndexEntryDescriptor(
1951 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1952 ? dwarf::GIEL_STATIC
1953 : dwarf::GIEL_EXTERNAL);
1954 case dwarf::DW_TAG_typedef:
1955 case dwarf::DW_TAG_base_type:
1956 case dwarf::DW_TAG_subrange_type:
1957 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1958 case dwarf::DW_TAG_namespace:
1959 return dwarf::GIEK_TYPE;
1960 case dwarf::DW_TAG_subprogram:
1961 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1962 case dwarf::DW_TAG_constant:
1963 case dwarf::DW_TAG_variable:
1964 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1965 case dwarf::DW_TAG_enumerator:
1966 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1967 dwarf::GIEL_STATIC);
1969 return dwarf::GIEK_NONE;
1973 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1975 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1976 const MCSection *PSec =
1977 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1978 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1980 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1983 void DwarfDebug::emitDebugPubSection(
1984 bool GnuStyle, const MCSection *PSec, StringRef Name,
1985 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1986 for (const auto &NU : CUMap) {
1987 DwarfCompileUnit *TheU = NU.second;
1989 const auto &Globals = (TheU->*Accessor)();
1991 if (Globals.empty())
1994 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1996 unsigned ID = TheU->getUniqueID();
1998 // Start the dwarf pubnames section.
1999 Asm->OutStreamer.SwitchSection(PSec);
2002 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2003 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2004 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2005 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2007 Asm->OutStreamer.EmitLabel(BeginLabel);
2009 Asm->OutStreamer.AddComment("DWARF Version");
2010 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2012 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2013 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2015 Asm->OutStreamer.AddComment("Compilation Unit Length");
2016 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2018 // Emit the pubnames for this compilation unit.
2019 for (const auto &GI : Globals) {
2020 const char *Name = GI.getKeyData();
2021 const DIE *Entity = GI.second;
2023 Asm->OutStreamer.AddComment("DIE offset");
2024 Asm->EmitInt32(Entity->getOffset());
2027 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2028 Asm->OutStreamer.AddComment(
2029 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2030 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2031 Asm->EmitInt8(Desc.toBits());
2034 Asm->OutStreamer.AddComment("External Name");
2035 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2038 Asm->OutStreamer.AddComment("End Mark");
2040 Asm->OutStreamer.EmitLabel(EndLabel);
2044 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2045 const MCSection *PSec =
2046 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2047 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2049 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2052 // Emit visible names into a debug str section.
2053 void DwarfDebug::emitDebugStr() {
2054 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2055 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2058 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2059 const DebugLocEntry &Entry) {
2060 DIVariable DV(Entry.getVariable());
2061 if (Entry.isInt()) {
2062 DIBasicType BTy(resolve(DV.getType()));
2063 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2064 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2065 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2066 Streamer.EmitSLEB128(Entry.getInt());
2068 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2069 Streamer.EmitULEB128(Entry.getInt());
2071 } else if (Entry.isLocation()) {
2072 MachineLocation Loc = Entry.getLoc();
2073 if (!DV.hasComplexAddress())
2075 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2077 // Complex address entry.
2078 unsigned N = DV.getNumAddrElements();
2080 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2081 if (Loc.getOffset()) {
2083 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2084 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2085 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2086 Streamer.EmitSLEB128(DV.getAddrElement(1));
2088 // If first address element is OpPlus then emit
2089 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2090 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2091 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2095 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2098 // Emit remaining complex address elements.
2099 for (; i < N; ++i) {
2100 uint64_t Element = DV.getAddrElement(i);
2101 if (Element == DIBuilder::OpPlus) {
2102 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2103 Streamer.EmitULEB128(DV.getAddrElement(++i));
2104 } else if (Element == DIBuilder::OpDeref) {
2106 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2108 llvm_unreachable("unknown Opcode found in complex address");
2112 // else ... ignore constant fp. There is not any good way to
2113 // to represent them here in dwarf.
2117 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2118 Asm->OutStreamer.AddComment("Loc expr size");
2119 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2120 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2121 Asm->EmitLabelDifference(end, begin, 2);
2122 Asm->OutStreamer.EmitLabel(begin);
2124 APByteStreamer Streamer(*Asm);
2125 emitDebugLocEntry(Streamer, Entry);
2127 Asm->OutStreamer.EmitLabel(end);
2130 // Emit locations into the debug loc section.
2131 void DwarfDebug::emitDebugLoc() {
2132 // Start the dwarf loc section.
2133 Asm->OutStreamer.SwitchSection(
2134 Asm->getObjFileLowering().getDwarfLocSection());
2135 unsigned char Size = Asm->getDataLayout().getPointerSize();
2136 for (const auto &DebugLoc : DotDebugLocEntries) {
2137 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2138 for (const auto &Entry : DebugLoc.List) {
2139 // Set up the range. This range is relative to the entry point of the
2140 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2141 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2142 const DwarfCompileUnit *CU = Entry.getCU();
2143 if (CU->getRanges().size() == 1) {
2144 // Grab the begin symbol from the first range as our base.
2145 const MCSymbol *Base = CU->getRanges()[0].getStart();
2146 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2147 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2149 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2150 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2153 emitDebugLocEntryLocation(Entry);
2155 Asm->OutStreamer.EmitIntValue(0, Size);
2156 Asm->OutStreamer.EmitIntValue(0, Size);
2160 void DwarfDebug::emitDebugLocDWO() {
2161 Asm->OutStreamer.SwitchSection(
2162 Asm->getObjFileLowering().getDwarfLocDWOSection());
2163 for (const auto &DebugLoc : DotDebugLocEntries) {
2164 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2165 for (const auto &Entry : DebugLoc.List) {
2166 // Just always use start_length for now - at least that's one address
2167 // rather than two. We could get fancier and try to, say, reuse an
2168 // address we know we've emitted elsewhere (the start of the function?
2169 // The start of the CU or CU subrange that encloses this range?)
2170 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2171 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2172 Asm->EmitULEB128(idx);
2173 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2175 emitDebugLocEntryLocation(Entry);
2177 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2182 const MCSymbol *Start, *End;
2185 // Emit a debug aranges section, containing a CU lookup for any
2186 // address we can tie back to a CU.
2187 void DwarfDebug::emitDebugARanges() {
2188 // Start the dwarf aranges section.
2189 Asm->OutStreamer.SwitchSection(
2190 Asm->getObjFileLowering().getDwarfARangesSection());
2192 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2196 // Build a list of sections used.
2197 std::vector<const MCSection *> Sections;
2198 for (const auto &it : SectionMap) {
2199 const MCSection *Section = it.first;
2200 Sections.push_back(Section);
2203 // Sort the sections into order.
2204 // This is only done to ensure consistent output order across different runs.
2205 std::sort(Sections.begin(), Sections.end(), SectionSort);
2207 // Build a set of address spans, sorted by CU.
2208 for (const MCSection *Section : Sections) {
2209 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2210 if (List.size() < 2)
2213 // Sort the symbols by offset within the section.
2214 std::sort(List.begin(), List.end(),
2215 [&](const SymbolCU &A, const SymbolCU &B) {
2216 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2217 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2219 // Symbols with no order assigned should be placed at the end.
2220 // (e.g. section end labels)
2228 // If we have no section (e.g. common), just write out
2229 // individual spans for each symbol.
2231 for (const SymbolCU &Cur : List) {
2233 Span.Start = Cur.Sym;
2236 Spans[Cur.CU].push_back(Span);
2239 // Build spans between each label.
2240 const MCSymbol *StartSym = List[0].Sym;
2241 for (size_t n = 1, e = List.size(); n < e; n++) {
2242 const SymbolCU &Prev = List[n - 1];
2243 const SymbolCU &Cur = List[n];
2245 // Try and build the longest span we can within the same CU.
2246 if (Cur.CU != Prev.CU) {
2248 Span.Start = StartSym;
2250 Spans[Prev.CU].push_back(Span);
2257 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2259 // Build a list of CUs used.
2260 std::vector<DwarfCompileUnit *> CUs;
2261 for (const auto &it : Spans) {
2262 DwarfCompileUnit *CU = it.first;
2266 // Sort the CU list (again, to ensure consistent output order).
2267 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2268 return A->getUniqueID() < B->getUniqueID();
2271 // Emit an arange table for each CU we used.
2272 for (DwarfCompileUnit *CU : CUs) {
2273 std::vector<ArangeSpan> &List = Spans[CU];
2275 // Emit size of content not including length itself.
2276 unsigned ContentSize =
2277 sizeof(int16_t) + // DWARF ARange version number
2278 sizeof(int32_t) + // Offset of CU in the .debug_info section
2279 sizeof(int8_t) + // Pointer Size (in bytes)
2280 sizeof(int8_t); // Segment Size (in bytes)
2282 unsigned TupleSize = PtrSize * 2;
2284 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2286 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2288 ContentSize += Padding;
2289 ContentSize += (List.size() + 1) * TupleSize;
2291 // For each compile unit, write the list of spans it covers.
2292 Asm->OutStreamer.AddComment("Length of ARange Set");
2293 Asm->EmitInt32(ContentSize);
2294 Asm->OutStreamer.AddComment("DWARF Arange version number");
2295 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2296 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2297 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2298 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2299 Asm->EmitInt8(PtrSize);
2300 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2303 Asm->OutStreamer.EmitFill(Padding, 0xff);
2305 for (const ArangeSpan &Span : List) {
2306 Asm->EmitLabelReference(Span.Start, PtrSize);
2308 // Calculate the size as being from the span start to it's end.
2310 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2312 // For symbols without an end marker (e.g. common), we
2313 // write a single arange entry containing just that one symbol.
2314 uint64_t Size = SymSize[Span.Start];
2318 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2322 Asm->OutStreamer.AddComment("ARange terminator");
2323 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2324 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2328 // Emit visible names into a debug ranges section.
2329 void DwarfDebug::emitDebugRanges() {
2330 // Start the dwarf ranges section.
2331 Asm->OutStreamer.SwitchSection(
2332 Asm->getObjFileLowering().getDwarfRangesSection());
2334 // Size for our labels.
2335 unsigned char Size = Asm->getDataLayout().getPointerSize();
2337 // Grab the specific ranges for the compile units in the module.
2338 for (const auto &I : CUMap) {
2339 DwarfCompileUnit *TheCU = I.second;
2341 // Emit a symbol so we can find the beginning of our ranges.
2342 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2344 // Iterate over the misc ranges for the compile units in the module.
2345 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2346 // Emit our symbol so we can find the beginning of the range.
2347 Asm->OutStreamer.EmitLabel(List.getSym());
2349 for (const RangeSpan &Range : List.getRanges()) {
2350 const MCSymbol *Begin = Range.getStart();
2351 const MCSymbol *End = Range.getEnd();
2352 assert(Begin && "Range without a begin symbol?");
2353 assert(End && "Range without an end symbol?");
2354 if (TheCU->getRanges().size() == 1) {
2355 // Grab the begin symbol from the first range as our base.
2356 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2357 Asm->EmitLabelDifference(Begin, Base, Size);
2358 Asm->EmitLabelDifference(End, Base, Size);
2360 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2361 Asm->OutStreamer.EmitSymbolValue(End, Size);
2365 // And terminate the list with two 0 values.
2366 Asm->OutStreamer.EmitIntValue(0, Size);
2367 Asm->OutStreamer.EmitIntValue(0, Size);
2370 // Now emit a range for the CU itself.
2371 if (TheCU->getRanges().size() > 1) {
2372 Asm->OutStreamer.EmitLabel(
2373 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2374 for (const RangeSpan &Range : TheCU->getRanges()) {
2375 const MCSymbol *Begin = Range.getStart();
2376 const MCSymbol *End = Range.getEnd();
2377 assert(Begin && "Range without a begin symbol?");
2378 assert(End && "Range without an end symbol?");
2379 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2380 Asm->OutStreamer.EmitSymbolValue(End, Size);
2382 // And terminate the list with two 0 values.
2383 Asm->OutStreamer.EmitIntValue(0, Size);
2384 Asm->OutStreamer.EmitIntValue(0, Size);
2389 // DWARF5 Experimental Separate Dwarf emitters.
2391 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2392 std::unique_ptr<DwarfUnit> NewU) {
2393 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2394 U.getCUNode().getSplitDebugFilename());
2396 if (!CompilationDir.empty())
2397 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2399 addGnuPubAttributes(*NewU, Die);
2401 SkeletonHolder.addUnit(std::move(NewU));
2404 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2405 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2406 // DW_AT_addr_base, DW_AT_ranges_base.
2407 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2409 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2410 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2411 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2412 DwarfCompileUnit &NewCU = *OwnedUnit;
2413 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2414 DwarfInfoSectionSym);
2416 NewCU.initStmtList(DwarfLineSectionSym);
2418 initSkeletonUnit(CU, *Die, std::move(OwnedUnit));
2423 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2425 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2426 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2427 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2429 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2430 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2431 this, &SkeletonHolder);
2432 DwarfTypeUnit &NewTU = *OwnedUnit;
2433 NewTU.setTypeSignature(TU.getTypeSignature());
2434 NewTU.setType(nullptr);
2436 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2438 initSkeletonUnit(TU, *Die, std::move(OwnedUnit));
2442 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2443 // compile units that would normally be in debug_info.
2444 void DwarfDebug::emitDebugInfoDWO() {
2445 assert(useSplitDwarf() && "No split dwarf debug info?");
2446 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2447 // emit relocations into the dwo file.
2448 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2451 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2452 // abbreviations for the .debug_info.dwo section.
2453 void DwarfDebug::emitDebugAbbrevDWO() {
2454 assert(useSplitDwarf() && "No split dwarf?");
2455 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2458 void DwarfDebug::emitDebugLineDWO() {
2459 assert(useSplitDwarf() && "No split dwarf?");
2460 Asm->OutStreamer.SwitchSection(
2461 Asm->getObjFileLowering().getDwarfLineDWOSection());
2462 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2465 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2466 // string section and is identical in format to traditional .debug_str
2468 void DwarfDebug::emitDebugStrDWO() {
2469 assert(useSplitDwarf() && "No split dwarf?");
2470 const MCSection *OffSec =
2471 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2472 const MCSymbol *StrSym = DwarfStrSectionSym;
2473 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2477 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2478 if (!useSplitDwarf())
2481 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2482 return &SplitTypeUnitFileTable;
2485 static uint64_t makeTypeSignature(StringRef Identifier) {
2487 Hash.update(Identifier);
2488 // ... take the least significant 8 bytes and return those. Our MD5
2489 // implementation always returns its results in little endian, swap bytes
2491 MD5::MD5Result Result;
2493 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2496 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2497 StringRef Identifier, DIE &RefDie,
2498 DICompositeType CTy) {
2499 // Fast path if we're building some type units and one has already used the
2500 // address pool we know we're going to throw away all this work anyway, so
2501 // don't bother building dependent types.
2502 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2505 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2507 CU.addDIETypeSignature(RefDie, *TU);
2511 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2512 AddrPool.resetUsedFlag();
2514 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2516 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2517 this, &InfoHolder, getDwoLineTable(CU));
2518 DwarfTypeUnit &NewTU = *OwnedUnit;
2520 TypeUnitsUnderConstruction.push_back(std::make_pair(std::move(OwnedUnit), CTy));
2522 NewTU.addUInt(*UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2525 uint64_t Signature = makeTypeSignature(Identifier);
2526 NewTU.setTypeSignature(Signature);
2528 if (!useSplitDwarf())
2529 CU.applyStmtList(*UnitDie);
2533 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2534 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2536 NewTU.setType(NewTU.createTypeDIE(CTy));
2539 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2540 TypeUnitsUnderConstruction.clear();
2542 // Types referencing entries in the address table cannot be placed in type
2544 if (AddrPool.hasBeenUsed()) {
2546 // Remove all the types built while building this type.
2547 // This is pessimistic as some of these types might not be dependent on
2548 // the type that used an address.
2549 for (const auto &TU : TypeUnitsToAdd)
2550 DwarfTypeUnits.erase(TU.second);
2552 // Construct this type in the CU directly.
2553 // This is inefficient because all the dependent types will be rebuilt
2554 // from scratch, including building them in type units, discovering that
2555 // they depend on addresses, throwing them out and rebuilding them.
2556 CU.constructTypeDIE(RefDie, CTy);
2560 // If the type wasn't dependent on fission addresses, finish adding the type
2561 // and all its dependent types.
2562 for (auto &TU : TypeUnitsToAdd) {
2563 if (useSplitDwarf())
2564 TU.first->setSkeleton(constructSkeletonTU(*TU.first));
2565 InfoHolder.addUnit(std::move(TU.first));
2568 CU.addDIETypeSignature(RefDie, NewTU);
2571 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2572 MCSymbol *Begin, MCSymbol *End) {
2573 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2574 if (DwarfVersion < 4)
2575 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2577 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2580 // Accelerator table mutators - add each name along with its companion
2581 // DIE to the proper table while ensuring that the name that we're going
2582 // to reference is in the string table. We do this since the names we
2583 // add may not only be identical to the names in the DIE.
2584 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2585 if (!useDwarfAccelTables())
2587 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2591 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2592 if (!useDwarfAccelTables())
2594 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2598 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2599 if (!useDwarfAccelTables())
2601 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2605 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2606 if (!useDwarfAccelTables())
2608 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),