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());
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type)
154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156 DIArray Elements = DICompositeType(subType).getTypeArray();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
173 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, "skel_string", DIEValueAllocator),
176 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
177 dwarf::DW_FORM_data4)),
178 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
179 dwarf::DW_FORM_data4)),
180 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
181 dwarf::DW_FORM_data4)),
182 AccelTypes(TypeAtoms) {
184 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
185 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
186 DwarfLineSectionSym = nullptr;
187 DwarfAddrSectionSym = nullptr;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
189 FunctionBeginSym = FunctionEndSym = nullptr;
193 // Turn on accelerator tables for Darwin by default, pubnames by
194 // default for non-Darwin, and handle split dwarf.
195 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
197 if (DwarfAccelTables == Default)
198 HasDwarfAccelTables = IsDarwin;
200 HasDwarfAccelTables = DwarfAccelTables == Enable;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable;
207 if (DwarfPubSections == Default)
208 HasDwarfPubSections = !IsDarwin;
210 HasDwarfPubSections = DwarfPubSections == Enable;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
216 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
221 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
222 DwarfDebug::~DwarfDebug() { }
224 // Switch to the specified MCSection and emit an assembler
225 // temporary label to it if SymbolStem is specified.
226 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
227 const char *SymbolStem = nullptr) {
228 Asm->OutStreamer.SwitchSection(Section);
232 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
233 Asm->OutStreamer.EmitLabel(TmpSym);
237 static bool isObjCClass(StringRef Name) {
238 return Name.startswith("+") || Name.startswith("-");
241 static bool hasObjCCategory(StringRef Name) {
242 if (!isObjCClass(Name))
245 return Name.find(") ") != StringRef::npos;
248 static void getObjCClassCategory(StringRef In, StringRef &Class,
249 StringRef &Category) {
250 if (!hasObjCCategory(In)) {
251 Class = In.slice(In.find('[') + 1, In.find(' '));
256 Class = In.slice(In.find('[') + 1, In.find('('));
257 Category = In.slice(In.find('[') + 1, In.find(' '));
261 static StringRef getObjCMethodName(StringRef In) {
262 return In.slice(In.find(' ') + 1, In.find(']'));
265 // Helper for sorting sections into a stable output order.
266 static bool SectionSort(const MCSection *A, const MCSection *B) {
267 std::string LA = (A ? A->getLabelBeginName() : "");
268 std::string LB = (B ? B->getLabelBeginName() : "");
272 // Add the various names to the Dwarf accelerator table names.
273 // TODO: Determine whether or not we should add names for programs
274 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
275 // is only slightly different than the lookup of non-standard ObjC names.
276 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
277 if (!SP.isDefinition())
279 addAccelName(SP.getName(), Die);
281 // If the linkage name is different than the name, go ahead and output
282 // that as well into the name table.
283 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
284 addAccelName(SP.getLinkageName(), Die);
286 // If this is an Objective-C selector name add it to the ObjC accelerator
288 if (isObjCClass(SP.getName())) {
289 StringRef Class, Category;
290 getObjCClassCategory(SP.getName(), Class, Category);
291 addAccelObjC(Class, Die);
293 addAccelObjC(Category, Die);
294 // Also add the base method name to the name table.
295 addAccelName(getObjCMethodName(SP.getName()), Die);
299 /// isSubprogramContext - Return true if Context is either a subprogram
300 /// or another context nested inside a subprogram.
301 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
304 DIDescriptor D(Context);
305 if (D.isSubprogram())
308 return isSubprogramContext(resolve(DIType(Context).getContext()));
312 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
313 // and DW_AT_high_pc attributes. If there are global variables in this
314 // scope then create and insert DIEs for these variables.
315 DIE &DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
317 DIE *SPDie = SPCU.getDIE(SP);
319 assert(SPDie && "Unable to find subprogram DIE!");
321 // If we're updating an abstract DIE, then we will be adding the children and
322 // object pointer later on. But what we don't want to do is process the
323 // concrete DIE twice.
324 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
325 // Pick up abstract subprogram DIE.
326 SPDie = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
327 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
329 DISubprogram SPDecl = SP.getFunctionDeclaration();
330 if (!SPDecl.isSubprogram()) {
331 // There is not any need to generate specification DIE for a function
332 // defined at compile unit level. If a function is defined inside another
333 // function then gdb prefers the definition at top level and but does not
334 // expect specification DIE in parent function. So avoid creating
335 // specification DIE for a function defined inside a function.
336 DIScope SPContext = resolve(SP.getContext());
337 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
338 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
339 SPCU.addFlag(*SPDie, dwarf::DW_AT_declaration);
342 DICompositeType SPTy = SP.getType();
343 DIArray Args = SPTy.getTypeArray();
344 uint16_t SPTag = SPTy.getTag();
345 if (SPTag == dwarf::DW_TAG_subroutine_type)
346 SPCU.constructSubprogramArguments(*SPDie, Args);
347 DIE *SPDeclDie = SPDie;
349 &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
350 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_specification, *SPDeclDie);
355 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
357 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
358 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
359 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
361 // Add name to the name table, we do this here because we're guaranteed
362 // to have concrete versions of our DW_TAG_subprogram nodes.
363 addSubprogramNames(SP, *SPDie);
368 /// Check whether we should create a DIE for the given Scope, return true
369 /// if we don't create a DIE (the corresponding DIE is null).
370 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
371 if (Scope->isAbstractScope())
374 // We don't create a DIE if there is no Range.
375 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
379 if (Ranges.size() > 1)
382 // We don't create a DIE if we have a single Range and the end label
384 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
385 MCSymbol *End = getLabelAfterInsn(RI->second);
389 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
390 dwarf::Attribute A, const MCSymbol *L,
391 const MCSymbol *Sec) {
392 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
393 U.addSectionLabel(D, A, L);
395 U.addSectionDelta(D, A, L, Sec);
398 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
399 const SmallVectorImpl<InsnRange> &Range) {
400 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
401 // emitting it appropriately.
402 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
404 // Under fission, ranges are specified by constant offsets relative to the
405 // CU's DW_AT_GNU_ranges_base.
407 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
408 DwarfDebugRangeSectionSym);
410 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
411 DwarfDebugRangeSectionSym);
413 RangeSpanList List(RangeSym);
414 for (const InsnRange &R : Range) {
415 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
416 List.addRange(std::move(Span));
419 // Add the range list to the set of ranges to be emitted.
420 TheCU.addRangeList(std::move(List));
423 // Construct new DW_TAG_lexical_block for this scope and attach
424 // DW_AT_low_pc/DW_AT_high_pc labels.
426 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
427 LexicalScope *Scope) {
428 if (isLexicalScopeDIENull(Scope))
431 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
432 if (Scope->isAbstractScope())
435 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
437 // If we have multiple ranges, emit them into the range section.
438 if (ScopeRanges.size() > 1) {
439 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
443 // Construct the address range for this DIE.
444 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
445 MCSymbol *Start = getLabelBeforeInsn(RI->first);
446 MCSymbol *End = getLabelAfterInsn(RI->second);
447 assert(End && "End label should not be null!");
449 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
450 assert(End->isDefined() && "Invalid end label for an inlined scope!");
452 attachLowHighPC(TheCU, *ScopeDIE, Start, End);
457 // This scope represents inlined body of a function. Construct DIE to
458 // represent this concrete inlined copy of the function.
460 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
461 LexicalScope *Scope) {
462 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
463 assert(!ScopeRanges.empty() &&
464 "LexicalScope does not have instruction markers!");
466 if (!Scope->getScopeNode())
468 DIScope DS(Scope->getScopeNode());
469 DISubprogram InlinedSP = getDISubprogram(DS);
470 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
472 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
476 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
477 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
479 // If we have multiple ranges, emit them into the range section.
480 if (ScopeRanges.size() > 1)
481 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
483 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
484 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
485 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
487 if (!StartLabel || !EndLabel)
488 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
490 assert(StartLabel->isDefined() &&
491 "Invalid starting label for an inlined scope!");
492 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
494 attachLowHighPC(TheCU, *ScopeDIE, StartLabel, EndLabel);
497 InlinedSubprogramDIEs.insert(OriginDIE);
499 // Add the call site information to the DIE.
500 DILocation DL(Scope->getInlinedAt());
501 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
502 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
503 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
505 // Add name to the name table, we do this here because we're guaranteed
506 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
507 addSubprogramNames(InlinedSP, *ScopeDIE);
512 DIE *DwarfDebug::createScopeChildrenDIE(
513 DwarfCompileUnit &TheCU, LexicalScope *Scope,
514 SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
515 DIE *ObjectPointer = nullptr;
517 // Collect arguments for current function.
518 if (LScopes.isCurrentFunctionScope(Scope)) {
519 for (DbgVariable *ArgDV : CurrentFnArguments)
522 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope()));
523 if (ArgDV->isObjectPointer())
524 ObjectPointer = Children.back().get();
527 // If this is a variadic function, add an unspecified parameter.
528 DISubprogram SP(Scope->getScopeNode());
529 DIArray FnArgs = SP.getType().getTypeArray();
530 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
531 .isUnspecifiedParameter()) {
533 make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
537 // Collect lexical scope children first.
538 for (DbgVariable *DV : ScopeVariables.lookup(Scope)) {
540 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope()));
541 if (DV->isObjectPointer())
542 ObjectPointer = Children.back().get();
544 for (LexicalScope *LS : Scope->getChildren())
545 if (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
546 Children.push_back(std::move(Nested));
547 return ObjectPointer;
550 void DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
551 LexicalScope *Scope, DIE &ScopeDIE) {
552 // We create children when the scope DIE is not null.
553 SmallVector<std::unique_ptr<DIE>, 8> Children;
554 if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
555 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
558 for (auto &I : Children)
559 ScopeDIE.addChild(std::move(I));
562 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
563 LexicalScope *Scope) {
564 assert(Scope && Scope->getScopeNode());
565 assert(Scope->isAbstractScope());
566 assert(!Scope->getInlinedAt());
568 DISubprogram Sub(Scope->getScopeNode());
570 ProcessedSPNodes.insert(Sub);
572 if (DIE *ScopeDIE = TheCU.getDIE(Sub)) {
573 AbstractSPDies.insert(std::make_pair(Sub, ScopeDIE));
574 createAndAddScopeChildren(TheCU, Scope, *ScopeDIE);
578 DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
579 LexicalScope *Scope) {
580 assert(Scope && Scope->getScopeNode());
581 assert(!Scope->getInlinedAt());
582 assert(!Scope->isAbstractScope());
583 assert(DIScope(Scope->getScopeNode()).isSubprogram());
585 DISubprogram Sub(Scope->getScopeNode());
587 ProcessedSPNodes.insert(Sub);
589 DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
591 createAndAddScopeChildren(TheCU, Scope, ScopeDIE);
596 // Construct a DIE for this scope.
597 std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
598 LexicalScope *Scope) {
599 if (!Scope || !Scope->getScopeNode())
602 DIScope DS(Scope->getScopeNode());
604 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
605 "Only handle inlined subprograms here, use "
606 "constructSubprogramScopeDIE for non-inlined "
609 SmallVector<std::unique_ptr<DIE>, 8> Children;
611 // We try to create the scope DIE first, then the children DIEs. This will
612 // avoid creating un-used children then removing them later when we find out
613 // the scope DIE is null.
614 std::unique_ptr<DIE> ScopeDIE;
615 if (Scope->getInlinedAt()) {
616 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
619 // We create children when the scope DIE is not null.
620 createScopeChildrenDIE(TheCU, Scope, Children);
622 // Early exit when we know the scope DIE is going to be null.
623 if (isLexicalScopeDIENull(Scope))
626 // We create children here when we know the scope DIE is not going to be
627 // null and the children will be added to the scope DIE.
628 createScopeChildrenDIE(TheCU, Scope, Children);
630 // There is no need to emit empty lexical block DIE.
631 std::pair<ImportedEntityMap::const_iterator,
632 ImportedEntityMap::const_iterator> Range =
633 std::equal_range(ScopesWithImportedEntities.begin(),
634 ScopesWithImportedEntities.end(),
635 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
637 if (Children.empty() && Range.first == Range.second)
639 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
640 assert(ScopeDIE && "Scope DIE should not be null.");
641 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
643 constructImportedEntityDIE(TheCU, i->second, *ScopeDIE);
647 for (auto &I : Children)
648 ScopeDIE->addChild(std::move(I));
653 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
654 if (!GenerateGnuPubSections)
657 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
660 // Create new DwarfCompileUnit for the given metadata node with tag
661 // DW_TAG_compile_unit.
662 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
663 StringRef FN = DIUnit.getFilename();
664 CompilationDir = DIUnit.getDirectory();
666 auto OwnedUnit = make_unique<DwarfCompileUnit>(
667 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
668 DwarfCompileUnit &NewCU = *OwnedUnit;
669 DIE &Die = NewCU.getUnitDie();
670 InfoHolder.addUnit(std::move(OwnedUnit));
672 // LTO with assembly output shares a single line table amongst multiple CUs.
673 // To avoid the compilation directory being ambiguous, let the line table
674 // explicitly describe the directory of all files, never relying on the
675 // compilation directory.
676 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
677 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
678 NewCU.getUniqueID(), CompilationDir);
680 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
681 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
682 DIUnit.getLanguage());
683 NewCU.addString(Die, dwarf::DW_AT_name, FN);
685 if (!useSplitDwarf()) {
686 NewCU.initStmtList(DwarfLineSectionSym);
688 // If we're using split dwarf the compilation dir is going to be in the
689 // skeleton CU and so we don't need to duplicate it here.
690 if (!CompilationDir.empty())
691 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
693 addGnuPubAttributes(NewCU, Die);
696 if (DIUnit.isOptimized())
697 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
699 StringRef Flags = DIUnit.getFlags();
701 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
703 if (unsigned RVer = DIUnit.getRunTimeVersion())
704 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
705 dwarf::DW_FORM_data1, RVer);
710 if (useSplitDwarf()) {
711 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
712 DwarfInfoDWOSectionSym);
713 NewCU.setSkeleton(constructSkeletonCU(NewCU));
715 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
716 DwarfInfoSectionSym);
718 CUMap.insert(std::make_pair(DIUnit, &NewCU));
719 CUDieMap.insert(std::make_pair(&Die, &NewCU));
723 // Construct subprogram DIE.
724 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
726 // FIXME: We should only call this routine once, however, during LTO if a
727 // program is defined in multiple CUs we could end up calling it out of
728 // beginModule as we walk the CUs.
730 DwarfCompileUnit *&CURef = SPMap[N];
736 if (!SP.isDefinition())
737 // This is a method declaration which will be handled while constructing
741 DIE &SubprogramDie = *TheCU.getOrCreateSubprogramDIE(SP);
743 // Expose as a global name.
744 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
747 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
749 DIImportedEntity Module(N);
750 assert(Module.Verify());
751 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
752 constructImportedEntityDIE(TheCU, Module, *D);
755 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
756 const MDNode *N, DIE &Context) {
757 DIImportedEntity Module(N);
758 assert(Module.Verify());
759 return constructImportedEntityDIE(TheCU, Module, Context);
762 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
763 const DIImportedEntity &Module,
765 assert(Module.Verify() &&
766 "Use one of the MDNode * overloads to handle invalid metadata");
767 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), Context, Module);
769 DIDescriptor Entity = resolve(Module.getEntity());
770 if (Entity.isNameSpace())
771 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
772 else if (Entity.isSubprogram())
773 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
774 else if (Entity.isType())
775 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
777 EntityDie = TheCU.getDIE(Entity);
778 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
779 Module.getContext().getFilename(),
780 Module.getContext().getDirectory());
781 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
782 StringRef Name = Module.getName();
784 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
787 // Emit all Dwarf sections that should come prior to the content. Create
788 // global DIEs and emit initial debug info sections. This is invoked by
789 // the target AsmPrinter.
790 void DwarfDebug::beginModule() {
791 if (DisableDebugInfoPrinting)
794 const Module *M = MMI->getModule();
796 // If module has named metadata anchors then use them, otherwise scan the
797 // module using debug info finder to collect debug info.
798 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
801 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
803 // Emit initial sections so we can reference labels later.
806 SingleCU = CU_Nodes->getNumOperands() == 1;
808 for (MDNode *N : CU_Nodes->operands()) {
809 DICompileUnit CUNode(N);
810 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
811 DIArray ImportedEntities = CUNode.getImportedEntities();
812 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
813 ScopesWithImportedEntities.push_back(std::make_pair(
814 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
815 ImportedEntities.getElement(i)));
816 std::sort(ScopesWithImportedEntities.begin(),
817 ScopesWithImportedEntities.end(), less_first());
818 DIArray GVs = CUNode.getGlobalVariables();
819 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
820 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
821 DIArray SPs = CUNode.getSubprograms();
822 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
823 constructSubprogramDIE(CU, SPs.getElement(i));
824 DIArray EnumTypes = CUNode.getEnumTypes();
825 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
826 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
827 DIArray RetainedTypes = CUNode.getRetainedTypes();
828 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
829 DIType Ty(RetainedTypes.getElement(i));
830 // The retained types array by design contains pointers to
831 // MDNodes rather than DIRefs. Unique them here.
832 DIType UniqueTy(resolve(Ty.getRef()));
833 CU.getOrCreateTypeDIE(UniqueTy);
835 // Emit imported_modules last so that the relevant context is already
837 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
838 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
841 // Tell MMI that we have debug info.
842 MMI->setDebugInfoAvailability(true);
844 // Prime section data.
845 SectionMap[Asm->getObjFileLowering().getTextSection()];
848 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
849 void DwarfDebug::computeInlinedDIEs() {
850 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
851 for (DIE *ISP : InlinedSubprogramDIEs)
852 FirstCU->addUInt(*ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
854 for (const auto &AI : AbstractSPDies) {
855 DIE &ISP = *AI.second;
856 if (InlinedSubprogramDIEs.count(&ISP))
858 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
862 // Collect info for variables that were optimized out.
863 void DwarfDebug::collectDeadVariables() {
864 const Module *M = MMI->getModule();
866 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
867 for (MDNode *N : CU_Nodes->operands()) {
868 DICompileUnit TheCU(N);
869 DIArray Subprograms = TheCU.getSubprograms();
870 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
871 DISubprogram SP(Subprograms.getElement(i));
872 if (ProcessedSPNodes.count(SP) != 0)
874 if (!SP.isSubprogram())
876 if (!SP.isDefinition())
878 DIArray Variables = SP.getVariables();
879 if (Variables.getNumElements() == 0)
882 // Construct subprogram DIE and add variables DIEs.
883 DwarfCompileUnit *SPCU =
884 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
885 assert(SPCU && "Unable to find Compile Unit!");
886 // FIXME: See the comment in constructSubprogramDIE about duplicate
888 constructSubprogramDIE(*SPCU, SP);
889 DIE *SPDIE = SPCU->getDIE(SP);
890 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
891 DIVariable DV(Variables.getElement(vi));
892 if (!DV.isVariable())
894 DbgVariable NewVar(DV, nullptr, this);
895 SPDIE->addChild(SPCU->constructVariableDIE(NewVar, false));
902 void DwarfDebug::finalizeModuleInfo() {
903 // Collect info for variables that were optimized out.
904 collectDeadVariables();
906 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
907 computeInlinedDIEs();
909 // Handle anything that needs to be done on a per-unit basis after
910 // all other generation.
911 for (const auto &TheU : getUnits()) {
912 // Emit DW_AT_containing_type attribute to connect types with their
913 // vtable holding type.
914 TheU->constructContainingTypeDIEs();
916 // Add CU specific attributes if we need to add any.
917 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
918 // If we're splitting the dwarf out now that we've got the entire
919 // CU then add the dwo id to it.
920 DwarfCompileUnit *SkCU =
921 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
922 if (useSplitDwarf()) {
923 // Emit a unique identifier for this CU.
924 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
925 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
926 dwarf::DW_FORM_data8, ID);
927 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
928 dwarf::DW_FORM_data8, ID);
930 // We don't keep track of which addresses are used in which CU so this
931 // is a bit pessimistic under LTO.
932 if (!AddrPool.isEmpty())
933 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
934 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
935 DwarfAddrSectionSym);
936 if (!TheU->getRangeLists().empty())
937 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
938 dwarf::DW_AT_GNU_ranges_base,
939 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
942 // If we have code split among multiple sections or non-contiguous
943 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
944 // remain in the .o file, otherwise add a DW_AT_low_pc.
945 // FIXME: We should use ranges allow reordering of code ala
946 // .subsections_via_symbols in mach-o. This would mean turning on
947 // ranges for all subprogram DIEs for mach-o.
948 DwarfCompileUnit &U =
949 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
950 unsigned NumRanges = TheU->getRanges().size();
953 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
954 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
955 DwarfDebugRangeSectionSym);
957 // A DW_AT_low_pc attribute may also be specified in combination with
958 // DW_AT_ranges to specify the default base address for use in
959 // location lists (see Section 2.6.2) and range lists (see Section
961 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
964 RangeSpan &Range = TheU->getRanges().back();
965 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
967 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
974 // Compute DIE offsets and sizes.
975 InfoHolder.computeSizeAndOffsets();
977 SkeletonHolder.computeSizeAndOffsets();
980 void DwarfDebug::endSections() {
981 // Filter labels by section.
982 for (const SymbolCU &SCU : ArangeLabels) {
983 if (SCU.Sym->isInSection()) {
984 // Make a note of this symbol and it's section.
985 const MCSection *Section = &SCU.Sym->getSection();
986 if (!Section->getKind().isMetadata())
987 SectionMap[Section].push_back(SCU);
989 // Some symbols (e.g. common/bss on mach-o) can have no section but still
990 // appear in the output. This sucks as we rely on sections to build
991 // arange spans. We can do it without, but it's icky.
992 SectionMap[nullptr].push_back(SCU);
996 // Build a list of sections used.
997 std::vector<const MCSection *> Sections;
998 for (const auto &it : SectionMap) {
999 const MCSection *Section = it.first;
1000 Sections.push_back(Section);
1003 // Sort the sections into order.
1004 // This is only done to ensure consistent output order across different runs.
1005 std::sort(Sections.begin(), Sections.end(), SectionSort);
1007 // Add terminating symbols for each section.
1008 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1009 const MCSection *Section = Sections[ID];
1010 MCSymbol *Sym = nullptr;
1013 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1014 // if we know the section name up-front. For user-created sections, the
1015 // resulting label may not be valid to use as a label. (section names can
1016 // use a greater set of characters on some systems)
1017 Sym = Asm->GetTempSymbol("debug_end", ID);
1018 Asm->OutStreamer.SwitchSection(Section);
1019 Asm->OutStreamer.EmitLabel(Sym);
1022 // Insert a final terminator.
1023 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1027 // Emit all Dwarf sections that should come after the content.
1028 void DwarfDebug::endModule() {
1029 assert(CurFn == nullptr);
1030 assert(CurMI == nullptr);
1035 // End any existing sections.
1036 // TODO: Does this need to happen?
1039 // Finalize the debug info for the module.
1040 finalizeModuleInfo();
1044 // Emit all the DIEs into a debug info section.
1047 // Corresponding abbreviations into a abbrev section.
1048 emitAbbreviations();
1050 // Emit info into a debug aranges section.
1051 if (GenerateARangeSection)
1054 // Emit info into a debug ranges section.
1057 if (useSplitDwarf()) {
1060 emitDebugAbbrevDWO();
1062 // Emit DWO addresses.
1063 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1066 // Emit info into a debug loc section.
1069 // Emit info into the dwarf accelerator table sections.
1070 if (useDwarfAccelTables()) {
1073 emitAccelNamespaces();
1077 // Emit the pubnames and pubtypes sections if requested.
1078 if (HasDwarfPubSections) {
1079 emitDebugPubNames(GenerateGnuPubSections);
1080 emitDebugPubTypes(GenerateGnuPubSections);
1086 // Reset these for the next Module if we have one.
1090 // Find abstract variable, if any, associated with Var.
1091 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1092 DebugLoc ScopeLoc) {
1093 LLVMContext &Ctx = DV->getContext();
1094 // More then one inlined variable corresponds to one abstract variable.
1095 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1096 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1098 return AbsDbgVariable;
1100 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1104 AbsDbgVariable = new DbgVariable(Var, nullptr, this);
1105 addScopeVariable(Scope, AbsDbgVariable);
1106 AbstractVariables[Var] = AbsDbgVariable;
1107 return AbsDbgVariable;
1110 // If Var is a current function argument then add it to CurrentFnArguments list.
1111 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1112 if (!LScopes.isCurrentFunctionScope(Scope))
1114 DIVariable DV = Var->getVariable();
1115 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1117 unsigned ArgNo = DV.getArgNumber();
1121 size_t Size = CurrentFnArguments.size();
1123 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1124 // llvm::Function argument size is not good indicator of how many
1125 // arguments does the function have at source level.
1127 CurrentFnArguments.resize(ArgNo * 2);
1128 CurrentFnArguments[ArgNo - 1] = Var;
1132 // Collect variable information from side table maintained by MMI.
1133 void DwarfDebug::collectVariableInfoFromMMITable(
1134 SmallPtrSet<const MDNode *, 16> &Processed) {
1135 for (const auto &VI : MMI->getVariableDbgInfo()) {
1138 Processed.insert(VI.Var);
1139 DIVariable DV(VI.Var);
1140 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1142 // If variable scope is not found then skip this variable.
1146 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1147 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1148 RegVar->setFrameIndex(VI.Slot);
1149 if (!addCurrentFnArgument(RegVar, Scope))
1150 addScopeVariable(Scope, RegVar);
1152 AbsDbgVariable->setFrameIndex(VI.Slot);
1156 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1158 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1159 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1160 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1161 MI->getOperand(0).getReg() &&
1162 (MI->getOperand(1).isImm() ||
1163 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1166 // Get .debug_loc entry for the instruction range starting at MI.
1167 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1168 const MDNode *Var = MI->getDebugVariable();
1170 assert(MI->getNumOperands() == 3);
1171 if (MI->getOperand(0).isReg()) {
1172 MachineLocation MLoc;
1173 // If the second operand is an immediate, this is a
1174 // register-indirect address.
1175 if (!MI->getOperand(1).isImm())
1176 MLoc.set(MI->getOperand(0).getReg());
1178 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1179 return DebugLocEntry::Value(Var, MLoc);
1181 if (MI->getOperand(0).isImm())
1182 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1183 if (MI->getOperand(0).isFPImm())
1184 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1185 if (MI->getOperand(0).isCImm())
1186 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1188 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1191 // Find variables for each lexical scope.
1193 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1194 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1195 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1197 // Grab the variable info that was squirreled away in the MMI side-table.
1198 collectVariableInfoFromMMITable(Processed);
1200 for (const MDNode *Var : UserVariables) {
1201 if (Processed.count(Var))
1204 // History contains relevant DBG_VALUE instructions for Var and instructions
1206 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1207 if (History.empty())
1209 const MachineInstr *MInsn = History.front();
1212 LexicalScope *Scope = nullptr;
1213 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1214 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1215 Scope = LScopes.getCurrentFunctionScope();
1216 else if (MDNode *IA = DV.getInlinedAt())
1217 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1219 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1220 // If variable scope is not found then skip this variable.
1224 Processed.insert(DV);
1225 assert(MInsn->isDebugValue() && "History must begin with debug value");
1226 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1227 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1228 if (!addCurrentFnArgument(RegVar, Scope))
1229 addScopeVariable(Scope, RegVar);
1231 AbsVar->setMInsn(MInsn);
1233 // Simplify ranges that are fully coalesced.
1234 if (History.size() <= 1 ||
1235 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1236 RegVar->setMInsn(MInsn);
1240 // Handle multiple DBG_VALUE instructions describing one variable.
1241 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1243 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1244 DebugLocList &LocList = DotDebugLocEntries.back();
1246 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1247 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1248 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1249 HI = History.begin(),
1252 const MachineInstr *Begin = *HI;
1253 assert(Begin->isDebugValue() && "Invalid History entry");
1255 // Check if DBG_VALUE is truncating a range.
1256 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1257 !Begin->getOperand(0).getReg())
1260 // Compute the range for a register location.
1261 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1262 const MCSymbol *SLabel = nullptr;
1265 // If Begin is the last instruction in History then its value is valid
1266 // until the end of the function.
1267 SLabel = FunctionEndSym;
1269 const MachineInstr *End = HI[1];
1270 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1271 << "\t" << *Begin << "\t" << *End << "\n");
1272 if (End->isDebugValue())
1273 SLabel = getLabelBeforeInsn(End);
1275 // End is a normal instruction clobbering the range.
1276 SLabel = getLabelAfterInsn(End);
1277 assert(SLabel && "Forgot label after clobber instruction");
1282 // The value is valid until the next DBG_VALUE or clobber.
1283 DebugLocEntry Loc(FLabel, SLabel, getDebugLocValue(Begin), TheCU);
1284 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1285 DebugLoc.push_back(std::move(Loc));
1289 // Collect info for variables that were optimized out.
1290 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1291 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1292 DIVariable DV(Variables.getElement(i));
1293 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1295 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1296 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1300 // Return Label preceding the instruction.
1301 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1302 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1303 assert(Label && "Didn't insert label before instruction");
1307 // Return Label immediately following the instruction.
1308 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1309 return LabelsAfterInsn.lookup(MI);
1312 // Process beginning of an instruction.
1313 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1314 assert(CurMI == nullptr);
1316 // Check if source location changes, but ignore DBG_VALUE locations.
1317 if (!MI->isDebugValue()) {
1318 DebugLoc DL = MI->getDebugLoc();
1319 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1322 if (DL == PrologEndLoc) {
1323 Flags |= DWARF2_FLAG_PROLOGUE_END;
1324 PrologEndLoc = DebugLoc();
1326 if (PrologEndLoc.isUnknown())
1327 Flags |= DWARF2_FLAG_IS_STMT;
1329 if (!DL.isUnknown()) {
1330 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1331 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1333 recordSourceLine(0, 0, nullptr, 0);
1337 // Insert labels where requested.
1338 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1339 LabelsBeforeInsn.find(MI);
1342 if (I == LabelsBeforeInsn.end())
1345 // Label already assigned.
1350 PrevLabel = MMI->getContext().CreateTempSymbol();
1351 Asm->OutStreamer.EmitLabel(PrevLabel);
1353 I->second = PrevLabel;
1356 // Process end of an instruction.
1357 void DwarfDebug::endInstruction() {
1358 assert(CurMI != nullptr);
1359 // Don't create a new label after DBG_VALUE instructions.
1360 // They don't generate code.
1361 if (!CurMI->isDebugValue())
1362 PrevLabel = nullptr;
1364 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1365 LabelsAfterInsn.find(CurMI);
1369 if (I == LabelsAfterInsn.end())
1372 // Label already assigned.
1376 // We need a label after this instruction.
1378 PrevLabel = MMI->getContext().CreateTempSymbol();
1379 Asm->OutStreamer.EmitLabel(PrevLabel);
1381 I->second = PrevLabel;
1384 // Each LexicalScope has first instruction and last instruction to mark
1385 // beginning and end of a scope respectively. Create an inverse map that list
1386 // scopes starts (and ends) with an instruction. One instruction may start (or
1387 // end) multiple scopes. Ignore scopes that are not reachable.
1388 void DwarfDebug::identifyScopeMarkers() {
1389 SmallVector<LexicalScope *, 4> WorkList;
1390 WorkList.push_back(LScopes.getCurrentFunctionScope());
1391 while (!WorkList.empty()) {
1392 LexicalScope *S = WorkList.pop_back_val();
1394 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1395 if (!Children.empty())
1396 WorkList.append(Children.begin(), Children.end());
1398 if (S->isAbstractScope())
1401 for (const InsnRange &R : S->getRanges()) {
1402 assert(R.first && "InsnRange does not have first instruction!");
1403 assert(R.second && "InsnRange does not have second instruction!");
1404 requestLabelBeforeInsn(R.first);
1405 requestLabelAfterInsn(R.second);
1410 // Gather pre-function debug information. Assumes being called immediately
1411 // after the function entry point has been emitted.
1412 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1415 // If there's no debug info for the function we're not going to do anything.
1416 if (!MMI->hasDebugInfo())
1419 // Grab the lexical scopes for the function, if we don't have any of those
1420 // then we're not going to be able to do anything.
1421 LScopes.initialize(*MF);
1422 if (LScopes.empty())
1425 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1427 // Make sure that each lexical scope will have a begin/end label.
1428 identifyScopeMarkers();
1430 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1431 // belongs to so that we add to the correct per-cu line table in the
1433 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1434 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1435 assert(TheCU && "Unable to find compile unit!");
1436 if (Asm->OutStreamer.hasRawTextSupport())
1437 // Use a single line table if we are generating assembly.
1438 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1440 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1442 // Emit a label for the function so that we have a beginning address.
1443 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1444 // Assumes in correct section after the entry point.
1445 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1447 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1448 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1449 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1451 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1453 bool AtBlockEntry = true;
1454 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1456 const MachineInstr *MI = II;
1458 if (MI->isDebugValue()) {
1459 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1461 // Keep track of user variables.
1462 const MDNode *Var = MI->getDebugVariable();
1464 // Variable is in a register, we need to check for clobbers.
1465 if (isDbgValueInDefinedReg(MI))
1466 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1468 // Check the history of this variable.
1469 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1470 if (History.empty()) {
1471 UserVariables.push_back(Var);
1472 // The first mention of a function argument gets the FunctionBeginSym
1473 // label, so arguments are visible when breaking at function entry.
1475 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1476 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1477 LabelsBeforeInsn[MI] = FunctionBeginSym;
1479 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1480 const MachineInstr *Prev = History.back();
1481 if (Prev->isDebugValue()) {
1482 // Coalesce identical entries at the end of History.
1483 if (History.size() >= 2 &&
1484 Prev->isIdenticalTo(History[History.size() - 2])) {
1485 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1486 << "\t" << *Prev << "\t"
1487 << *History[History.size() - 2] << "\n");
1491 // Terminate old register assignments that don't reach MI;
1492 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1493 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1494 isDbgValueInDefinedReg(Prev)) {
1495 // Previous register assignment needs to terminate at the end of
1497 MachineBasicBlock::const_iterator LastMI =
1498 PrevMBB->getLastNonDebugInstr();
1499 if (LastMI == PrevMBB->end()) {
1500 // Drop DBG_VALUE for empty range.
1501 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1502 << "\t" << *Prev << "\n");
1504 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1505 // Terminate after LastMI.
1506 History.push_back(LastMI);
1510 History.push_back(MI);
1512 // Not a DBG_VALUE instruction.
1513 if (!MI->isPosition())
1514 AtBlockEntry = false;
1516 // First known non-DBG_VALUE and non-frame setup location marks
1517 // the beginning of the function body.
1518 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1519 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1520 PrologEndLoc = MI->getDebugLoc();
1522 // Check if the instruction clobbers any registers with debug vars.
1523 for (const MachineOperand &MO : MI->operands()) {
1524 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1526 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1529 const MDNode *Var = LiveUserVar[Reg];
1532 // Reg is now clobbered.
1533 LiveUserVar[Reg] = nullptr;
1535 // Was MD last defined by a DBG_VALUE referring to Reg?
1536 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1537 if (HistI == DbgValues.end())
1539 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1540 if (History.empty())
1542 const MachineInstr *Prev = History.back();
1543 // Sanity-check: Register assignments are terminated at the end of
1545 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1547 // Is the variable still in Reg?
1548 if (!isDbgValueInDefinedReg(Prev) ||
1549 Prev->getOperand(0).getReg() != Reg)
1551 // Var is clobbered. Make sure the next instruction gets a label.
1552 History.push_back(MI);
1559 for (auto &I : DbgValues) {
1560 SmallVectorImpl<const MachineInstr *> &History = I.second;
1561 if (History.empty())
1564 // Make sure the final register assignments are terminated.
1565 const MachineInstr *Prev = History.back();
1566 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1567 const MachineBasicBlock *PrevMBB = Prev->getParent();
1568 MachineBasicBlock::const_iterator LastMI =
1569 PrevMBB->getLastNonDebugInstr();
1570 if (LastMI == PrevMBB->end())
1571 // Drop DBG_VALUE for empty range.
1573 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1574 // Terminate after LastMI.
1575 History.push_back(LastMI);
1578 // Request labels for the full history.
1579 for (const MachineInstr *MI : History) {
1580 if (MI->isDebugValue())
1581 requestLabelBeforeInsn(MI);
1583 requestLabelAfterInsn(MI);
1587 PrevInstLoc = DebugLoc();
1588 PrevLabel = FunctionBeginSym;
1590 // Record beginning of function.
1591 if (!PrologEndLoc.isUnknown()) {
1592 DebugLoc FnStartDL =
1593 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1595 FnStartDL.getLine(), FnStartDL.getCol(),
1596 FnStartDL.getScope(MF->getFunction()->getContext()),
1597 // We'd like to list the prologue as "not statements" but GDB behaves
1598 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1599 DWARF2_FLAG_IS_STMT);
1603 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1604 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1605 DIVariable DV = Var->getVariable();
1606 // Variables with positive arg numbers are parameters.
1607 if (unsigned ArgNum = DV.getArgNumber()) {
1608 // Keep all parameters in order at the start of the variable list to ensure
1609 // function types are correct (no out-of-order parameters)
1611 // This could be improved by only doing it for optimized builds (unoptimized
1612 // builds have the right order to begin with), searching from the back (this
1613 // would catch the unoptimized case quickly), or doing a binary search
1614 // rather than linear search.
1615 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1616 while (I != Vars.end()) {
1617 unsigned CurNum = (*I)->getVariable().getArgNumber();
1618 // A local (non-parameter) variable has been found, insert immediately
1622 // A later indexed parameter has been found, insert immediately before it.
1623 if (CurNum > ArgNum)
1627 Vars.insert(I, Var);
1631 Vars.push_back(Var);
1634 // Gather and emit post-function debug information.
1635 void DwarfDebug::endFunction(const MachineFunction *MF) {
1636 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1637 // though the beginFunction may not be called at all.
1638 // We should handle both cases.
1642 assert(CurFn == MF);
1643 assert(CurFn != nullptr);
1645 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1646 // If we don't have a lexical scope for this function then there will
1647 // be a hole in the range information. Keep note of this by setting the
1648 // previously used section to nullptr.
1649 PrevSection = nullptr;
1655 // Define end label for subprogram.
1656 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1657 // Assumes in correct section after the entry point.
1658 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1660 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1661 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1663 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1664 collectVariableInfo(ProcessedVars);
1666 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1667 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1669 // Construct abstract scopes.
1670 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1671 DISubprogram SP(AScope->getScopeNode());
1672 if (SP.isSubprogram()) {
1673 // Collect info for variables that were optimized out.
1674 DIArray Variables = SP.getVariables();
1675 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1676 DIVariable DV(Variables.getElement(i));
1677 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1679 // Check that DbgVariable for DV wasn't created earlier, when
1680 // findAbstractVariable() was called for inlined instance of DV.
1681 LLVMContext &Ctx = DV->getContext();
1682 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1683 if (AbstractVariables.lookup(CleanDV))
1685 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1686 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1689 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1690 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1693 DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
1694 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1695 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1697 // Add the range of this function to the list of ranges for the CU.
1698 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1699 TheCU.addRange(std::move(Span));
1700 PrevSection = Asm->getCurrentSection();
1704 for (auto &I : ScopeVariables)
1705 DeleteContainerPointers(I.second);
1706 ScopeVariables.clear();
1707 DeleteContainerPointers(CurrentFnArguments);
1708 UserVariables.clear();
1710 AbstractVariables.clear();
1711 LabelsBeforeInsn.clear();
1712 LabelsAfterInsn.clear();
1713 PrevLabel = nullptr;
1717 // Register a source line with debug info. Returns the unique label that was
1718 // emitted and which provides correspondence to the source line list.
1719 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1724 unsigned Discriminator = 0;
1726 DIDescriptor Scope(S);
1728 if (Scope.isCompileUnit()) {
1729 DICompileUnit CU(S);
1730 Fn = CU.getFilename();
1731 Dir = CU.getDirectory();
1732 } else if (Scope.isFile()) {
1734 Fn = F.getFilename();
1735 Dir = F.getDirectory();
1736 } else if (Scope.isSubprogram()) {
1738 Fn = SP.getFilename();
1739 Dir = SP.getDirectory();
1740 } else if (Scope.isLexicalBlockFile()) {
1741 DILexicalBlockFile DBF(S);
1742 Fn = DBF.getFilename();
1743 Dir = DBF.getDirectory();
1744 } else if (Scope.isLexicalBlock()) {
1745 DILexicalBlock DB(S);
1746 Fn = DB.getFilename();
1747 Dir = DB.getDirectory();
1748 Discriminator = DB.getDiscriminator();
1750 llvm_unreachable("Unexpected scope info");
1752 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1753 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1754 .getOrCreateSourceID(Fn, Dir);
1756 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1760 //===----------------------------------------------------------------------===//
1762 //===----------------------------------------------------------------------===//
1764 // Emit initial Dwarf sections with a label at the start of each one.
1765 void DwarfDebug::emitSectionLabels() {
1766 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1768 // Dwarf sections base addresses.
1769 DwarfInfoSectionSym =
1770 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1771 if (useSplitDwarf())
1772 DwarfInfoDWOSectionSym =
1773 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1774 DwarfAbbrevSectionSym =
1775 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1776 if (useSplitDwarf())
1777 DwarfAbbrevDWOSectionSym = emitSectionSym(
1778 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1779 if (GenerateARangeSection)
1780 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1782 DwarfLineSectionSym =
1783 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1784 if (GenerateGnuPubSections) {
1785 DwarfGnuPubNamesSectionSym =
1786 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1787 DwarfGnuPubTypesSectionSym =
1788 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1789 } else if (HasDwarfPubSections) {
1790 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1791 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1794 DwarfStrSectionSym =
1795 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1796 if (useSplitDwarf()) {
1797 DwarfStrDWOSectionSym =
1798 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1799 DwarfAddrSectionSym =
1800 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1801 DwarfDebugLocSectionSym =
1802 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1804 DwarfDebugLocSectionSym =
1805 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1806 DwarfDebugRangeSectionSym =
1807 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1810 // Recursively emits a debug information entry.
1811 void DwarfDebug::emitDIE(DIE &Die) {
1812 // Get the abbreviation for this DIE.
1813 const DIEAbbrev &Abbrev = Die.getAbbrev();
1815 // Emit the code (index) for the abbreviation.
1816 if (Asm->isVerbose())
1817 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1818 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1819 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1820 dwarf::TagString(Abbrev.getTag()));
1821 Asm->EmitULEB128(Abbrev.getNumber());
1823 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1824 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1826 // Emit the DIE attribute values.
1827 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1828 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1829 dwarf::Form Form = AbbrevData[i].getForm();
1830 assert(Form && "Too many attributes for DIE (check abbreviation)");
1832 if (Asm->isVerbose()) {
1833 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1834 if (Attr == dwarf::DW_AT_accessibility)
1835 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1836 cast<DIEInteger>(Values[i])->getValue()));
1839 // Emit an attribute using the defined form.
1840 Values[i]->EmitValue(Asm, Form);
1843 // Emit the DIE children if any.
1844 if (Abbrev.hasChildren()) {
1845 for (auto &Child : Die.getChildren())
1848 Asm->OutStreamer.AddComment("End Of Children Mark");
1853 // Emit the debug info section.
1854 void DwarfDebug::emitDebugInfo() {
1855 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1857 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1860 // Emit the abbreviation section.
1861 void DwarfDebug::emitAbbreviations() {
1862 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1864 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1867 // Emit the last address of the section and the end of the line matrix.
1868 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1869 // Define last address of section.
1870 Asm->OutStreamer.AddComment("Extended Op");
1873 Asm->OutStreamer.AddComment("Op size");
1874 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1875 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1876 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1878 Asm->OutStreamer.AddComment("Section end label");
1880 Asm->OutStreamer.EmitSymbolValue(
1881 Asm->GetTempSymbol("section_end", SectionEnd),
1882 Asm->getDataLayout().getPointerSize());
1884 // Mark end of matrix.
1885 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1891 // Emit visible names into a hashed accelerator table section.
1892 void DwarfDebug::emitAccelNames() {
1893 AccelNames.FinalizeTable(Asm, "Names");
1894 Asm->OutStreamer.SwitchSection(
1895 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1896 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1897 Asm->OutStreamer.EmitLabel(SectionBegin);
1899 // Emit the full data.
1900 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1903 // Emit objective C classes and categories into a hashed accelerator table
1905 void DwarfDebug::emitAccelObjC() {
1906 AccelObjC.FinalizeTable(Asm, "ObjC");
1907 Asm->OutStreamer.SwitchSection(
1908 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1909 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1910 Asm->OutStreamer.EmitLabel(SectionBegin);
1912 // Emit the full data.
1913 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1916 // Emit namespace dies into a hashed accelerator table.
1917 void DwarfDebug::emitAccelNamespaces() {
1918 AccelNamespace.FinalizeTable(Asm, "namespac");
1919 Asm->OutStreamer.SwitchSection(
1920 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1921 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1922 Asm->OutStreamer.EmitLabel(SectionBegin);
1924 // Emit the full data.
1925 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1928 // Emit type dies into a hashed accelerator table.
1929 void DwarfDebug::emitAccelTypes() {
1931 AccelTypes.FinalizeTable(Asm, "types");
1932 Asm->OutStreamer.SwitchSection(
1933 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1934 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1935 Asm->OutStreamer.EmitLabel(SectionBegin);
1937 // Emit the full data.
1938 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1941 // Public name handling.
1942 // The format for the various pubnames:
1944 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1945 // for the DIE that is named.
1947 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1948 // into the CU and the index value is computed according to the type of value
1949 // for the DIE that is named.
1951 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1952 // it's the offset within the debug_info/debug_types dwo section, however, the
1953 // reference in the pubname header doesn't change.
1955 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1956 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1958 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1960 // We could have a specification DIE that has our most of our knowledge,
1961 // look for that now.
1962 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1964 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1965 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1966 Linkage = dwarf::GIEL_EXTERNAL;
1967 } else if (Die->findAttribute(dwarf::DW_AT_external))
1968 Linkage = dwarf::GIEL_EXTERNAL;
1970 switch (Die->getTag()) {
1971 case dwarf::DW_TAG_class_type:
1972 case dwarf::DW_TAG_structure_type:
1973 case dwarf::DW_TAG_union_type:
1974 case dwarf::DW_TAG_enumeration_type:
1975 return dwarf::PubIndexEntryDescriptor(
1976 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1977 ? dwarf::GIEL_STATIC
1978 : dwarf::GIEL_EXTERNAL);
1979 case dwarf::DW_TAG_typedef:
1980 case dwarf::DW_TAG_base_type:
1981 case dwarf::DW_TAG_subrange_type:
1982 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1983 case dwarf::DW_TAG_namespace:
1984 return dwarf::GIEK_TYPE;
1985 case dwarf::DW_TAG_subprogram:
1986 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1987 case dwarf::DW_TAG_constant:
1988 case dwarf::DW_TAG_variable:
1989 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1990 case dwarf::DW_TAG_enumerator:
1991 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1992 dwarf::GIEL_STATIC);
1994 return dwarf::GIEK_NONE;
1998 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2000 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2001 const MCSection *PSec =
2002 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2003 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2005 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2008 void DwarfDebug::emitDebugPubSection(
2009 bool GnuStyle, const MCSection *PSec, StringRef Name,
2010 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2011 for (const auto &NU : CUMap) {
2012 DwarfCompileUnit *TheU = NU.second;
2014 const auto &Globals = (TheU->*Accessor)();
2016 if (Globals.empty())
2019 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2021 unsigned ID = TheU->getUniqueID();
2023 // Start the dwarf pubnames section.
2024 Asm->OutStreamer.SwitchSection(PSec);
2027 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2028 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2029 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2030 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2032 Asm->OutStreamer.EmitLabel(BeginLabel);
2034 Asm->OutStreamer.AddComment("DWARF Version");
2035 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2037 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2038 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2040 Asm->OutStreamer.AddComment("Compilation Unit Length");
2041 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2043 // Emit the pubnames for this compilation unit.
2044 for (const auto &GI : Globals) {
2045 const char *Name = GI.getKeyData();
2046 const DIE *Entity = GI.second;
2048 Asm->OutStreamer.AddComment("DIE offset");
2049 Asm->EmitInt32(Entity->getOffset());
2052 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2053 Asm->OutStreamer.AddComment(
2054 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2055 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2056 Asm->EmitInt8(Desc.toBits());
2059 Asm->OutStreamer.AddComment("External Name");
2060 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2063 Asm->OutStreamer.AddComment("End Mark");
2065 Asm->OutStreamer.EmitLabel(EndLabel);
2069 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2070 const MCSection *PSec =
2071 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2072 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2074 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2077 // Emit visible names into a debug str section.
2078 void DwarfDebug::emitDebugStr() {
2079 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2080 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2083 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2084 const DebugLocEntry &Entry) {
2085 assert(Entry.getValues().size() == 1 &&
2086 "multi-value entries are not supported yet.");
2087 const DebugLocEntry::Value Value = Entry.getValues()[0];
2088 DIVariable DV(Value.getVariable());
2089 if (Value.isInt()) {
2090 DIBasicType BTy(resolve(DV.getType()));
2091 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2092 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2093 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2094 Streamer.EmitSLEB128(Value.getInt());
2096 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2097 Streamer.EmitULEB128(Value.getInt());
2099 } else if (Value.isLocation()) {
2100 MachineLocation Loc = Value.getLoc();
2101 if (!DV.hasComplexAddress())
2103 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2105 // Complex address entry.
2106 unsigned N = DV.getNumAddrElements();
2108 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2109 if (Loc.getOffset()) {
2111 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2112 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2113 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2114 Streamer.EmitSLEB128(DV.getAddrElement(1));
2116 // If first address element is OpPlus then emit
2117 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2118 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2119 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2123 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2126 // Emit remaining complex address elements.
2127 for (; i < N; ++i) {
2128 uint64_t Element = DV.getAddrElement(i);
2129 if (Element == DIBuilder::OpPlus) {
2130 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2131 Streamer.EmitULEB128(DV.getAddrElement(++i));
2132 } else if (Element == DIBuilder::OpDeref) {
2134 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2136 llvm_unreachable("unknown Opcode found in complex address");
2140 // else ... ignore constant fp. There is not any good way to
2141 // to represent them here in dwarf.
2145 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2146 Asm->OutStreamer.AddComment("Loc expr size");
2147 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2148 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2149 Asm->EmitLabelDifference(end, begin, 2);
2150 Asm->OutStreamer.EmitLabel(begin);
2152 APByteStreamer Streamer(*Asm);
2153 emitDebugLocEntry(Streamer, Entry);
2155 Asm->OutStreamer.EmitLabel(end);
2158 // Emit locations into the debug loc section.
2159 void DwarfDebug::emitDebugLoc() {
2160 // Start the dwarf loc section.
2161 Asm->OutStreamer.SwitchSection(
2162 Asm->getObjFileLowering().getDwarfLocSection());
2163 unsigned char Size = Asm->getDataLayout().getPointerSize();
2164 for (const auto &DebugLoc : DotDebugLocEntries) {
2165 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2166 for (const auto &Entry : DebugLoc.List) {
2167 // Set up the range. This range is relative to the entry point of the
2168 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2169 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2170 const DwarfCompileUnit *CU = Entry.getCU();
2171 if (CU->getRanges().size() == 1) {
2172 // Grab the begin symbol from the first range as our base.
2173 const MCSymbol *Base = CU->getRanges()[0].getStart();
2174 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2175 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2177 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2178 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2181 emitDebugLocEntryLocation(Entry);
2183 Asm->OutStreamer.EmitIntValue(0, Size);
2184 Asm->OutStreamer.EmitIntValue(0, Size);
2188 void DwarfDebug::emitDebugLocDWO() {
2189 Asm->OutStreamer.SwitchSection(
2190 Asm->getObjFileLowering().getDwarfLocDWOSection());
2191 for (const auto &DebugLoc : DotDebugLocEntries) {
2192 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2193 for (const auto &Entry : DebugLoc.List) {
2194 // Just always use start_length for now - at least that's one address
2195 // rather than two. We could get fancier and try to, say, reuse an
2196 // address we know we've emitted elsewhere (the start of the function?
2197 // The start of the CU or CU subrange that encloses this range?)
2198 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2199 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2200 Asm->EmitULEB128(idx);
2201 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2203 emitDebugLocEntryLocation(Entry);
2205 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2210 const MCSymbol *Start, *End;
2213 // Emit a debug aranges section, containing a CU lookup for any
2214 // address we can tie back to a CU.
2215 void DwarfDebug::emitDebugARanges() {
2216 // Start the dwarf aranges section.
2217 Asm->OutStreamer.SwitchSection(
2218 Asm->getObjFileLowering().getDwarfARangesSection());
2220 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2224 // Build a list of sections used.
2225 std::vector<const MCSection *> Sections;
2226 for (const auto &it : SectionMap) {
2227 const MCSection *Section = it.first;
2228 Sections.push_back(Section);
2231 // Sort the sections into order.
2232 // This is only done to ensure consistent output order across different runs.
2233 std::sort(Sections.begin(), Sections.end(), SectionSort);
2235 // Build a set of address spans, sorted by CU.
2236 for (const MCSection *Section : Sections) {
2237 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2238 if (List.size() < 2)
2241 // Sort the symbols by offset within the section.
2242 std::sort(List.begin(), List.end(),
2243 [&](const SymbolCU &A, const SymbolCU &B) {
2244 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2245 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2247 // Symbols with no order assigned should be placed at the end.
2248 // (e.g. section end labels)
2256 // If we have no section (e.g. common), just write out
2257 // individual spans for each symbol.
2259 for (const SymbolCU &Cur : List) {
2261 Span.Start = Cur.Sym;
2264 Spans[Cur.CU].push_back(Span);
2267 // Build spans between each label.
2268 const MCSymbol *StartSym = List[0].Sym;
2269 for (size_t n = 1, e = List.size(); n < e; n++) {
2270 const SymbolCU &Prev = List[n - 1];
2271 const SymbolCU &Cur = List[n];
2273 // Try and build the longest span we can within the same CU.
2274 if (Cur.CU != Prev.CU) {
2276 Span.Start = StartSym;
2278 Spans[Prev.CU].push_back(Span);
2285 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2287 // Build a list of CUs used.
2288 std::vector<DwarfCompileUnit *> CUs;
2289 for (const auto &it : Spans) {
2290 DwarfCompileUnit *CU = it.first;
2294 // Sort the CU list (again, to ensure consistent output order).
2295 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2296 return A->getUniqueID() < B->getUniqueID();
2299 // Emit an arange table for each CU we used.
2300 for (DwarfCompileUnit *CU : CUs) {
2301 std::vector<ArangeSpan> &List = Spans[CU];
2303 // Emit size of content not including length itself.
2304 unsigned ContentSize =
2305 sizeof(int16_t) + // DWARF ARange version number
2306 sizeof(int32_t) + // Offset of CU in the .debug_info section
2307 sizeof(int8_t) + // Pointer Size (in bytes)
2308 sizeof(int8_t); // Segment Size (in bytes)
2310 unsigned TupleSize = PtrSize * 2;
2312 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2314 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2316 ContentSize += Padding;
2317 ContentSize += (List.size() + 1) * TupleSize;
2319 // For each compile unit, write the list of spans it covers.
2320 Asm->OutStreamer.AddComment("Length of ARange Set");
2321 Asm->EmitInt32(ContentSize);
2322 Asm->OutStreamer.AddComment("DWARF Arange version number");
2323 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2324 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2325 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2326 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2327 Asm->EmitInt8(PtrSize);
2328 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2331 Asm->OutStreamer.EmitFill(Padding, 0xff);
2333 for (const ArangeSpan &Span : List) {
2334 Asm->EmitLabelReference(Span.Start, PtrSize);
2336 // Calculate the size as being from the span start to it's end.
2338 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2340 // For symbols without an end marker (e.g. common), we
2341 // write a single arange entry containing just that one symbol.
2342 uint64_t Size = SymSize[Span.Start];
2346 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2350 Asm->OutStreamer.AddComment("ARange terminator");
2351 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2352 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2356 // Emit visible names into a debug ranges section.
2357 void DwarfDebug::emitDebugRanges() {
2358 // Start the dwarf ranges section.
2359 Asm->OutStreamer.SwitchSection(
2360 Asm->getObjFileLowering().getDwarfRangesSection());
2362 // Size for our labels.
2363 unsigned char Size = Asm->getDataLayout().getPointerSize();
2365 // Grab the specific ranges for the compile units in the module.
2366 for (const auto &I : CUMap) {
2367 DwarfCompileUnit *TheCU = I.second;
2369 // Iterate over the misc ranges for the compile units in the module.
2370 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2371 // Emit our symbol so we can find the beginning of the range.
2372 Asm->OutStreamer.EmitLabel(List.getSym());
2374 for (const RangeSpan &Range : List.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 if (TheCU->getRanges().size() == 1) {
2380 // Grab the begin symbol from the first range as our base.
2381 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2382 Asm->EmitLabelDifference(Begin, Base, Size);
2383 Asm->EmitLabelDifference(End, Base, Size);
2385 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2386 Asm->OutStreamer.EmitSymbolValue(End, Size);
2390 // And terminate the list with two 0 values.
2391 Asm->OutStreamer.EmitIntValue(0, Size);
2392 Asm->OutStreamer.EmitIntValue(0, Size);
2395 // Now emit a range for the CU itself.
2396 if (TheCU->getRanges().size() > 1) {
2397 Asm->OutStreamer.EmitLabel(
2398 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2399 for (const RangeSpan &Range : TheCU->getRanges()) {
2400 const MCSymbol *Begin = Range.getStart();
2401 const MCSymbol *End = Range.getEnd();
2402 assert(Begin && "Range without a begin symbol?");
2403 assert(End && "Range without an end symbol?");
2404 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2405 Asm->OutStreamer.EmitSymbolValue(End, Size);
2407 // And terminate the list with two 0 values.
2408 Asm->OutStreamer.EmitIntValue(0, Size);
2409 Asm->OutStreamer.EmitIntValue(0, Size);
2414 // DWARF5 Experimental Separate Dwarf emitters.
2416 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2417 std::unique_ptr<DwarfUnit> NewU) {
2418 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2419 U.getCUNode().getSplitDebugFilename());
2421 if (!CompilationDir.empty())
2422 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2424 addGnuPubAttributes(*NewU, Die);
2426 SkeletonHolder.addUnit(std::move(NewU));
2429 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2430 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2431 // DW_AT_addr_base, DW_AT_ranges_base.
2432 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2434 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2435 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2436 DwarfCompileUnit &NewCU = *OwnedUnit;
2437 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2438 DwarfInfoSectionSym);
2440 NewCU.initStmtList(DwarfLineSectionSym);
2442 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2447 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2449 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2450 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2451 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2453 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), CU, Asm, this,
2455 DwarfTypeUnit &NewTU = *OwnedUnit;
2456 NewTU.setTypeSignature(TU.getTypeSignature());
2457 NewTU.setType(nullptr);
2459 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2461 initSkeletonUnit(TU, NewTU.getUnitDie(), std::move(OwnedUnit));
2465 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2466 // compile units that would normally be in debug_info.
2467 void DwarfDebug::emitDebugInfoDWO() {
2468 assert(useSplitDwarf() && "No split dwarf debug info?");
2469 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2470 // emit relocations into the dwo file.
2471 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2474 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2475 // abbreviations for the .debug_info.dwo section.
2476 void DwarfDebug::emitDebugAbbrevDWO() {
2477 assert(useSplitDwarf() && "No split dwarf?");
2478 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2481 void DwarfDebug::emitDebugLineDWO() {
2482 assert(useSplitDwarf() && "No split dwarf?");
2483 Asm->OutStreamer.SwitchSection(
2484 Asm->getObjFileLowering().getDwarfLineDWOSection());
2485 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2488 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2489 // string section and is identical in format to traditional .debug_str
2491 void DwarfDebug::emitDebugStrDWO() {
2492 assert(useSplitDwarf() && "No split dwarf?");
2493 const MCSection *OffSec =
2494 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2495 const MCSymbol *StrSym = DwarfStrSectionSym;
2496 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2500 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2501 if (!useSplitDwarf())
2504 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2505 return &SplitTypeUnitFileTable;
2508 static uint64_t makeTypeSignature(StringRef Identifier) {
2510 Hash.update(Identifier);
2511 // ... take the least significant 8 bytes and return those. Our MD5
2512 // implementation always returns its results in little endian, swap bytes
2514 MD5::MD5Result Result;
2516 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2519 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2520 StringRef Identifier, DIE &RefDie,
2521 DICompositeType CTy) {
2522 // Fast path if we're building some type units and one has already used the
2523 // address pool we know we're going to throw away all this work anyway, so
2524 // don't bother building dependent types.
2525 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2528 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2530 CU.addDIETypeSignature(RefDie, *TU);
2534 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2535 AddrPool.resetUsedFlag();
2538 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), CU, Asm, this,
2539 &InfoHolder, getDwoLineTable(CU));
2540 DwarfTypeUnit &NewTU = *OwnedUnit;
2541 DIE &UnitDie = NewTU.getUnitDie();
2543 TypeUnitsUnderConstruction.push_back(
2544 std::make_pair(std::move(OwnedUnit), CTy));
2546 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2549 uint64_t Signature = makeTypeSignature(Identifier);
2550 NewTU.setTypeSignature(Signature);
2552 if (!useSplitDwarf())
2553 CU.applyStmtList(UnitDie);
2557 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2558 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2560 NewTU.setType(NewTU.createTypeDIE(CTy));
2563 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2564 TypeUnitsUnderConstruction.clear();
2566 // Types referencing entries in the address table cannot be placed in type
2568 if (AddrPool.hasBeenUsed()) {
2570 // Remove all the types built while building this type.
2571 // This is pessimistic as some of these types might not be dependent on
2572 // the type that used an address.
2573 for (const auto &TU : TypeUnitsToAdd)
2574 DwarfTypeUnits.erase(TU.second);
2576 // Construct this type in the CU directly.
2577 // This is inefficient because all the dependent types will be rebuilt
2578 // from scratch, including building them in type units, discovering that
2579 // they depend on addresses, throwing them out and rebuilding them.
2580 CU.constructTypeDIE(RefDie, CTy);
2584 // If the type wasn't dependent on fission addresses, finish adding the type
2585 // and all its dependent types.
2586 for (auto &TU : TypeUnitsToAdd) {
2587 if (useSplitDwarf())
2588 TU.first->setSkeleton(constructSkeletonTU(*TU.first));
2589 InfoHolder.addUnit(std::move(TU.first));
2592 CU.addDIETypeSignature(RefDie, NewTU);
2595 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2596 MCSymbol *Begin, MCSymbol *End) {
2597 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2598 if (DwarfVersion < 4)
2599 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2601 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2604 // Accelerator table mutators - add each name along with its companion
2605 // DIE to the proper table while ensuring that the name that we're going
2606 // to reference is in the string table. We do this since the names we
2607 // add may not only be identical to the names in the DIE.
2608 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2609 if (!useDwarfAccelTables())
2611 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2615 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2616 if (!useDwarfAccelTables())
2618 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2622 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2623 if (!useDwarfAccelTables())
2625 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2629 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2630 if (!useDwarfAccelTables())
2632 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),