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 // Switch to the specified MCSection and emit an assembler
222 // temporary label to it if SymbolStem is specified.
223 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
224 const char *SymbolStem = nullptr) {
225 Asm->OutStreamer.SwitchSection(Section);
229 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
230 Asm->OutStreamer.EmitLabel(TmpSym);
234 static bool isObjCClass(StringRef Name) {
235 return Name.startswith("+") || Name.startswith("-");
238 static bool hasObjCCategory(StringRef Name) {
239 if (!isObjCClass(Name))
242 return Name.find(") ") != StringRef::npos;
245 static void getObjCClassCategory(StringRef In, StringRef &Class,
246 StringRef &Category) {
247 if (!hasObjCCategory(In)) {
248 Class = In.slice(In.find('[') + 1, In.find(' '));
253 Class = In.slice(In.find('[') + 1, In.find('('));
254 Category = In.slice(In.find('[') + 1, In.find(' '));
258 static StringRef getObjCMethodName(StringRef In) {
259 return In.slice(In.find(' ') + 1, In.find(']'));
262 // Helper for sorting sections into a stable output order.
263 static bool SectionSort(const MCSection *A, const MCSection *B) {
264 std::string LA = (A ? A->getLabelBeginName() : "");
265 std::string LB = (B ? B->getLabelBeginName() : "");
269 // Add the various names to the Dwarf accelerator table names.
270 // TODO: Determine whether or not we should add names for programs
271 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
272 // is only slightly different than the lookup of non-standard ObjC names.
273 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
274 if (!SP.isDefinition())
276 addAccelName(SP.getName(), Die);
278 // If the linkage name is different than the name, go ahead and output
279 // that as well into the name table.
280 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
281 addAccelName(SP.getLinkageName(), Die);
283 // If this is an Objective-C selector name add it to the ObjC accelerator
285 if (isObjCClass(SP.getName())) {
286 StringRef Class, Category;
287 getObjCClassCategory(SP.getName(), Class, Category);
288 addAccelObjC(Class, Die);
290 addAccelObjC(Category, Die);
291 // Also add the base method name to the name table.
292 addAccelName(getObjCMethodName(SP.getName()), Die);
296 /// isSubprogramContext - Return true if Context is either a subprogram
297 /// or another context nested inside a subprogram.
298 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
301 DIDescriptor D(Context);
302 if (D.isSubprogram())
305 return isSubprogramContext(resolve(DIType(Context).getContext()));
309 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
310 // and DW_AT_high_pc attributes. If there are global variables in this
311 // scope then create and insert DIEs for these variables.
312 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
314 DIE *SPDie = SPCU.getDIE(SP);
316 assert(SPDie && "Unable to find subprogram DIE!");
318 // If we're updating an abstract DIE, then we will be adding the children and
319 // object pointer later on. But what we don't want to do is process the
320 // concrete DIE twice.
321 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
322 // Pick up abstract subprogram DIE.
323 SPDie = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
324 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
326 DISubprogram SPDecl = SP.getFunctionDeclaration();
327 if (!SPDecl.isSubprogram()) {
328 // There is not any need to generate specification DIE for a function
329 // defined at compile unit level. If a function is defined inside another
330 // function then gdb prefers the definition at top level and but does not
331 // expect specification DIE in parent function. So avoid creating
332 // specification DIE for a function defined inside a function.
333 DIScope SPContext = resolve(SP.getContext());
334 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
335 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
336 SPCU.addFlag(*SPDie, dwarf::DW_AT_declaration);
339 DICompositeType SPTy = SP.getType();
340 DIArray Args = SPTy.getTypeArray();
341 uint16_t SPTag = SPTy.getTag();
342 if (SPTag == dwarf::DW_TAG_subroutine_type)
343 SPCU.constructSubprogramArguments(*SPDie, Args);
344 DIE *SPDeclDie = SPDie;
346 &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
347 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_specification, *SPDeclDie);
352 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
354 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
355 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
356 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
358 // Add name to the name table, we do this here because we're guaranteed
359 // to have concrete versions of our DW_TAG_subprogram nodes.
360 addSubprogramNames(SP, *SPDie);
365 /// Check whether we should create a DIE for the given Scope, return true
366 /// if we don't create a DIE (the corresponding DIE is null).
367 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
368 if (Scope->isAbstractScope())
371 // We don't create a DIE if there is no Range.
372 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
376 if (Ranges.size() > 1)
379 // We don't create a DIE if we have a single Range and the end label
381 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
382 MCSymbol *End = getLabelAfterInsn(RI->second);
386 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
387 dwarf::Attribute A, const MCSymbol *L,
388 const MCSymbol *Sec) {
389 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
390 U.addSectionLabel(D, A, L);
392 U.addSectionDelta(D, A, L, Sec);
395 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
396 const SmallVectorImpl<InsnRange> &Range) {
397 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
398 // emitting it appropriately.
399 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
401 // Under fission, ranges are specified by constant offsets relative to the
402 // CU's DW_AT_GNU_ranges_base.
404 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
405 DwarfDebugRangeSectionSym);
407 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
408 DwarfDebugRangeSectionSym);
410 RangeSpanList List(RangeSym);
411 for (const InsnRange &R : Range) {
412 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
413 List.addRange(std::move(Span));
416 // Add the range list to the set of ranges to be emitted.
417 TheCU.addRangeList(std::move(List));
420 // Construct new DW_TAG_lexical_block for this scope and attach
421 // DW_AT_low_pc/DW_AT_high_pc labels.
423 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
424 LexicalScope *Scope) {
425 if (isLexicalScopeDIENull(Scope))
428 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
429 if (Scope->isAbstractScope())
432 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
434 // If we have multiple ranges, emit them into the range section.
435 if (ScopeRanges.size() > 1) {
436 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
440 // Construct the address range for this DIE.
441 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
442 MCSymbol *Start = getLabelBeforeInsn(RI->first);
443 MCSymbol *End = getLabelAfterInsn(RI->second);
444 assert(End && "End label should not be null!");
446 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
447 assert(End->isDefined() && "Invalid end label for an inlined scope!");
449 attachLowHighPC(TheCU, *ScopeDIE, Start, End);
454 // This scope represents inlined body of a function. Construct DIE to
455 // represent this concrete inlined copy of the function.
457 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 auto ScopeDIE = make_unique<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 (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
543 Children.push_back(std::move(Nested));
544 return ObjectPointer;
547 DIE *DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
548 LexicalScope *Scope) {
549 assert(Scope && Scope->getScopeNode());
551 DIScope DS(Scope->getScopeNode());
553 assert(!Scope->getInlinedAt());
554 assert(DS.isSubprogram());
556 ProcessedSPNodes.insert(DS);
558 SmallVector<std::unique_ptr<DIE>, 8> Children;
561 if (Scope->isAbstractScope()) {
562 ScopeDIE = TheCU.getDIE(DS);
563 // Note down abstract DIE.
565 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
567 assert(Children.empty() &&
568 "We create children only when the scope DIE is not null.");
572 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
574 // We create children when the scope DIE is not null.
575 if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
576 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
579 for (auto &I : Children)
580 ScopeDIE->addChild(std::move(I));
585 // Construct a DIE for this scope.
586 std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
587 LexicalScope *Scope) {
588 if (!Scope || !Scope->getScopeNode())
591 DIScope DS(Scope->getScopeNode());
593 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
594 "Only handle inlined subprograms here, use "
595 "constructSubprogramScopeDIE for non-inlined "
598 SmallVector<std::unique_ptr<DIE>, 8> Children;
600 // We try to create the scope DIE first, then the children DIEs. This will
601 // avoid creating un-used children then removing them later when we find out
602 // the scope DIE is null.
603 std::unique_ptr<DIE> ScopeDIE;
604 if (Scope->getInlinedAt()) {
605 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
608 // We create children when the scope DIE is not null.
609 createScopeChildrenDIE(TheCU, Scope, Children);
611 // Early exit when we know the scope DIE is going to be null.
612 if (isLexicalScopeDIENull(Scope))
615 // We create children here when we know the scope DIE is not going to be
616 // null and the children will be added to the scope DIE.
617 createScopeChildrenDIE(TheCU, Scope, Children);
619 // There is no need to emit empty lexical block DIE.
620 std::pair<ImportedEntityMap::const_iterator,
621 ImportedEntityMap::const_iterator> Range =
622 std::equal_range(ScopesWithImportedEntities.begin(),
623 ScopesWithImportedEntities.end(),
624 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
626 if (Children.empty() && Range.first == Range.second)
628 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
629 assert(ScopeDIE && "Scope DIE should not be null.");
630 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
632 constructImportedEntityDIE(TheCU, i->second, *ScopeDIE);
636 for (auto &I : Children)
637 ScopeDIE->addChild(std::move(I));
642 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
643 if (!GenerateGnuPubSections)
646 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
649 // Create new DwarfCompileUnit for the given metadata node with tag
650 // DW_TAG_compile_unit.
651 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
652 StringRef FN = DIUnit.getFilename();
653 CompilationDir = DIUnit.getDirectory();
655 auto OwnedUnit = make_unique<DwarfCompileUnit>(
656 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
657 DwarfCompileUnit &NewCU = *OwnedUnit;
658 DIE &Die = NewCU.getUnitDie();
659 InfoHolder.addUnit(std::move(OwnedUnit));
661 // LTO with assembly output shares a single line table amongst multiple CUs.
662 // To avoid the compilation directory being ambiguous, let the line table
663 // explicitly describe the directory of all files, never relying on the
664 // compilation directory.
665 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
666 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
667 NewCU.getUniqueID(), CompilationDir);
669 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
670 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
671 DIUnit.getLanguage());
672 NewCU.addString(Die, dwarf::DW_AT_name, FN);
674 if (!useSplitDwarf()) {
675 NewCU.initStmtList(DwarfLineSectionSym);
677 // If we're using split dwarf the compilation dir is going to be in the
678 // skeleton CU and so we don't need to duplicate it here.
679 if (!CompilationDir.empty())
680 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
682 addGnuPubAttributes(NewCU, Die);
685 if (DIUnit.isOptimized())
686 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
688 StringRef Flags = DIUnit.getFlags();
690 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
692 if (unsigned RVer = DIUnit.getRunTimeVersion())
693 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
694 dwarf::DW_FORM_data1, RVer);
699 if (useSplitDwarf()) {
700 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
701 DwarfInfoDWOSectionSym);
702 NewCU.setSkeleton(constructSkeletonCU(NewCU));
704 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
705 DwarfInfoSectionSym);
707 CUMap.insert(std::make_pair(DIUnit, &NewCU));
708 CUDieMap.insert(std::make_pair(&Die, &NewCU));
712 // Construct subprogram DIE.
713 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
715 // FIXME: We should only call this routine once, however, during LTO if a
716 // program is defined in multiple CUs we could end up calling it out of
717 // beginModule as we walk the CUs.
719 DwarfCompileUnit *&CURef = SPMap[N];
725 if (!SP.isDefinition())
726 // This is a method declaration which will be handled while constructing
730 DIE &SubprogramDie = *TheCU.getOrCreateSubprogramDIE(SP);
732 // Expose as a global name.
733 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
736 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
738 DIImportedEntity Module(N);
739 assert(Module.Verify());
740 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
741 constructImportedEntityDIE(TheCU, Module, *D);
744 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
745 const MDNode *N, DIE &Context) {
746 DIImportedEntity Module(N);
747 assert(Module.Verify());
748 return constructImportedEntityDIE(TheCU, Module, Context);
751 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
752 const DIImportedEntity &Module,
754 assert(Module.Verify() &&
755 "Use one of the MDNode * overloads to handle invalid metadata");
756 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), Context, Module);
758 DIDescriptor Entity = resolve(Module.getEntity());
759 if (Entity.isNameSpace())
760 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
761 else if (Entity.isSubprogram())
762 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
763 else if (Entity.isType())
764 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
766 EntityDie = TheCU.getDIE(Entity);
767 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
768 Module.getContext().getFilename(),
769 Module.getContext().getDirectory());
770 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
771 StringRef Name = Module.getName();
773 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
776 // Emit all Dwarf sections that should come prior to the content. Create
777 // global DIEs and emit initial debug info sections. This is invoked by
778 // the target AsmPrinter.
779 void DwarfDebug::beginModule() {
780 if (DisableDebugInfoPrinting)
783 const Module *M = MMI->getModule();
785 // If module has named metadata anchors then use them, otherwise scan the
786 // module using debug info finder to collect debug info.
787 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
790 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
792 // Emit initial sections so we can reference labels later.
795 SingleCU = CU_Nodes->getNumOperands() == 1;
797 for (MDNode *N : CU_Nodes->operands()) {
798 DICompileUnit CUNode(N);
799 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
800 DIArray ImportedEntities = CUNode.getImportedEntities();
801 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
802 ScopesWithImportedEntities.push_back(std::make_pair(
803 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
804 ImportedEntities.getElement(i)));
805 std::sort(ScopesWithImportedEntities.begin(),
806 ScopesWithImportedEntities.end(), less_first());
807 DIArray GVs = CUNode.getGlobalVariables();
808 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
809 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
810 DIArray SPs = CUNode.getSubprograms();
811 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
812 constructSubprogramDIE(CU, SPs.getElement(i));
813 DIArray EnumTypes = CUNode.getEnumTypes();
814 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
815 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
816 DIArray RetainedTypes = CUNode.getRetainedTypes();
817 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
818 DIType Ty(RetainedTypes.getElement(i));
819 // The retained types array by design contains pointers to
820 // MDNodes rather than DIRefs. Unique them here.
821 DIType UniqueTy(resolve(Ty.getRef()));
822 CU.getOrCreateTypeDIE(UniqueTy);
824 // Emit imported_modules last so that the relevant context is already
826 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
827 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
830 // Tell MMI that we have debug info.
831 MMI->setDebugInfoAvailability(true);
833 // Prime section data.
834 SectionMap[Asm->getObjFileLowering().getTextSection()];
837 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
838 void DwarfDebug::computeInlinedDIEs() {
839 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
840 for (DIE *ISP : InlinedSubprogramDIEs)
841 FirstCU->addUInt(*ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
843 for (const auto &AI : AbstractSPDies) {
844 DIE &ISP = *AI.second;
845 if (InlinedSubprogramDIEs.count(&ISP))
847 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
851 // Collect info for variables that were optimized out.
852 void DwarfDebug::collectDeadVariables() {
853 const Module *M = MMI->getModule();
855 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
856 for (MDNode *N : CU_Nodes->operands()) {
857 DICompileUnit TheCU(N);
858 DIArray Subprograms = TheCU.getSubprograms();
859 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
860 DISubprogram SP(Subprograms.getElement(i));
861 if (ProcessedSPNodes.count(SP) != 0)
863 if (!SP.isSubprogram())
865 if (!SP.isDefinition())
867 DIArray Variables = SP.getVariables();
868 if (Variables.getNumElements() == 0)
871 // Construct subprogram DIE and add variables DIEs.
872 DwarfCompileUnit *SPCU =
873 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
874 assert(SPCU && "Unable to find Compile Unit!");
875 // FIXME: See the comment in constructSubprogramDIE about duplicate
877 constructSubprogramDIE(*SPCU, SP);
878 DIE *SPDIE = SPCU->getDIE(SP);
879 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
880 DIVariable DV(Variables.getElement(vi));
881 if (!DV.isVariable())
883 DbgVariable NewVar(DV, nullptr, this);
884 SPDIE->addChild(SPCU->constructVariableDIE(NewVar, false));
891 void DwarfDebug::finalizeModuleInfo() {
892 // Collect info for variables that were optimized out.
893 collectDeadVariables();
895 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
896 computeInlinedDIEs();
898 // Handle anything that needs to be done on a per-unit basis after
899 // all other generation.
900 for (const auto &TheU : getUnits()) {
901 // Emit DW_AT_containing_type attribute to connect types with their
902 // vtable holding type.
903 TheU->constructContainingTypeDIEs();
905 // Add CU specific attributes if we need to add any.
906 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
907 // If we're splitting the dwarf out now that we've got the entire
908 // CU then add the dwo id to it.
909 DwarfCompileUnit *SkCU =
910 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
911 if (useSplitDwarf()) {
912 // Emit a unique identifier for this CU.
913 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
914 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
915 dwarf::DW_FORM_data8, ID);
916 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
917 dwarf::DW_FORM_data8, ID);
919 // We don't keep track of which addresses are used in which CU so this
920 // is a bit pessimistic under LTO.
921 if (!AddrPool.isEmpty())
922 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
923 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
924 DwarfAddrSectionSym);
925 if (!TheU->getRangeLists().empty())
926 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
927 dwarf::DW_AT_GNU_ranges_base,
928 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
931 // If we have code split among multiple sections or non-contiguous
932 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
933 // remain in the .o file, otherwise add a DW_AT_low_pc.
934 // FIXME: We should use ranges allow reordering of code ala
935 // .subsections_via_symbols in mach-o. This would mean turning on
936 // ranges for all subprogram DIEs for mach-o.
937 DwarfCompileUnit &U =
938 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
939 unsigned NumRanges = TheU->getRanges().size();
942 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
943 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
944 DwarfDebugRangeSectionSym);
946 // A DW_AT_low_pc attribute may also be specified in combination with
947 // DW_AT_ranges to specify the default base address for use in
948 // location lists (see Section 2.6.2) and range lists (see Section
950 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
953 RangeSpan &Range = TheU->getRanges().back();
954 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
956 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
963 // Compute DIE offsets and sizes.
964 InfoHolder.computeSizeAndOffsets();
966 SkeletonHolder.computeSizeAndOffsets();
969 void DwarfDebug::endSections() {
970 // Filter labels by section.
971 for (const SymbolCU &SCU : ArangeLabels) {
972 if (SCU.Sym->isInSection()) {
973 // Make a note of this symbol and it's section.
974 const MCSection *Section = &SCU.Sym->getSection();
975 if (!Section->getKind().isMetadata())
976 SectionMap[Section].push_back(SCU);
978 // Some symbols (e.g. common/bss on mach-o) can have no section but still
979 // appear in the output. This sucks as we rely on sections to build
980 // arange spans. We can do it without, but it's icky.
981 SectionMap[nullptr].push_back(SCU);
985 // Build a list of sections used.
986 std::vector<const MCSection *> Sections;
987 for (const auto &it : SectionMap) {
988 const MCSection *Section = it.first;
989 Sections.push_back(Section);
992 // Sort the sections into order.
993 // This is only done to ensure consistent output order across different runs.
994 std::sort(Sections.begin(), Sections.end(), SectionSort);
996 // Add terminating symbols for each section.
997 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
998 const MCSection *Section = Sections[ID];
999 MCSymbol *Sym = nullptr;
1002 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1003 // if we know the section name up-front. For user-created sections, the
1004 // resulting label may not be valid to use as a label. (section names can
1005 // use a greater set of characters on some systems)
1006 Sym = Asm->GetTempSymbol("debug_end", ID);
1007 Asm->OutStreamer.SwitchSection(Section);
1008 Asm->OutStreamer.EmitLabel(Sym);
1011 // Insert a final terminator.
1012 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1016 // Emit all Dwarf sections that should come after the content.
1017 void DwarfDebug::endModule() {
1018 assert(CurFn == nullptr);
1019 assert(CurMI == nullptr);
1024 // End any existing sections.
1025 // TODO: Does this need to happen?
1028 // Finalize the debug info for the module.
1029 finalizeModuleInfo();
1033 // Emit all the DIEs into a debug info section.
1036 // Corresponding abbreviations into a abbrev section.
1037 emitAbbreviations();
1039 // Emit info into a debug aranges section.
1040 if (GenerateARangeSection)
1043 // Emit info into a debug ranges section.
1046 if (useSplitDwarf()) {
1049 emitDebugAbbrevDWO();
1051 // Emit DWO addresses.
1052 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1055 // Emit info into a debug loc section.
1058 // Emit info into the dwarf accelerator table sections.
1059 if (useDwarfAccelTables()) {
1062 emitAccelNamespaces();
1066 // Emit the pubnames and pubtypes sections if requested.
1067 if (HasDwarfPubSections) {
1068 emitDebugPubNames(GenerateGnuPubSections);
1069 emitDebugPubTypes(GenerateGnuPubSections);
1075 // Reset these for the next Module if we have one.
1079 // Find abstract variable, if any, associated with Var.
1080 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1081 DebugLoc ScopeLoc) {
1082 LLVMContext &Ctx = DV->getContext();
1083 // More then one inlined variable corresponds to one abstract variable.
1084 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1085 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1087 return AbsDbgVariable;
1089 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1093 AbsDbgVariable = new DbgVariable(Var, nullptr, this);
1094 addScopeVariable(Scope, AbsDbgVariable);
1095 AbstractVariables[Var] = AbsDbgVariable;
1096 return AbsDbgVariable;
1099 // If Var is a current function argument then add it to CurrentFnArguments list.
1100 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1101 if (!LScopes.isCurrentFunctionScope(Scope))
1103 DIVariable DV = Var->getVariable();
1104 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1106 unsigned ArgNo = DV.getArgNumber();
1110 size_t Size = CurrentFnArguments.size();
1112 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1113 // llvm::Function argument size is not good indicator of how many
1114 // arguments does the function have at source level.
1116 CurrentFnArguments.resize(ArgNo * 2);
1117 CurrentFnArguments[ArgNo - 1] = Var;
1121 // Collect variable information from side table maintained by MMI.
1122 void DwarfDebug::collectVariableInfoFromMMITable(
1123 SmallPtrSet<const MDNode *, 16> &Processed) {
1124 for (const auto &VI : MMI->getVariableDbgInfo()) {
1127 Processed.insert(VI.Var);
1128 DIVariable DV(VI.Var);
1129 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1131 // If variable scope is not found then skip this variable.
1135 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1136 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1137 RegVar->setFrameIndex(VI.Slot);
1138 if (!addCurrentFnArgument(RegVar, Scope))
1139 addScopeVariable(Scope, RegVar);
1141 AbsDbgVariable->setFrameIndex(VI.Slot);
1145 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1147 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1148 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1149 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1150 MI->getOperand(0).getReg() &&
1151 (MI->getOperand(1).isImm() ||
1152 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1155 // Get .debug_loc entry for the instruction range starting at MI.
1156 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1157 const MDNode *Var = MI->getDebugVariable();
1159 assert(MI->getNumOperands() == 3);
1160 if (MI->getOperand(0).isReg()) {
1161 MachineLocation MLoc;
1162 // If the second operand is an immediate, this is a
1163 // register-indirect address.
1164 if (!MI->getOperand(1).isImm())
1165 MLoc.set(MI->getOperand(0).getReg());
1167 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1168 return DebugLocEntry::Value(Var, MLoc);
1170 if (MI->getOperand(0).isImm())
1171 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1172 if (MI->getOperand(0).isFPImm())
1173 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1174 if (MI->getOperand(0).isCImm())
1175 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1177 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1180 // Find variables for each lexical scope.
1182 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1183 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1184 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1186 // Grab the variable info that was squirreled away in the MMI side-table.
1187 collectVariableInfoFromMMITable(Processed);
1189 for (const MDNode *Var : UserVariables) {
1190 if (Processed.count(Var))
1193 // History contains relevant DBG_VALUE instructions for Var and instructions
1195 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1196 if (History.empty())
1198 const MachineInstr *MInsn = History.front();
1201 LexicalScope *Scope = nullptr;
1202 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1203 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1204 Scope = LScopes.getCurrentFunctionScope();
1205 else if (MDNode *IA = DV.getInlinedAt())
1206 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1208 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1209 // If variable scope is not found then skip this variable.
1213 Processed.insert(DV);
1214 assert(MInsn->isDebugValue() && "History must begin with debug value");
1215 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1216 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1217 if (!addCurrentFnArgument(RegVar, Scope))
1218 addScopeVariable(Scope, RegVar);
1220 AbsVar->setMInsn(MInsn);
1222 // Simplify ranges that are fully coalesced.
1223 if (History.size() <= 1 ||
1224 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1225 RegVar->setMInsn(MInsn);
1229 // Handle multiple DBG_VALUE instructions describing one variable.
1230 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1232 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1233 DebugLocList &LocList = DotDebugLocEntries.back();
1235 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1236 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1237 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1238 HI = History.begin(),
1241 const MachineInstr *Begin = *HI;
1242 assert(Begin->isDebugValue() && "Invalid History entry");
1244 // Check if DBG_VALUE is truncating a range.
1245 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1246 !Begin->getOperand(0).getReg())
1249 // Compute the range for a register location.
1250 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1251 const MCSymbol *SLabel = nullptr;
1254 // If Begin is the last instruction in History then its value is valid
1255 // until the end of the function.
1256 SLabel = FunctionEndSym;
1258 const MachineInstr *End = HI[1];
1259 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1260 << "\t" << *Begin << "\t" << *End << "\n");
1261 if (End->isDebugValue())
1262 SLabel = getLabelBeforeInsn(End);
1264 // End is a normal instruction clobbering the range.
1265 SLabel = getLabelAfterInsn(End);
1266 assert(SLabel && "Forgot label after clobber instruction");
1271 // The value is valid until the next DBG_VALUE or clobber.
1272 DebugLocEntry Loc(FLabel, SLabel, getDebugLocValue(Begin), TheCU);
1273 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1274 DebugLoc.push_back(std::move(Loc));
1278 // Collect info for variables that were optimized out.
1279 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1280 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1281 DIVariable DV(Variables.getElement(i));
1282 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1284 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1285 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1289 // Return Label preceding the instruction.
1290 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1291 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1292 assert(Label && "Didn't insert label before instruction");
1296 // Return Label immediately following the instruction.
1297 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1298 return LabelsAfterInsn.lookup(MI);
1301 // Process beginning of an instruction.
1302 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1303 assert(CurMI == nullptr);
1305 // Check if source location changes, but ignore DBG_VALUE locations.
1306 if (!MI->isDebugValue()) {
1307 DebugLoc DL = MI->getDebugLoc();
1308 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1311 if (DL == PrologEndLoc) {
1312 Flags |= DWARF2_FLAG_PROLOGUE_END;
1313 PrologEndLoc = DebugLoc();
1315 if (PrologEndLoc.isUnknown())
1316 Flags |= DWARF2_FLAG_IS_STMT;
1318 if (!DL.isUnknown()) {
1319 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1320 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1322 recordSourceLine(0, 0, nullptr, 0);
1326 // Insert labels where requested.
1327 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1328 LabelsBeforeInsn.find(MI);
1331 if (I == LabelsBeforeInsn.end())
1334 // Label already assigned.
1339 PrevLabel = MMI->getContext().CreateTempSymbol();
1340 Asm->OutStreamer.EmitLabel(PrevLabel);
1342 I->second = PrevLabel;
1345 // Process end of an instruction.
1346 void DwarfDebug::endInstruction() {
1347 assert(CurMI != nullptr);
1348 // Don't create a new label after DBG_VALUE instructions.
1349 // They don't generate code.
1350 if (!CurMI->isDebugValue())
1351 PrevLabel = nullptr;
1353 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1354 LabelsAfterInsn.find(CurMI);
1358 if (I == LabelsAfterInsn.end())
1361 // Label already assigned.
1365 // We need a label after this instruction.
1367 PrevLabel = MMI->getContext().CreateTempSymbol();
1368 Asm->OutStreamer.EmitLabel(PrevLabel);
1370 I->second = PrevLabel;
1373 // Each LexicalScope has first instruction and last instruction to mark
1374 // beginning and end of a scope respectively. Create an inverse map that list
1375 // scopes starts (and ends) with an instruction. One instruction may start (or
1376 // end) multiple scopes. Ignore scopes that are not reachable.
1377 void DwarfDebug::identifyScopeMarkers() {
1378 SmallVector<LexicalScope *, 4> WorkList;
1379 WorkList.push_back(LScopes.getCurrentFunctionScope());
1380 while (!WorkList.empty()) {
1381 LexicalScope *S = WorkList.pop_back_val();
1383 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1384 if (!Children.empty())
1385 WorkList.append(Children.begin(), Children.end());
1387 if (S->isAbstractScope())
1390 for (const InsnRange &R : S->getRanges()) {
1391 assert(R.first && "InsnRange does not have first instruction!");
1392 assert(R.second && "InsnRange does not have second instruction!");
1393 requestLabelBeforeInsn(R.first);
1394 requestLabelAfterInsn(R.second);
1399 // Gather pre-function debug information. Assumes being called immediately
1400 // after the function entry point has been emitted.
1401 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1404 // If there's no debug info for the function we're not going to do anything.
1405 if (!MMI->hasDebugInfo())
1408 // Grab the lexical scopes for the function, if we don't have any of those
1409 // then we're not going to be able to do anything.
1410 LScopes.initialize(*MF);
1411 if (LScopes.empty())
1414 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1416 // Make sure that each lexical scope will have a begin/end label.
1417 identifyScopeMarkers();
1419 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1420 // belongs to so that we add to the correct per-cu line table in the
1422 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1423 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1424 assert(TheCU && "Unable to find compile unit!");
1425 if (Asm->OutStreamer.hasRawTextSupport())
1426 // Use a single line table if we are generating assembly.
1427 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1429 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1431 // Emit a label for the function so that we have a beginning address.
1432 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1433 // Assumes in correct section after the entry point.
1434 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1436 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1437 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1438 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1440 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1442 bool AtBlockEntry = true;
1443 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1445 const MachineInstr *MI = II;
1447 if (MI->isDebugValue()) {
1448 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1450 // Keep track of user variables.
1451 const MDNode *Var = MI->getDebugVariable();
1453 // Variable is in a register, we need to check for clobbers.
1454 if (isDbgValueInDefinedReg(MI))
1455 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1457 // Check the history of this variable.
1458 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1459 if (History.empty()) {
1460 UserVariables.push_back(Var);
1461 // The first mention of a function argument gets the FunctionBeginSym
1462 // label, so arguments are visible when breaking at function entry.
1464 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1465 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1466 LabelsBeforeInsn[MI] = FunctionBeginSym;
1468 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1469 const MachineInstr *Prev = History.back();
1470 if (Prev->isDebugValue()) {
1471 // Coalesce identical entries at the end of History.
1472 if (History.size() >= 2 &&
1473 Prev->isIdenticalTo(History[History.size() - 2])) {
1474 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1475 << "\t" << *Prev << "\t"
1476 << *History[History.size() - 2] << "\n");
1480 // Terminate old register assignments that don't reach MI;
1481 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1482 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1483 isDbgValueInDefinedReg(Prev)) {
1484 // Previous register assignment needs to terminate at the end of
1486 MachineBasicBlock::const_iterator LastMI =
1487 PrevMBB->getLastNonDebugInstr();
1488 if (LastMI == PrevMBB->end()) {
1489 // Drop DBG_VALUE for empty range.
1490 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1491 << "\t" << *Prev << "\n");
1493 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1494 // Terminate after LastMI.
1495 History.push_back(LastMI);
1499 History.push_back(MI);
1501 // Not a DBG_VALUE instruction.
1502 if (!MI->isPosition())
1503 AtBlockEntry = false;
1505 // First known non-DBG_VALUE and non-frame setup location marks
1506 // the beginning of the function body.
1507 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1508 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1509 PrologEndLoc = MI->getDebugLoc();
1511 // Check if the instruction clobbers any registers with debug vars.
1512 for (const MachineOperand &MO : MI->operands()) {
1513 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1515 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1518 const MDNode *Var = LiveUserVar[Reg];
1521 // Reg is now clobbered.
1522 LiveUserVar[Reg] = nullptr;
1524 // Was MD last defined by a DBG_VALUE referring to Reg?
1525 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1526 if (HistI == DbgValues.end())
1528 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1529 if (History.empty())
1531 const MachineInstr *Prev = History.back();
1532 // Sanity-check: Register assignments are terminated at the end of
1534 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1536 // Is the variable still in Reg?
1537 if (!isDbgValueInDefinedReg(Prev) ||
1538 Prev->getOperand(0).getReg() != Reg)
1540 // Var is clobbered. Make sure the next instruction gets a label.
1541 History.push_back(MI);
1548 for (auto &I : DbgValues) {
1549 SmallVectorImpl<const MachineInstr *> &History = I.second;
1550 if (History.empty())
1553 // Make sure the final register assignments are terminated.
1554 const MachineInstr *Prev = History.back();
1555 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1556 const MachineBasicBlock *PrevMBB = Prev->getParent();
1557 MachineBasicBlock::const_iterator LastMI =
1558 PrevMBB->getLastNonDebugInstr();
1559 if (LastMI == PrevMBB->end())
1560 // Drop DBG_VALUE for empty range.
1562 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1563 // Terminate after LastMI.
1564 History.push_back(LastMI);
1567 // Request labels for the full history.
1568 for (const MachineInstr *MI : History) {
1569 if (MI->isDebugValue())
1570 requestLabelBeforeInsn(MI);
1572 requestLabelAfterInsn(MI);
1576 PrevInstLoc = DebugLoc();
1577 PrevLabel = FunctionBeginSym;
1579 // Record beginning of function.
1580 if (!PrologEndLoc.isUnknown()) {
1581 DebugLoc FnStartDL =
1582 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1584 FnStartDL.getLine(), FnStartDL.getCol(),
1585 FnStartDL.getScope(MF->getFunction()->getContext()),
1586 // We'd like to list the prologue as "not statements" but GDB behaves
1587 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1588 DWARF2_FLAG_IS_STMT);
1592 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1593 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1594 DIVariable DV = Var->getVariable();
1595 // Variables with positive arg numbers are parameters.
1596 if (unsigned ArgNum = DV.getArgNumber()) {
1597 // Keep all parameters in order at the start of the variable list to ensure
1598 // function types are correct (no out-of-order parameters)
1600 // This could be improved by only doing it for optimized builds (unoptimized
1601 // builds have the right order to begin with), searching from the back (this
1602 // would catch the unoptimized case quickly), or doing a binary search
1603 // rather than linear search.
1604 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1605 while (I != Vars.end()) {
1606 unsigned CurNum = (*I)->getVariable().getArgNumber();
1607 // A local (non-parameter) variable has been found, insert immediately
1611 // A later indexed parameter has been found, insert immediately before it.
1612 if (CurNum > ArgNum)
1616 Vars.insert(I, Var);
1620 Vars.push_back(Var);
1623 // Gather and emit post-function debug information.
1624 void DwarfDebug::endFunction(const MachineFunction *MF) {
1625 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1626 // though the beginFunction may not be called at all.
1627 // We should handle both cases.
1631 assert(CurFn == MF);
1632 assert(CurFn != nullptr);
1634 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1635 // If we don't have a lexical scope for this function then there will
1636 // be a hole in the range information. Keep note of this by setting the
1637 // previously used section to nullptr.
1638 PrevSection = nullptr;
1644 // Define end label for subprogram.
1645 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1646 // Assumes in correct section after the entry point.
1647 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1649 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1650 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1652 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1653 collectVariableInfo(ProcessedVars);
1655 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1656 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1658 // Construct abstract scopes.
1659 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1660 DISubprogram SP(AScope->getScopeNode());
1661 if (SP.isSubprogram()) {
1662 // Collect info for variables that were optimized out.
1663 DIArray Variables = SP.getVariables();
1664 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1665 DIVariable DV(Variables.getElement(i));
1666 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1668 // Check that DbgVariable for DV wasn't created earlier, when
1669 // findAbstractVariable() was called for inlined instance of DV.
1670 LLVMContext &Ctx = DV->getContext();
1671 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1672 if (AbstractVariables.lookup(CleanDV))
1674 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1675 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1678 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1679 constructSubprogramScopeDIE(TheCU, AScope);
1682 DIE &CurFnDIE = *constructSubprogramScopeDIE(TheCU, FnScope);
1683 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1684 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1686 // Add the range of this function to the list of ranges for the CU.
1687 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1688 TheCU.addRange(std::move(Span));
1689 PrevSection = Asm->getCurrentSection();
1693 for (auto &I : ScopeVariables)
1694 DeleteContainerPointers(I.second);
1695 ScopeVariables.clear();
1696 DeleteContainerPointers(CurrentFnArguments);
1697 UserVariables.clear();
1699 AbstractVariables.clear();
1700 LabelsBeforeInsn.clear();
1701 LabelsAfterInsn.clear();
1702 PrevLabel = nullptr;
1706 // Register a source line with debug info. Returns the unique label that was
1707 // emitted and which provides correspondence to the source line list.
1708 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1713 unsigned Discriminator = 0;
1715 DIDescriptor Scope(S);
1717 if (Scope.isCompileUnit()) {
1718 DICompileUnit CU(S);
1719 Fn = CU.getFilename();
1720 Dir = CU.getDirectory();
1721 } else if (Scope.isFile()) {
1723 Fn = F.getFilename();
1724 Dir = F.getDirectory();
1725 } else if (Scope.isSubprogram()) {
1727 Fn = SP.getFilename();
1728 Dir = SP.getDirectory();
1729 } else if (Scope.isLexicalBlockFile()) {
1730 DILexicalBlockFile DBF(S);
1731 Fn = DBF.getFilename();
1732 Dir = DBF.getDirectory();
1733 } else if (Scope.isLexicalBlock()) {
1734 DILexicalBlock DB(S);
1735 Fn = DB.getFilename();
1736 Dir = DB.getDirectory();
1737 Discriminator = DB.getDiscriminator();
1739 llvm_unreachable("Unexpected scope info");
1741 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1742 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1743 .getOrCreateSourceID(Fn, Dir);
1745 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1749 //===----------------------------------------------------------------------===//
1751 //===----------------------------------------------------------------------===//
1753 // Emit initial Dwarf sections with a label at the start of each one.
1754 void DwarfDebug::emitSectionLabels() {
1755 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1757 // Dwarf sections base addresses.
1758 DwarfInfoSectionSym =
1759 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1760 if (useSplitDwarf())
1761 DwarfInfoDWOSectionSym =
1762 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1763 DwarfAbbrevSectionSym =
1764 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1765 if (useSplitDwarf())
1766 DwarfAbbrevDWOSectionSym = emitSectionSym(
1767 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1768 if (GenerateARangeSection)
1769 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1771 DwarfLineSectionSym =
1772 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1773 if (GenerateGnuPubSections) {
1774 DwarfGnuPubNamesSectionSym =
1775 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1776 DwarfGnuPubTypesSectionSym =
1777 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1778 } else if (HasDwarfPubSections) {
1779 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1780 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1783 DwarfStrSectionSym =
1784 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1785 if (useSplitDwarf()) {
1786 DwarfStrDWOSectionSym =
1787 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1788 DwarfAddrSectionSym =
1789 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1790 DwarfDebugLocSectionSym =
1791 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1793 DwarfDebugLocSectionSym =
1794 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1795 DwarfDebugRangeSectionSym =
1796 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1799 // Recursively emits a debug information entry.
1800 void DwarfDebug::emitDIE(DIE &Die) {
1801 // Get the abbreviation for this DIE.
1802 const DIEAbbrev &Abbrev = Die.getAbbrev();
1804 // Emit the code (index) for the abbreviation.
1805 if (Asm->isVerbose())
1806 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1807 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1808 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1809 dwarf::TagString(Abbrev.getTag()));
1810 Asm->EmitULEB128(Abbrev.getNumber());
1812 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1813 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1815 // Emit the DIE attribute values.
1816 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1817 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1818 dwarf::Form Form = AbbrevData[i].getForm();
1819 assert(Form && "Too many attributes for DIE (check abbreviation)");
1821 if (Asm->isVerbose()) {
1822 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1823 if (Attr == dwarf::DW_AT_accessibility)
1824 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1825 cast<DIEInteger>(Values[i])->getValue()));
1828 // Emit an attribute using the defined form.
1829 Values[i]->EmitValue(Asm, Form);
1832 // Emit the DIE children if any.
1833 if (Abbrev.hasChildren()) {
1834 for (auto &Child : Die.getChildren())
1837 Asm->OutStreamer.AddComment("End Of Children Mark");
1842 // Emit the debug info section.
1843 void DwarfDebug::emitDebugInfo() {
1844 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1846 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1849 // Emit the abbreviation section.
1850 void DwarfDebug::emitAbbreviations() {
1851 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1853 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1856 // Emit the last address of the section and the end of the line matrix.
1857 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1858 // Define last address of section.
1859 Asm->OutStreamer.AddComment("Extended Op");
1862 Asm->OutStreamer.AddComment("Op size");
1863 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1864 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1865 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1867 Asm->OutStreamer.AddComment("Section end label");
1869 Asm->OutStreamer.EmitSymbolValue(
1870 Asm->GetTempSymbol("section_end", SectionEnd),
1871 Asm->getDataLayout().getPointerSize());
1873 // Mark end of matrix.
1874 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1880 // Emit visible names into a hashed accelerator table section.
1881 void DwarfDebug::emitAccelNames() {
1882 AccelNames.FinalizeTable(Asm, "Names");
1883 Asm->OutStreamer.SwitchSection(
1884 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1885 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1886 Asm->OutStreamer.EmitLabel(SectionBegin);
1888 // Emit the full data.
1889 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1892 // Emit objective C classes and categories into a hashed accelerator table
1894 void DwarfDebug::emitAccelObjC() {
1895 AccelObjC.FinalizeTable(Asm, "ObjC");
1896 Asm->OutStreamer.SwitchSection(
1897 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1898 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1899 Asm->OutStreamer.EmitLabel(SectionBegin);
1901 // Emit the full data.
1902 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1905 // Emit namespace dies into a hashed accelerator table.
1906 void DwarfDebug::emitAccelNamespaces() {
1907 AccelNamespace.FinalizeTable(Asm, "namespac");
1908 Asm->OutStreamer.SwitchSection(
1909 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1910 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1911 Asm->OutStreamer.EmitLabel(SectionBegin);
1913 // Emit the full data.
1914 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1917 // Emit type dies into a hashed accelerator table.
1918 void DwarfDebug::emitAccelTypes() {
1920 AccelTypes.FinalizeTable(Asm, "types");
1921 Asm->OutStreamer.SwitchSection(
1922 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1923 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1924 Asm->OutStreamer.EmitLabel(SectionBegin);
1926 // Emit the full data.
1927 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1930 // Public name handling.
1931 // The format for the various pubnames:
1933 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1934 // for the DIE that is named.
1936 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1937 // into the CU and the index value is computed according to the type of value
1938 // for the DIE that is named.
1940 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1941 // it's the offset within the debug_info/debug_types dwo section, however, the
1942 // reference in the pubname header doesn't change.
1944 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1945 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1947 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1949 // We could have a specification DIE that has our most of our knowledge,
1950 // look for that now.
1951 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1953 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1954 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1955 Linkage = dwarf::GIEL_EXTERNAL;
1956 } else if (Die->findAttribute(dwarf::DW_AT_external))
1957 Linkage = dwarf::GIEL_EXTERNAL;
1959 switch (Die->getTag()) {
1960 case dwarf::DW_TAG_class_type:
1961 case dwarf::DW_TAG_structure_type:
1962 case dwarf::DW_TAG_union_type:
1963 case dwarf::DW_TAG_enumeration_type:
1964 return dwarf::PubIndexEntryDescriptor(
1965 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1966 ? dwarf::GIEL_STATIC
1967 : dwarf::GIEL_EXTERNAL);
1968 case dwarf::DW_TAG_typedef:
1969 case dwarf::DW_TAG_base_type:
1970 case dwarf::DW_TAG_subrange_type:
1971 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1972 case dwarf::DW_TAG_namespace:
1973 return dwarf::GIEK_TYPE;
1974 case dwarf::DW_TAG_subprogram:
1975 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1976 case dwarf::DW_TAG_constant:
1977 case dwarf::DW_TAG_variable:
1978 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1979 case dwarf::DW_TAG_enumerator:
1980 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1981 dwarf::GIEL_STATIC);
1983 return dwarf::GIEK_NONE;
1987 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1989 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1990 const MCSection *PSec =
1991 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1992 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1994 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1997 void DwarfDebug::emitDebugPubSection(
1998 bool GnuStyle, const MCSection *PSec, StringRef Name,
1999 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2000 for (const auto &NU : CUMap) {
2001 DwarfCompileUnit *TheU = NU.second;
2003 const auto &Globals = (TheU->*Accessor)();
2005 if (Globals.empty())
2008 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2010 unsigned ID = TheU->getUniqueID();
2012 // Start the dwarf pubnames section.
2013 Asm->OutStreamer.SwitchSection(PSec);
2016 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2017 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2018 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2019 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2021 Asm->OutStreamer.EmitLabel(BeginLabel);
2023 Asm->OutStreamer.AddComment("DWARF Version");
2024 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2026 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2027 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2029 Asm->OutStreamer.AddComment("Compilation Unit Length");
2030 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2032 // Emit the pubnames for this compilation unit.
2033 for (const auto &GI : Globals) {
2034 const char *Name = GI.getKeyData();
2035 const DIE *Entity = GI.second;
2037 Asm->OutStreamer.AddComment("DIE offset");
2038 Asm->EmitInt32(Entity->getOffset());
2041 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2042 Asm->OutStreamer.AddComment(
2043 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2044 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2045 Asm->EmitInt8(Desc.toBits());
2048 Asm->OutStreamer.AddComment("External Name");
2049 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2052 Asm->OutStreamer.AddComment("End Mark");
2054 Asm->OutStreamer.EmitLabel(EndLabel);
2058 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2059 const MCSection *PSec =
2060 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2061 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2063 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2066 // Emit visible names into a debug str section.
2067 void DwarfDebug::emitDebugStr() {
2068 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2069 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2072 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2073 const DebugLocEntry &Entry) {
2074 assert(Entry.getValues().size() == 1 &&
2075 "multi-value entries are not supported yet.");
2076 const DebugLocEntry::Value Value = Entry.getValues()[0];
2077 DIVariable DV(Value.getVariable());
2078 if (Value.isInt()) {
2079 DIBasicType BTy(resolve(DV.getType()));
2080 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2081 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2082 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2083 Streamer.EmitSLEB128(Value.getInt());
2085 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2086 Streamer.EmitULEB128(Value.getInt());
2088 } else if (Value.isLocation()) {
2089 MachineLocation Loc = Value.getLoc();
2090 if (!DV.hasComplexAddress())
2092 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2094 // Complex address entry.
2095 unsigned N = DV.getNumAddrElements();
2097 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2098 if (Loc.getOffset()) {
2100 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2101 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2102 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2103 Streamer.EmitSLEB128(DV.getAddrElement(1));
2105 // If first address element is OpPlus then emit
2106 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2107 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2108 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2112 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2115 // Emit remaining complex address elements.
2116 for (; i < N; ++i) {
2117 uint64_t Element = DV.getAddrElement(i);
2118 if (Element == DIBuilder::OpPlus) {
2119 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2120 Streamer.EmitULEB128(DV.getAddrElement(++i));
2121 } else if (Element == DIBuilder::OpDeref) {
2123 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2125 llvm_unreachable("unknown Opcode found in complex address");
2129 // else ... ignore constant fp. There is not any good way to
2130 // to represent them here in dwarf.
2134 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2135 Asm->OutStreamer.AddComment("Loc expr size");
2136 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2137 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2138 Asm->EmitLabelDifference(end, begin, 2);
2139 Asm->OutStreamer.EmitLabel(begin);
2141 APByteStreamer Streamer(*Asm);
2142 emitDebugLocEntry(Streamer, Entry);
2144 Asm->OutStreamer.EmitLabel(end);
2147 // Emit locations into the debug loc section.
2148 void DwarfDebug::emitDebugLoc() {
2149 // Start the dwarf loc section.
2150 Asm->OutStreamer.SwitchSection(
2151 Asm->getObjFileLowering().getDwarfLocSection());
2152 unsigned char Size = Asm->getDataLayout().getPointerSize();
2153 for (const auto &DebugLoc : DotDebugLocEntries) {
2154 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2155 for (const auto &Entry : DebugLoc.List) {
2156 // Set up the range. This range is relative to the entry point of the
2157 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2158 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2159 const DwarfCompileUnit *CU = Entry.getCU();
2160 if (CU->getRanges().size() == 1) {
2161 // Grab the begin symbol from the first range as our base.
2162 const MCSymbol *Base = CU->getRanges()[0].getStart();
2163 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2164 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2166 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2167 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2170 emitDebugLocEntryLocation(Entry);
2172 Asm->OutStreamer.EmitIntValue(0, Size);
2173 Asm->OutStreamer.EmitIntValue(0, Size);
2177 void DwarfDebug::emitDebugLocDWO() {
2178 Asm->OutStreamer.SwitchSection(
2179 Asm->getObjFileLowering().getDwarfLocDWOSection());
2180 for (const auto &DebugLoc : DotDebugLocEntries) {
2181 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2182 for (const auto &Entry : DebugLoc.List) {
2183 // Just always use start_length for now - at least that's one address
2184 // rather than two. We could get fancier and try to, say, reuse an
2185 // address we know we've emitted elsewhere (the start of the function?
2186 // The start of the CU or CU subrange that encloses this range?)
2187 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2188 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2189 Asm->EmitULEB128(idx);
2190 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2192 emitDebugLocEntryLocation(Entry);
2194 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2199 const MCSymbol *Start, *End;
2202 // Emit a debug aranges section, containing a CU lookup for any
2203 // address we can tie back to a CU.
2204 void DwarfDebug::emitDebugARanges() {
2205 // Start the dwarf aranges section.
2206 Asm->OutStreamer.SwitchSection(
2207 Asm->getObjFileLowering().getDwarfARangesSection());
2209 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2213 // Build a list of sections used.
2214 std::vector<const MCSection *> Sections;
2215 for (const auto &it : SectionMap) {
2216 const MCSection *Section = it.first;
2217 Sections.push_back(Section);
2220 // Sort the sections into order.
2221 // This is only done to ensure consistent output order across different runs.
2222 std::sort(Sections.begin(), Sections.end(), SectionSort);
2224 // Build a set of address spans, sorted by CU.
2225 for (const MCSection *Section : Sections) {
2226 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2227 if (List.size() < 2)
2230 // Sort the symbols by offset within the section.
2231 std::sort(List.begin(), List.end(),
2232 [&](const SymbolCU &A, const SymbolCU &B) {
2233 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2234 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2236 // Symbols with no order assigned should be placed at the end.
2237 // (e.g. section end labels)
2245 // If we have no section (e.g. common), just write out
2246 // individual spans for each symbol.
2248 for (const SymbolCU &Cur : List) {
2250 Span.Start = Cur.Sym;
2253 Spans[Cur.CU].push_back(Span);
2256 // Build spans between each label.
2257 const MCSymbol *StartSym = List[0].Sym;
2258 for (size_t n = 1, e = List.size(); n < e; n++) {
2259 const SymbolCU &Prev = List[n - 1];
2260 const SymbolCU &Cur = List[n];
2262 // Try and build the longest span we can within the same CU.
2263 if (Cur.CU != Prev.CU) {
2265 Span.Start = StartSym;
2267 Spans[Prev.CU].push_back(Span);
2274 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2276 // Build a list of CUs used.
2277 std::vector<DwarfCompileUnit *> CUs;
2278 for (const auto &it : Spans) {
2279 DwarfCompileUnit *CU = it.first;
2283 // Sort the CU list (again, to ensure consistent output order).
2284 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2285 return A->getUniqueID() < B->getUniqueID();
2288 // Emit an arange table for each CU we used.
2289 for (DwarfCompileUnit *CU : CUs) {
2290 std::vector<ArangeSpan> &List = Spans[CU];
2292 // Emit size of content not including length itself.
2293 unsigned ContentSize =
2294 sizeof(int16_t) + // DWARF ARange version number
2295 sizeof(int32_t) + // Offset of CU in the .debug_info section
2296 sizeof(int8_t) + // Pointer Size (in bytes)
2297 sizeof(int8_t); // Segment Size (in bytes)
2299 unsigned TupleSize = PtrSize * 2;
2301 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2303 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2305 ContentSize += Padding;
2306 ContentSize += (List.size() + 1) * TupleSize;
2308 // For each compile unit, write the list of spans it covers.
2309 Asm->OutStreamer.AddComment("Length of ARange Set");
2310 Asm->EmitInt32(ContentSize);
2311 Asm->OutStreamer.AddComment("DWARF Arange version number");
2312 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2313 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2314 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2315 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2316 Asm->EmitInt8(PtrSize);
2317 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2320 Asm->OutStreamer.EmitFill(Padding, 0xff);
2322 for (const ArangeSpan &Span : List) {
2323 Asm->EmitLabelReference(Span.Start, PtrSize);
2325 // Calculate the size as being from the span start to it's end.
2327 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2329 // For symbols without an end marker (e.g. common), we
2330 // write a single arange entry containing just that one symbol.
2331 uint64_t Size = SymSize[Span.Start];
2335 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2339 Asm->OutStreamer.AddComment("ARange terminator");
2340 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2341 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2345 // Emit visible names into a debug ranges section.
2346 void DwarfDebug::emitDebugRanges() {
2347 // Start the dwarf ranges section.
2348 Asm->OutStreamer.SwitchSection(
2349 Asm->getObjFileLowering().getDwarfRangesSection());
2351 // Size for our labels.
2352 unsigned char Size = Asm->getDataLayout().getPointerSize();
2354 // Grab the specific ranges for the compile units in the module.
2355 for (const auto &I : CUMap) {
2356 DwarfCompileUnit *TheCU = I.second;
2358 // Emit a symbol so we can find the beginning of our ranges.
2359 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2361 // Iterate over the misc ranges for the compile units in the module.
2362 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2363 // Emit our symbol so we can find the beginning of the range.
2364 Asm->OutStreamer.EmitLabel(List.getSym());
2366 for (const RangeSpan &Range : List.getRanges()) {
2367 const MCSymbol *Begin = Range.getStart();
2368 const MCSymbol *End = Range.getEnd();
2369 assert(Begin && "Range without a begin symbol?");
2370 assert(End && "Range without an end symbol?");
2371 if (TheCU->getRanges().size() == 1) {
2372 // Grab the begin symbol from the first range as our base.
2373 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2374 Asm->EmitLabelDifference(Begin, Base, Size);
2375 Asm->EmitLabelDifference(End, Base, Size);
2377 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2378 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);
2387 // Now emit a range for the CU itself.
2388 if (TheCU->getRanges().size() > 1) {
2389 Asm->OutStreamer.EmitLabel(
2390 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2391 for (const RangeSpan &Range : TheCU->getRanges()) {
2392 const MCSymbol *Begin = Range.getStart();
2393 const MCSymbol *End = Range.getEnd();
2394 assert(Begin && "Range without a begin symbol?");
2395 assert(End && "Range without an end symbol?");
2396 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2397 Asm->OutStreamer.EmitSymbolValue(End, Size);
2399 // And terminate the list with two 0 values.
2400 Asm->OutStreamer.EmitIntValue(0, Size);
2401 Asm->OutStreamer.EmitIntValue(0, Size);
2406 // DWARF5 Experimental Separate Dwarf emitters.
2408 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2409 std::unique_ptr<DwarfUnit> NewU) {
2410 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2411 U.getCUNode().getSplitDebugFilename());
2413 if (!CompilationDir.empty())
2414 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2416 addGnuPubAttributes(*NewU, Die);
2418 SkeletonHolder.addUnit(std::move(NewU));
2421 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2422 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2423 // DW_AT_addr_base, DW_AT_ranges_base.
2424 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2426 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2427 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2428 DwarfCompileUnit &NewCU = *OwnedUnit;
2429 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2430 DwarfInfoSectionSym);
2432 NewCU.initStmtList(DwarfLineSectionSym);
2434 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2439 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2441 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2442 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2443 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2445 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), CU, Asm, this,
2447 DwarfTypeUnit &NewTU = *OwnedUnit;
2448 NewTU.setTypeSignature(TU.getTypeSignature());
2449 NewTU.setType(nullptr);
2451 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2453 initSkeletonUnit(TU, NewTU.getUnitDie(), std::move(OwnedUnit));
2457 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2458 // compile units that would normally be in debug_info.
2459 void DwarfDebug::emitDebugInfoDWO() {
2460 assert(useSplitDwarf() && "No split dwarf debug info?");
2461 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2462 // emit relocations into the dwo file.
2463 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2466 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2467 // abbreviations for the .debug_info.dwo section.
2468 void DwarfDebug::emitDebugAbbrevDWO() {
2469 assert(useSplitDwarf() && "No split dwarf?");
2470 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2473 void DwarfDebug::emitDebugLineDWO() {
2474 assert(useSplitDwarf() && "No split dwarf?");
2475 Asm->OutStreamer.SwitchSection(
2476 Asm->getObjFileLowering().getDwarfLineDWOSection());
2477 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2480 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2481 // string section and is identical in format to traditional .debug_str
2483 void DwarfDebug::emitDebugStrDWO() {
2484 assert(useSplitDwarf() && "No split dwarf?");
2485 const MCSection *OffSec =
2486 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2487 const MCSymbol *StrSym = DwarfStrSectionSym;
2488 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2492 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2493 if (!useSplitDwarf())
2496 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2497 return &SplitTypeUnitFileTable;
2500 static uint64_t makeTypeSignature(StringRef Identifier) {
2502 Hash.update(Identifier);
2503 // ... take the least significant 8 bytes and return those. Our MD5
2504 // implementation always returns its results in little endian, swap bytes
2506 MD5::MD5Result Result;
2508 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2511 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2512 StringRef Identifier, DIE &RefDie,
2513 DICompositeType CTy) {
2514 // Fast path if we're building some type units and one has already used the
2515 // address pool we know we're going to throw away all this work anyway, so
2516 // don't bother building dependent types.
2517 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2520 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2522 CU.addDIETypeSignature(RefDie, *TU);
2526 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2527 AddrPool.resetUsedFlag();
2530 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), CU, Asm, this,
2531 &InfoHolder, getDwoLineTable(CU));
2532 DwarfTypeUnit &NewTU = *OwnedUnit;
2533 DIE &UnitDie = NewTU.getUnitDie();
2535 TypeUnitsUnderConstruction.push_back(
2536 std::make_pair(std::move(OwnedUnit), CTy));
2538 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2541 uint64_t Signature = makeTypeSignature(Identifier);
2542 NewTU.setTypeSignature(Signature);
2544 if (!useSplitDwarf())
2545 CU.applyStmtList(UnitDie);
2549 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2550 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2552 NewTU.setType(NewTU.createTypeDIE(CTy));
2555 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2556 TypeUnitsUnderConstruction.clear();
2558 // Types referencing entries in the address table cannot be placed in type
2560 if (AddrPool.hasBeenUsed()) {
2562 // Remove all the types built while building this type.
2563 // This is pessimistic as some of these types might not be dependent on
2564 // the type that used an address.
2565 for (const auto &TU : TypeUnitsToAdd)
2566 DwarfTypeUnits.erase(TU.second);
2568 // Construct this type in the CU directly.
2569 // This is inefficient because all the dependent types will be rebuilt
2570 // from scratch, including building them in type units, discovering that
2571 // they depend on addresses, throwing them out and rebuilding them.
2572 CU.constructTypeDIE(RefDie, CTy);
2576 // If the type wasn't dependent on fission addresses, finish adding the type
2577 // and all its dependent types.
2578 for (auto &TU : TypeUnitsToAdd) {
2579 if (useSplitDwarf())
2580 TU.first->setSkeleton(constructSkeletonTU(*TU.first));
2581 InfoHolder.addUnit(std::move(TU.first));
2584 CU.addDIETypeSignature(RefDie, NewTU);
2587 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2588 MCSymbol *Begin, MCSymbol *End) {
2589 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2590 if (DwarfVersion < 4)
2591 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2593 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2596 // Accelerator table mutators - add each name along with its companion
2597 // DIE to the proper table while ensuring that the name that we're going
2598 // to reference is in the string table. We do this since the names we
2599 // add may not only be identical to the names in the DIE.
2600 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2601 if (!useDwarfAccelTables())
2603 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2607 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2608 if (!useDwarfAccelTables())
2610 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2614 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2615 if (!useDwarfAccelTables())
2617 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2621 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2622 if (!useDwarfAccelTables())
2624 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),