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.getOrCreateSubprogramDIE(SP);
319 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
321 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
322 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
323 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
325 // Add name to the name table, we do this here because we're guaranteed
326 // to have concrete versions of our DW_TAG_subprogram nodes.
327 addSubprogramNames(SP, *SPDie);
332 /// Check whether we should create a DIE for the given Scope, return true
333 /// if we don't create a DIE (the corresponding DIE is null).
334 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
335 if (Scope->isAbstractScope())
338 // We don't create a DIE if there is no Range.
339 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
343 if (Ranges.size() > 1)
346 // We don't create a DIE if we have a single Range and the end label
348 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
349 MCSymbol *End = getLabelAfterInsn(RI->second);
353 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
354 dwarf::Attribute A, const MCSymbol *L,
355 const MCSymbol *Sec) {
356 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
357 U.addSectionLabel(D, A, L);
359 U.addSectionDelta(D, A, L, Sec);
362 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
363 const SmallVectorImpl<InsnRange> &Range) {
364 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
365 // emitting it appropriately.
366 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
368 // Under fission, ranges are specified by constant offsets relative to the
369 // CU's DW_AT_GNU_ranges_base.
371 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
372 DwarfDebugRangeSectionSym);
374 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
375 DwarfDebugRangeSectionSym);
377 RangeSpanList List(RangeSym);
378 for (const InsnRange &R : Range) {
379 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
380 List.addRange(std::move(Span));
383 // Add the range list to the set of ranges to be emitted.
384 TheCU.addRangeList(std::move(List));
387 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
388 const SmallVectorImpl<InsnRange> &Ranges) {
389 assert(!Ranges.empty());
390 if (Ranges.size() == 1)
391 attachLowHighPC(TheCU, Die, getLabelBeforeInsn(Ranges.front().first),
392 getLabelAfterInsn(Ranges.front().second));
394 addScopeRangeList(TheCU, Die, Ranges);
397 // Construct new DW_TAG_lexical_block for this scope and attach
398 // DW_AT_low_pc/DW_AT_high_pc labels.
400 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
401 LexicalScope *Scope) {
402 if (isLexicalScopeDIENull(Scope))
405 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
406 if (Scope->isAbstractScope())
409 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
414 // This scope represents inlined body of a function. Construct DIE to
415 // represent this concrete inlined copy of the function.
417 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
418 LexicalScope *Scope) {
419 assert(Scope->getScopeNode());
420 DIScope DS(Scope->getScopeNode());
421 DISubprogram InlinedSP = getDISubprogram(DS);
422 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
423 // was inlined from another compile unit.
424 DIE *OriginDIE = AbstractSPDies[InlinedSP];
425 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
427 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
428 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
430 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
432 InlinedSubprogramDIEs.insert(OriginDIE);
434 // Add the call site information to the DIE.
435 DILocation DL(Scope->getInlinedAt());
436 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
437 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
438 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
440 // Add name to the name table, we do this here because we're guaranteed
441 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
442 addSubprogramNames(InlinedSP, *ScopeDIE);
447 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
449 const LexicalScope &Scope,
450 DIE *&ObjectPointer) {
451 AbstractOrInlined AOI = AOI_None;
452 if (Scope.isAbstractScope())
454 else if (Scope.getInlinedAt())
456 auto Var = TheCU.constructVariableDIE(DV, AOI);
457 if (DV.isObjectPointer())
458 ObjectPointer = Var.get();
462 DIE *DwarfDebug::createScopeChildrenDIE(
463 DwarfCompileUnit &TheCU, LexicalScope *Scope,
464 SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
465 DIE *ObjectPointer = nullptr;
467 // Collect arguments for current function.
468 if (LScopes.isCurrentFunctionScope(Scope)) {
469 for (DbgVariable *ArgDV : CurrentFnArguments)
472 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
474 // If this is a variadic function, add an unspecified parameter.
475 DISubprogram SP(Scope->getScopeNode());
476 DIArray FnArgs = SP.getType().getTypeArray();
477 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
478 .isUnspecifiedParameter()) {
480 make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
484 // Collect lexical scope children first.
485 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
486 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
488 for (LexicalScope *LS : Scope->getChildren())
489 if (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
490 Children.push_back(std::move(Nested));
491 return ObjectPointer;
494 void DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
495 LexicalScope *Scope, DIE &ScopeDIE) {
496 // We create children when the scope DIE is not null.
497 SmallVector<std::unique_ptr<DIE>, 8> Children;
498 if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
499 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
502 for (auto &I : Children)
503 ScopeDIE.addChild(std::move(I));
506 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
507 LexicalScope *Scope) {
508 assert(Scope && Scope->getScopeNode());
509 assert(Scope->isAbstractScope());
510 assert(!Scope->getInlinedAt());
512 DISubprogram SP(Scope->getScopeNode());
514 ProcessedSPNodes.insert(SP);
516 DIE *&AbsDef = AbstractSPDies[SP];
520 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
521 // was inlined from another compile unit.
522 DwarfCompileUnit &SPCU = *SPMap[SP];
525 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
526 // the important distinction that the DIDescriptor is not associated with the
527 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
528 // any). It could be refactored to some common utility function.
529 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
530 ContextDIE = &SPCU.getUnitDie();
531 SPCU.getOrCreateSubprogramDIE(SPDecl);
533 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
535 // Passing null as the associated DIDescriptor because the abstract definition
536 // shouldn't be found by lookup.
537 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
539 SPCU.applySubprogramAttributes(SP, *AbsDef);
540 SPCU.addGlobalName(SP.getName(), *AbsDef, resolve(SP.getContext()));
542 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
543 createAndAddScopeChildren(SPCU, Scope, *AbsDef);
546 DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
547 LexicalScope *Scope) {
548 assert(Scope && Scope->getScopeNode());
549 assert(!Scope->getInlinedAt());
550 assert(!Scope->isAbstractScope());
551 DISubprogram Sub(Scope->getScopeNode());
553 assert(Sub.isSubprogram());
555 ProcessedSPNodes.insert(Sub);
557 DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
559 createAndAddScopeChildren(TheCU, Scope, ScopeDIE);
564 // Construct a DIE for this scope.
565 std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
566 LexicalScope *Scope) {
567 if (!Scope || !Scope->getScopeNode())
570 DIScope DS(Scope->getScopeNode());
572 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
573 "Only handle inlined subprograms here, use "
574 "constructSubprogramScopeDIE for non-inlined "
577 SmallVector<std::unique_ptr<DIE>, 8> Children;
579 // We try to create the scope DIE first, then the children DIEs. This will
580 // avoid creating un-used children then removing them later when we find out
581 // the scope DIE is null.
582 std::unique_ptr<DIE> ScopeDIE;
583 if (Scope->getParent() && DS.isSubprogram()) {
584 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
587 // We create children when the scope DIE is not null.
588 createScopeChildrenDIE(TheCU, Scope, Children);
590 // Early exit when we know the scope DIE is going to be null.
591 if (isLexicalScopeDIENull(Scope))
594 // We create children here when we know the scope DIE is not going to be
595 // null and the children will be added to the scope DIE.
596 createScopeChildrenDIE(TheCU, Scope, Children);
598 // There is no need to emit empty lexical block DIE.
599 std::pair<ImportedEntityMap::const_iterator,
600 ImportedEntityMap::const_iterator> Range =
601 std::equal_range(ScopesWithImportedEntities.begin(),
602 ScopesWithImportedEntities.end(),
603 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
605 if (Children.empty() && Range.first == Range.second)
607 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
608 assert(ScopeDIE && "Scope DIE should not be null.");
609 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
611 constructImportedEntityDIE(TheCU, i->second, *ScopeDIE);
615 for (auto &I : Children)
616 ScopeDIE->addChild(std::move(I));
621 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
622 if (!GenerateGnuPubSections)
625 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
628 // Create new DwarfCompileUnit for the given metadata node with tag
629 // DW_TAG_compile_unit.
630 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
631 StringRef FN = DIUnit.getFilename();
632 CompilationDir = DIUnit.getDirectory();
634 auto OwnedUnit = make_unique<DwarfCompileUnit>(
635 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
636 DwarfCompileUnit &NewCU = *OwnedUnit;
637 DIE &Die = NewCU.getUnitDie();
638 InfoHolder.addUnit(std::move(OwnedUnit));
640 // LTO with assembly output shares a single line table amongst multiple CUs.
641 // To avoid the compilation directory being ambiguous, let the line table
642 // explicitly describe the directory of all files, never relying on the
643 // compilation directory.
644 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
645 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
646 NewCU.getUniqueID(), CompilationDir);
648 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
649 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
650 DIUnit.getLanguage());
651 NewCU.addString(Die, dwarf::DW_AT_name, FN);
653 if (!useSplitDwarf()) {
654 NewCU.initStmtList(DwarfLineSectionSym);
656 // If we're using split dwarf the compilation dir is going to be in the
657 // skeleton CU and so we don't need to duplicate it here.
658 if (!CompilationDir.empty())
659 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
661 addGnuPubAttributes(NewCU, Die);
664 if (DIUnit.isOptimized())
665 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
667 StringRef Flags = DIUnit.getFlags();
669 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
671 if (unsigned RVer = DIUnit.getRunTimeVersion())
672 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
673 dwarf::DW_FORM_data1, RVer);
678 if (useSplitDwarf()) {
679 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
680 DwarfInfoDWOSectionSym);
681 NewCU.setSkeleton(constructSkeletonCU(NewCU));
683 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
684 DwarfInfoSectionSym);
686 CUMap.insert(std::make_pair(DIUnit, &NewCU));
687 CUDieMap.insert(std::make_pair(&Die, &NewCU));
691 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
693 DIImportedEntity Module(N);
694 assert(Module.Verify());
695 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
696 constructImportedEntityDIE(TheCU, Module, *D);
699 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
700 const MDNode *N, DIE &Context) {
701 DIImportedEntity Module(N);
702 assert(Module.Verify());
703 return constructImportedEntityDIE(TheCU, Module, Context);
706 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
707 const DIImportedEntity &Module,
709 assert(Module.Verify() &&
710 "Use one of the MDNode * overloads to handle invalid metadata");
711 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), Context, Module);
713 DIDescriptor Entity = resolve(Module.getEntity());
714 if (Entity.isNameSpace())
715 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
716 else if (Entity.isSubprogram())
717 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
718 else if (Entity.isType())
719 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
721 EntityDie = TheCU.getDIE(Entity);
722 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
723 Module.getContext().getFilename(),
724 Module.getContext().getDirectory());
725 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
726 StringRef Name = Module.getName();
728 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
731 // Emit all Dwarf sections that should come prior to the content. Create
732 // global DIEs and emit initial debug info sections. This is invoked by
733 // the target AsmPrinter.
734 void DwarfDebug::beginModule() {
735 if (DisableDebugInfoPrinting)
738 const Module *M = MMI->getModule();
740 // If module has named metadata anchors then use them, otherwise scan the
741 // module using debug info finder to collect debug info.
742 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
745 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
747 // Emit initial sections so we can reference labels later.
750 SingleCU = CU_Nodes->getNumOperands() == 1;
752 for (MDNode *N : CU_Nodes->operands()) {
753 DICompileUnit CUNode(N);
754 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
755 DIArray ImportedEntities = CUNode.getImportedEntities();
756 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
757 ScopesWithImportedEntities.push_back(std::make_pair(
758 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
759 ImportedEntities.getElement(i)));
760 std::sort(ScopesWithImportedEntities.begin(),
761 ScopesWithImportedEntities.end(), less_first());
762 DIArray GVs = CUNode.getGlobalVariables();
763 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
764 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
765 DIArray SPs = CUNode.getSubprograms();
766 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
767 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
768 DIArray EnumTypes = CUNode.getEnumTypes();
769 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
770 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
771 DIArray RetainedTypes = CUNode.getRetainedTypes();
772 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
773 DIType Ty(RetainedTypes.getElement(i));
774 // The retained types array by design contains pointers to
775 // MDNodes rather than DIRefs. Unique them here.
776 DIType UniqueTy(resolve(Ty.getRef()));
777 CU.getOrCreateTypeDIE(UniqueTy);
779 // Emit imported_modules last so that the relevant context is already
781 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
782 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
785 // Tell MMI that we have debug info.
786 MMI->setDebugInfoAvailability(true);
788 // Prime section data.
789 SectionMap[Asm->getObjFileLowering().getTextSection()];
792 void DwarfDebug::finishSubprogramDefinitions() {
793 const Module *M = MMI->getModule();
795 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
796 for (MDNode *N : CU_Nodes->operands()) {
797 DICompileUnit TheCU(N);
798 // Construct subprogram DIE and add variables DIEs.
799 DwarfCompileUnit *SPCU =
800 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
801 DIArray Subprograms = TheCU.getSubprograms();
802 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
803 DISubprogram SP(Subprograms.getElement(i));
804 // Perhaps the subprogram is in another CU (such as due to comdat
805 // folding, etc), in which case ignore it here.
806 if (SPMap[SP] != SPCU)
808 DIE *D = SPCU->getDIE(SP);
809 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
811 // If this subprogram has an abstract definition, reference that
812 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
815 // Lazily construct the subprogram if we didn't see either concrete or
816 // inlined versions during codegen.
817 D = SPCU->getOrCreateSubprogramDIE(SP);
818 // And attach the attributes
819 SPCU->applySubprogramAttributes(SP, *D);
820 SPCU->addGlobalName(SP.getName(), *D, resolve(SP.getContext()));
827 // Collect info for variables that were optimized out.
828 void DwarfDebug::collectDeadVariables() {
829 const Module *M = MMI->getModule();
831 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
832 for (MDNode *N : CU_Nodes->operands()) {
833 DICompileUnit TheCU(N);
834 // Construct subprogram DIE and add variables DIEs.
835 DwarfCompileUnit *SPCU =
836 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
837 assert(SPCU && "Unable to find Compile Unit!");
838 DIArray Subprograms = TheCU.getSubprograms();
839 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
840 DISubprogram SP(Subprograms.getElement(i));
841 if (ProcessedSPNodes.count(SP) != 0)
843 assert(SP.isSubprogram() &&
844 "CU's subprogram list contains a non-subprogram");
845 assert(SP.isDefinition() &&
846 "CU's subprogram list contains a subprogram declaration");
847 DIArray Variables = SP.getVariables();
848 if (Variables.getNumElements() == 0)
851 DIE *SPDIE = AbstractSPDies.lookup(SP);
853 SPDIE = SPCU->getDIE(SP);
855 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
856 DIVariable DV(Variables.getElement(vi));
857 assert(DV.isVariable());
858 DbgVariable NewVar(DV, nullptr, this);
859 SPDIE->addChild(SPCU->constructVariableDIE(NewVar));
866 void DwarfDebug::finalizeModuleInfo() {
867 finishSubprogramDefinitions();
869 // Collect info for variables that were optimized out.
870 collectDeadVariables();
872 // Handle anything that needs to be done on a per-unit basis after
873 // all other generation.
874 for (const auto &TheU : getUnits()) {
875 // Emit DW_AT_containing_type attribute to connect types with their
876 // vtable holding type.
877 TheU->constructContainingTypeDIEs();
879 // Add CU specific attributes if we need to add any.
880 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
881 // If we're splitting the dwarf out now that we've got the entire
882 // CU then add the dwo id to it.
883 DwarfCompileUnit *SkCU =
884 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
885 if (useSplitDwarf()) {
886 // Emit a unique identifier for this CU.
887 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
888 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
889 dwarf::DW_FORM_data8, ID);
890 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
891 dwarf::DW_FORM_data8, ID);
893 // We don't keep track of which addresses are used in which CU so this
894 // is a bit pessimistic under LTO.
895 if (!AddrPool.isEmpty())
896 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
897 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
898 DwarfAddrSectionSym);
899 if (!TheU->getRangeLists().empty())
900 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
901 dwarf::DW_AT_GNU_ranges_base,
902 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
905 // If we have code split among multiple sections or non-contiguous
906 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
907 // remain in the .o file, otherwise add a DW_AT_low_pc.
908 // FIXME: We should use ranges allow reordering of code ala
909 // .subsections_via_symbols in mach-o. This would mean turning on
910 // ranges for all subprogram DIEs for mach-o.
911 DwarfCompileUnit &U =
912 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
913 unsigned NumRanges = TheU->getRanges().size();
916 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
917 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
918 DwarfDebugRangeSectionSym);
920 // A DW_AT_low_pc attribute may also be specified in combination with
921 // DW_AT_ranges to specify the default base address for use in
922 // location lists (see Section 2.6.2) and range lists (see Section
924 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
927 RangeSpan &Range = TheU->getRanges().back();
928 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
930 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
937 // Compute DIE offsets and sizes.
938 InfoHolder.computeSizeAndOffsets();
940 SkeletonHolder.computeSizeAndOffsets();
943 void DwarfDebug::endSections() {
944 // Filter labels by section.
945 for (const SymbolCU &SCU : ArangeLabels) {
946 if (SCU.Sym->isInSection()) {
947 // Make a note of this symbol and it's section.
948 const MCSection *Section = &SCU.Sym->getSection();
949 if (!Section->getKind().isMetadata())
950 SectionMap[Section].push_back(SCU);
952 // Some symbols (e.g. common/bss on mach-o) can have no section but still
953 // appear in the output. This sucks as we rely on sections to build
954 // arange spans. We can do it without, but it's icky.
955 SectionMap[nullptr].push_back(SCU);
959 // Build a list of sections used.
960 std::vector<const MCSection *> Sections;
961 for (const auto &it : SectionMap) {
962 const MCSection *Section = it.first;
963 Sections.push_back(Section);
966 // Sort the sections into order.
967 // This is only done to ensure consistent output order across different runs.
968 std::sort(Sections.begin(), Sections.end(), SectionSort);
970 // Add terminating symbols for each section.
971 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
972 const MCSection *Section = Sections[ID];
973 MCSymbol *Sym = nullptr;
976 // We can't call MCSection::getLabelEndName, as it's only safe to do so
977 // if we know the section name up-front. For user-created sections, the
978 // resulting label may not be valid to use as a label. (section names can
979 // use a greater set of characters on some systems)
980 Sym = Asm->GetTempSymbol("debug_end", ID);
981 Asm->OutStreamer.SwitchSection(Section);
982 Asm->OutStreamer.EmitLabel(Sym);
985 // Insert a final terminator.
986 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
990 // Emit all Dwarf sections that should come after the content.
991 void DwarfDebug::endModule() {
992 assert(CurFn == nullptr);
993 assert(CurMI == nullptr);
998 // End any existing sections.
999 // TODO: Does this need to happen?
1002 // Finalize the debug info for the module.
1003 finalizeModuleInfo();
1007 // Emit all the DIEs into a debug info section.
1010 // Corresponding abbreviations into a abbrev section.
1011 emitAbbreviations();
1013 // Emit info into a debug aranges section.
1014 if (GenerateARangeSection)
1017 // Emit info into a debug ranges section.
1020 if (useSplitDwarf()) {
1023 emitDebugAbbrevDWO();
1025 // Emit DWO addresses.
1026 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1029 // Emit info into a debug loc section.
1032 // Emit info into the dwarf accelerator table sections.
1033 if (useDwarfAccelTables()) {
1036 emitAccelNamespaces();
1040 // Emit the pubnames and pubtypes sections if requested.
1041 if (HasDwarfPubSections) {
1042 emitDebugPubNames(GenerateGnuPubSections);
1043 emitDebugPubTypes(GenerateGnuPubSections);
1048 AbstractVariables.clear();
1050 // Reset these for the next Module if we have one.
1054 // Find abstract variable, if any, associated with Var.
1055 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1056 DebugLoc ScopeLoc) {
1057 return findAbstractVariable(DV, ScopeLoc.getScope(DV->getContext()));
1060 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1061 const MDNode *ScopeNode) {
1062 LLVMContext &Ctx = DV->getContext();
1063 // More then one inlined variable corresponds to one abstract variable.
1064 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1065 auto I = AbstractVariables.find(Var);
1066 if (I != AbstractVariables.end())
1067 return I->second.get();
1069 LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode);
1073 auto AbsDbgVariable = make_unique<DbgVariable>(Var, nullptr, this);
1074 addScopeVariable(Scope, AbsDbgVariable.get());
1075 return (AbstractVariables[Var] = std::move(AbsDbgVariable)).get();
1078 // If Var is a current function argument then add it to CurrentFnArguments list.
1079 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1080 if (!LScopes.isCurrentFunctionScope(Scope))
1082 DIVariable DV = Var->getVariable();
1083 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1085 unsigned ArgNo = DV.getArgNumber();
1089 size_t Size = CurrentFnArguments.size();
1091 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1092 // llvm::Function argument size is not good indicator of how many
1093 // arguments does the function have at source level.
1095 CurrentFnArguments.resize(ArgNo * 2);
1096 CurrentFnArguments[ArgNo - 1] = Var;
1100 // Collect variable information from side table maintained by MMI.
1101 void DwarfDebug::collectVariableInfoFromMMITable(
1102 SmallPtrSet<const MDNode *, 16> &Processed) {
1103 for (const auto &VI : MMI->getVariableDbgInfo()) {
1106 Processed.insert(VI.Var);
1107 DIVariable DV(VI.Var);
1108 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1110 // If variable scope is not found then skip this variable.
1114 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1115 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1116 RegVar->setFrameIndex(VI.Slot);
1117 if (!addCurrentFnArgument(RegVar, Scope))
1118 addScopeVariable(Scope, RegVar);
1122 // Get .debug_loc entry for the instruction range starting at MI.
1123 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1124 const MDNode *Var = MI->getDebugVariable();
1126 assert(MI->getNumOperands() == 3);
1127 if (MI->getOperand(0).isReg()) {
1128 MachineLocation MLoc;
1129 // If the second operand is an immediate, this is a
1130 // register-indirect address.
1131 if (!MI->getOperand(1).isImm())
1132 MLoc.set(MI->getOperand(0).getReg());
1134 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1135 return DebugLocEntry::Value(Var, MLoc);
1137 if (MI->getOperand(0).isImm())
1138 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1139 if (MI->getOperand(0).isFPImm())
1140 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1141 if (MI->getOperand(0).isCImm())
1142 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1144 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1147 // Find variables for each lexical scope.
1149 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1150 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1151 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1153 // Grab the variable info that was squirreled away in the MMI side-table.
1154 collectVariableInfoFromMMITable(Processed);
1156 for (const auto &I : DbgValues) {
1157 DIVariable DV(I.first);
1158 if (Processed.count(DV))
1161 // History contains relevant DBG_VALUE instructions for DV and instructions
1163 const SmallVectorImpl<const MachineInstr *> &History = I.second;
1164 if (History.empty())
1166 const MachineInstr *MInsn = History.front();
1168 LexicalScope *Scope = nullptr;
1169 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1170 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1171 Scope = LScopes.getCurrentFunctionScope();
1172 else if (MDNode *IA = DV.getInlinedAt()) {
1173 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1174 Scope = LScopes.findInlinedScope(DebugLoc::get(
1175 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1177 Scope = LScopes.findLexicalScope(DV.getContext());
1178 // If variable scope is not found then skip this variable.
1182 Processed.insert(DV);
1183 assert(MInsn->isDebugValue() && "History must begin with debug value");
1184 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1185 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1186 if (!addCurrentFnArgument(RegVar, Scope))
1187 addScopeVariable(Scope, RegVar);
1189 AbsVar->setMInsn(MInsn);
1191 // Simplify ranges that are fully coalesced.
1192 if (History.size() <= 1 ||
1193 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1194 RegVar->setMInsn(MInsn);
1198 // Handle multiple DBG_VALUE instructions describing one variable.
1199 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1201 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1202 DebugLocList &LocList = DotDebugLocEntries.back();
1204 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1205 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1206 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1207 HI = History.begin(),
1210 const MachineInstr *Begin = *HI;
1211 assert(Begin->isDebugValue() && "Invalid History entry");
1213 // Check if DBG_VALUE is truncating a range.
1214 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1215 !Begin->getOperand(0).getReg())
1218 // Compute the range for a register location.
1219 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1220 const MCSymbol *SLabel = nullptr;
1223 // If Begin is the last instruction in History then its value is valid
1224 // until the end of the function.
1225 SLabel = FunctionEndSym;
1227 const MachineInstr *End = HI[1];
1228 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1229 << "\t" << *Begin << "\t" << *End << "\n");
1230 if (End->isDebugValue() && End->getDebugVariable() == DV)
1231 SLabel = getLabelBeforeInsn(End);
1233 // End is clobbering the range.
1234 SLabel = getLabelAfterInsn(End);
1235 assert(SLabel && "Forgot label after clobber instruction");
1240 // The value is valid until the next DBG_VALUE or clobber.
1241 DebugLocEntry Loc(FLabel, SLabel, getDebugLocValue(Begin), TheCU);
1242 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1243 DebugLoc.push_back(std::move(Loc));
1247 // Collect info for variables that were optimized out.
1248 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1249 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1250 DIVariable DV(Variables.getElement(i));
1251 assert(DV.isVariable());
1252 if (!Processed.insert(DV))
1254 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1257 new DbgVariable(DV, findAbstractVariable(DV, Scope->getScopeNode()),
1262 // Return Label preceding the instruction.
1263 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1264 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1265 assert(Label && "Didn't insert label before instruction");
1269 // Return Label immediately following the instruction.
1270 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1271 return LabelsAfterInsn.lookup(MI);
1274 // Process beginning of an instruction.
1275 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1276 assert(CurMI == nullptr);
1278 // Check if source location changes, but ignore DBG_VALUE locations.
1279 if (!MI->isDebugValue()) {
1280 DebugLoc DL = MI->getDebugLoc();
1281 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1284 if (DL == PrologEndLoc) {
1285 Flags |= DWARF2_FLAG_PROLOGUE_END;
1286 PrologEndLoc = DebugLoc();
1288 if (PrologEndLoc.isUnknown())
1289 Flags |= DWARF2_FLAG_IS_STMT;
1291 if (!DL.isUnknown()) {
1292 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1293 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1295 recordSourceLine(0, 0, nullptr, 0);
1299 // Insert labels where requested.
1300 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1301 LabelsBeforeInsn.find(MI);
1304 if (I == LabelsBeforeInsn.end())
1307 // Label already assigned.
1312 PrevLabel = MMI->getContext().CreateTempSymbol();
1313 Asm->OutStreamer.EmitLabel(PrevLabel);
1315 I->second = PrevLabel;
1318 // Process end of an instruction.
1319 void DwarfDebug::endInstruction() {
1320 assert(CurMI != nullptr);
1321 // Don't create a new label after DBG_VALUE instructions.
1322 // They don't generate code.
1323 if (!CurMI->isDebugValue())
1324 PrevLabel = nullptr;
1326 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1327 LabelsAfterInsn.find(CurMI);
1331 if (I == LabelsAfterInsn.end())
1334 // Label already assigned.
1338 // We need a label after this instruction.
1340 PrevLabel = MMI->getContext().CreateTempSymbol();
1341 Asm->OutStreamer.EmitLabel(PrevLabel);
1343 I->second = PrevLabel;
1346 // Each LexicalScope has first instruction and last instruction to mark
1347 // beginning and end of a scope respectively. Create an inverse map that list
1348 // scopes starts (and ends) with an instruction. One instruction may start (or
1349 // end) multiple scopes. Ignore scopes that are not reachable.
1350 void DwarfDebug::identifyScopeMarkers() {
1351 SmallVector<LexicalScope *, 4> WorkList;
1352 WorkList.push_back(LScopes.getCurrentFunctionScope());
1353 while (!WorkList.empty()) {
1354 LexicalScope *S = WorkList.pop_back_val();
1356 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1357 if (!Children.empty())
1358 WorkList.append(Children.begin(), Children.end());
1360 if (S->isAbstractScope())
1363 for (const InsnRange &R : S->getRanges()) {
1364 assert(R.first && "InsnRange does not have first instruction!");
1365 assert(R.second && "InsnRange does not have second instruction!");
1366 requestLabelBeforeInsn(R.first);
1367 requestLabelAfterInsn(R.second);
1372 // Gather pre-function debug information. Assumes being called immediately
1373 // after the function entry point has been emitted.
1374 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1377 // If there's no debug info for the function we're not going to do anything.
1378 if (!MMI->hasDebugInfo())
1381 // Grab the lexical scopes for the function, if we don't have any of those
1382 // then we're not going to be able to do anything.
1383 LScopes.initialize(*MF);
1384 if (LScopes.empty())
1387 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1389 // Make sure that each lexical scope will have a begin/end label.
1390 identifyScopeMarkers();
1392 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1393 // belongs to so that we add to the correct per-cu line table in the
1395 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1396 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1397 assert(TheCU && "Unable to find compile unit!");
1398 if (Asm->OutStreamer.hasRawTextSupport())
1399 // Use a single line table if we are generating assembly.
1400 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1402 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1404 // Emit a label for the function so that we have a beginning address.
1405 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1406 // Assumes in correct section after the entry point.
1407 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1409 // Collect user variables, find the end of the prologue.
1410 for (const auto &MBB : *MF) {
1411 for (const auto &MI : MBB) {
1412 if (MI.isDebugValue()) {
1413 assert(MI.getNumOperands() > 1 && "Invalid machine instruction!");
1414 // Keep track of user variables in order of appearance. Create the
1415 // empty history for each variable so that the order of keys in
1416 // DbgValues is correct. Actual history will be populated in
1417 // calculateDbgValueHistory() function.
1418 const MDNode *Var = MI.getDebugVariable();
1420 std::make_pair(Var, SmallVector<const MachineInstr *, 4>()));
1421 } else if (!MI.getFlag(MachineInstr::FrameSetup) &&
1422 PrologEndLoc.isUnknown() && !MI.getDebugLoc().isUnknown()) {
1423 // First known non-DBG_VALUE and non-frame setup location marks
1424 // the beginning of the function body.
1425 PrologEndLoc = MI.getDebugLoc();
1430 // Calculate history for local variables.
1431 calculateDbgValueHistory(MF, Asm->TM.getRegisterInfo(), DbgValues);
1433 // Request labels for the full history.
1434 for (auto &I : DbgValues) {
1435 const SmallVectorImpl<const MachineInstr *> &History = I.second;
1436 if (History.empty())
1439 // The first mention of a function argument gets the FunctionBeginSym
1440 // label, so arguments are visible when breaking at function entry.
1441 DIVariable DV(I.first);
1442 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1443 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1444 LabelsBeforeInsn[History.front()] = FunctionBeginSym;
1446 for (const MachineInstr *MI : History) {
1447 if (MI->isDebugValue() && MI->getDebugVariable() == DV)
1448 requestLabelBeforeInsn(MI);
1450 requestLabelAfterInsn(MI);
1454 PrevInstLoc = DebugLoc();
1455 PrevLabel = FunctionBeginSym;
1457 // Record beginning of function.
1458 if (!PrologEndLoc.isUnknown()) {
1459 DebugLoc FnStartDL =
1460 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1462 FnStartDL.getLine(), FnStartDL.getCol(),
1463 FnStartDL.getScope(MF->getFunction()->getContext()),
1464 // We'd like to list the prologue as "not statements" but GDB behaves
1465 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1466 DWARF2_FLAG_IS_STMT);
1470 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1471 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1472 DIVariable DV = Var->getVariable();
1473 // Variables with positive arg numbers are parameters.
1474 if (unsigned ArgNum = DV.getArgNumber()) {
1475 // Keep all parameters in order at the start of the variable list to ensure
1476 // function types are correct (no out-of-order parameters)
1478 // This could be improved by only doing it for optimized builds (unoptimized
1479 // builds have the right order to begin with), searching from the back (this
1480 // would catch the unoptimized case quickly), or doing a binary search
1481 // rather than linear search.
1482 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1483 while (I != Vars.end()) {
1484 unsigned CurNum = (*I)->getVariable().getArgNumber();
1485 // A local (non-parameter) variable has been found, insert immediately
1489 // A later indexed parameter has been found, insert immediately before it.
1490 if (CurNum > ArgNum)
1494 Vars.insert(I, Var);
1498 Vars.push_back(Var);
1501 // Gather and emit post-function debug information.
1502 void DwarfDebug::endFunction(const MachineFunction *MF) {
1503 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1504 // though the beginFunction may not be called at all.
1505 // We should handle both cases.
1509 assert(CurFn == MF);
1510 assert(CurFn != nullptr);
1512 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1513 // If we don't have a lexical scope for this function then there will
1514 // be a hole in the range information. Keep note of this by setting the
1515 // previously used section to nullptr.
1516 PrevSection = nullptr;
1522 // Define end label for subprogram.
1523 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1524 // Assumes in correct section after the entry point.
1525 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1527 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1528 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1530 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1531 collectVariableInfo(ProcessedVars);
1533 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1534 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1536 // Construct abstract scopes.
1537 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1538 DISubprogram SP(AScope->getScopeNode());
1539 if (!SP.isSubprogram())
1541 // Collect info for variables that were optimized out.
1542 DIArray Variables = SP.getVariables();
1543 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1544 DIVariable DV(Variables.getElement(i));
1545 assert(DV && DV.isVariable());
1546 if (!ProcessedVars.insert(DV))
1548 findAbstractVariable(DV, DV.getContext());
1550 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1553 DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
1554 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1555 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1557 // Add the range of this function to the list of ranges for the CU.
1558 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1559 TheCU.addRange(std::move(Span));
1560 PrevSection = Asm->getCurrentSection();
1564 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1565 // DbgVariables except those that are also in AbstractVariables (since they
1566 // can be used cross-function)
1567 for (const auto &I : ScopeVariables)
1568 for (const auto *Var : I.second)
1569 if (!AbstractVariables.count(Var->getVariable()) || Var->getAbstractVariable())
1571 ScopeVariables.clear();
1572 DeleteContainerPointers(CurrentFnArguments);
1574 LabelsBeforeInsn.clear();
1575 LabelsAfterInsn.clear();
1576 PrevLabel = nullptr;
1580 // Register a source line with debug info. Returns the unique label that was
1581 // emitted and which provides correspondence to the source line list.
1582 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1587 unsigned Discriminator = 0;
1588 if (DIScope Scope = DIScope(S)) {
1589 assert(Scope.isScope());
1590 Fn = Scope.getFilename();
1591 Dir = Scope.getDirectory();
1592 if (Scope.isLexicalBlock())
1593 Discriminator = DILexicalBlock(S).getDiscriminator();
1595 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1596 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1597 .getOrCreateSourceID(Fn, Dir);
1599 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1603 //===----------------------------------------------------------------------===//
1605 //===----------------------------------------------------------------------===//
1607 // Emit initial Dwarf sections with a label at the start of each one.
1608 void DwarfDebug::emitSectionLabels() {
1609 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1611 // Dwarf sections base addresses.
1612 DwarfInfoSectionSym =
1613 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1614 if (useSplitDwarf())
1615 DwarfInfoDWOSectionSym =
1616 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1617 DwarfAbbrevSectionSym =
1618 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1619 if (useSplitDwarf())
1620 DwarfAbbrevDWOSectionSym = emitSectionSym(
1621 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1622 if (GenerateARangeSection)
1623 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1625 DwarfLineSectionSym =
1626 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1627 if (GenerateGnuPubSections) {
1628 DwarfGnuPubNamesSectionSym =
1629 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1630 DwarfGnuPubTypesSectionSym =
1631 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1632 } else if (HasDwarfPubSections) {
1633 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1634 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1637 DwarfStrSectionSym =
1638 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1639 if (useSplitDwarf()) {
1640 DwarfStrDWOSectionSym =
1641 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1642 DwarfAddrSectionSym =
1643 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1644 DwarfDebugLocSectionSym =
1645 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1647 DwarfDebugLocSectionSym =
1648 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1649 DwarfDebugRangeSectionSym =
1650 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1653 // Recursively emits a debug information entry.
1654 void DwarfDebug::emitDIE(DIE &Die) {
1655 // Get the abbreviation for this DIE.
1656 const DIEAbbrev &Abbrev = Die.getAbbrev();
1658 // Emit the code (index) for the abbreviation.
1659 if (Asm->isVerbose())
1660 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1661 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1662 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1663 dwarf::TagString(Abbrev.getTag()));
1664 Asm->EmitULEB128(Abbrev.getNumber());
1666 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1667 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1669 // Emit the DIE attribute values.
1670 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1671 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1672 dwarf::Form Form = AbbrevData[i].getForm();
1673 assert(Form && "Too many attributes for DIE (check abbreviation)");
1675 if (Asm->isVerbose()) {
1676 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1677 if (Attr == dwarf::DW_AT_accessibility)
1678 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1679 cast<DIEInteger>(Values[i])->getValue()));
1682 // Emit an attribute using the defined form.
1683 Values[i]->EmitValue(Asm, Form);
1686 // Emit the DIE children if any.
1687 if (Abbrev.hasChildren()) {
1688 for (auto &Child : Die.getChildren())
1691 Asm->OutStreamer.AddComment("End Of Children Mark");
1696 // Emit the debug info section.
1697 void DwarfDebug::emitDebugInfo() {
1698 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1700 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1703 // Emit the abbreviation section.
1704 void DwarfDebug::emitAbbreviations() {
1705 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1707 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1710 // Emit the last address of the section and the end of the line matrix.
1711 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1712 // Define last address of section.
1713 Asm->OutStreamer.AddComment("Extended Op");
1716 Asm->OutStreamer.AddComment("Op size");
1717 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1718 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1719 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1721 Asm->OutStreamer.AddComment("Section end label");
1723 Asm->OutStreamer.EmitSymbolValue(
1724 Asm->GetTempSymbol("section_end", SectionEnd),
1725 Asm->getDataLayout().getPointerSize());
1727 // Mark end of matrix.
1728 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1734 // Emit visible names into a hashed accelerator table section.
1735 void DwarfDebug::emitAccelNames() {
1736 AccelNames.FinalizeTable(Asm, "Names");
1737 Asm->OutStreamer.SwitchSection(
1738 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1739 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1740 Asm->OutStreamer.EmitLabel(SectionBegin);
1742 // Emit the full data.
1743 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1746 // Emit objective C classes and categories into a hashed accelerator table
1748 void DwarfDebug::emitAccelObjC() {
1749 AccelObjC.FinalizeTable(Asm, "ObjC");
1750 Asm->OutStreamer.SwitchSection(
1751 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1752 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1753 Asm->OutStreamer.EmitLabel(SectionBegin);
1755 // Emit the full data.
1756 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1759 // Emit namespace dies into a hashed accelerator table.
1760 void DwarfDebug::emitAccelNamespaces() {
1761 AccelNamespace.FinalizeTable(Asm, "namespac");
1762 Asm->OutStreamer.SwitchSection(
1763 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1764 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1765 Asm->OutStreamer.EmitLabel(SectionBegin);
1767 // Emit the full data.
1768 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1771 // Emit type dies into a hashed accelerator table.
1772 void DwarfDebug::emitAccelTypes() {
1774 AccelTypes.FinalizeTable(Asm, "types");
1775 Asm->OutStreamer.SwitchSection(
1776 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1777 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1778 Asm->OutStreamer.EmitLabel(SectionBegin);
1780 // Emit the full data.
1781 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1784 // Public name handling.
1785 // The format for the various pubnames:
1787 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1788 // for the DIE that is named.
1790 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1791 // into the CU and the index value is computed according to the type of value
1792 // for the DIE that is named.
1794 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1795 // it's the offset within the debug_info/debug_types dwo section, however, the
1796 // reference in the pubname header doesn't change.
1798 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1799 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1801 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1803 // We could have a specification DIE that has our most of our knowledge,
1804 // look for that now.
1805 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1807 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1808 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1809 Linkage = dwarf::GIEL_EXTERNAL;
1810 } else if (Die->findAttribute(dwarf::DW_AT_external))
1811 Linkage = dwarf::GIEL_EXTERNAL;
1813 switch (Die->getTag()) {
1814 case dwarf::DW_TAG_class_type:
1815 case dwarf::DW_TAG_structure_type:
1816 case dwarf::DW_TAG_union_type:
1817 case dwarf::DW_TAG_enumeration_type:
1818 return dwarf::PubIndexEntryDescriptor(
1819 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1820 ? dwarf::GIEL_STATIC
1821 : dwarf::GIEL_EXTERNAL);
1822 case dwarf::DW_TAG_typedef:
1823 case dwarf::DW_TAG_base_type:
1824 case dwarf::DW_TAG_subrange_type:
1825 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1826 case dwarf::DW_TAG_namespace:
1827 return dwarf::GIEK_TYPE;
1828 case dwarf::DW_TAG_subprogram:
1829 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1830 case dwarf::DW_TAG_constant:
1831 case dwarf::DW_TAG_variable:
1832 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1833 case dwarf::DW_TAG_enumerator:
1834 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1835 dwarf::GIEL_STATIC);
1837 return dwarf::GIEK_NONE;
1841 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1843 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1844 const MCSection *PSec =
1845 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1846 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1848 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1851 void DwarfDebug::emitDebugPubSection(
1852 bool GnuStyle, const MCSection *PSec, StringRef Name,
1853 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1854 for (const auto &NU : CUMap) {
1855 DwarfCompileUnit *TheU = NU.second;
1857 const auto &Globals = (TheU->*Accessor)();
1859 if (Globals.empty())
1862 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1864 unsigned ID = TheU->getUniqueID();
1866 // Start the dwarf pubnames section.
1867 Asm->OutStreamer.SwitchSection(PSec);
1870 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1871 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1872 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1873 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1875 Asm->OutStreamer.EmitLabel(BeginLabel);
1877 Asm->OutStreamer.AddComment("DWARF Version");
1878 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1880 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1881 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1883 Asm->OutStreamer.AddComment("Compilation Unit Length");
1884 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1886 // Emit the pubnames for this compilation unit.
1887 for (const auto &GI : Globals) {
1888 const char *Name = GI.getKeyData();
1889 const DIE *Entity = GI.second;
1891 Asm->OutStreamer.AddComment("DIE offset");
1892 Asm->EmitInt32(Entity->getOffset());
1895 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1896 Asm->OutStreamer.AddComment(
1897 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1898 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1899 Asm->EmitInt8(Desc.toBits());
1902 Asm->OutStreamer.AddComment("External Name");
1903 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1906 Asm->OutStreamer.AddComment("End Mark");
1908 Asm->OutStreamer.EmitLabel(EndLabel);
1912 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1913 const MCSection *PSec =
1914 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1915 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1917 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1920 // Emit visible names into a debug str section.
1921 void DwarfDebug::emitDebugStr() {
1922 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1923 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1926 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1927 const DebugLocEntry &Entry) {
1928 assert(Entry.getValues().size() == 1 &&
1929 "multi-value entries are not supported yet.");
1930 const DebugLocEntry::Value Value = Entry.getValues()[0];
1931 DIVariable DV(Value.getVariable());
1932 if (Value.isInt()) {
1933 DIBasicType BTy(resolve(DV.getType()));
1934 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1935 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1936 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1937 Streamer.EmitSLEB128(Value.getInt());
1939 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1940 Streamer.EmitULEB128(Value.getInt());
1942 } else if (Value.isLocation()) {
1943 MachineLocation Loc = Value.getLoc();
1944 if (!DV.hasComplexAddress())
1946 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1948 // Complex address entry.
1949 unsigned N = DV.getNumAddrElements();
1951 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1952 if (Loc.getOffset()) {
1954 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1955 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1956 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1957 Streamer.EmitSLEB128(DV.getAddrElement(1));
1959 // If first address element is OpPlus then emit
1960 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1961 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
1962 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1966 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1969 // Emit remaining complex address elements.
1970 for (; i < N; ++i) {
1971 uint64_t Element = DV.getAddrElement(i);
1972 if (Element == DIBuilder::OpPlus) {
1973 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1974 Streamer.EmitULEB128(DV.getAddrElement(++i));
1975 } else if (Element == DIBuilder::OpDeref) {
1977 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1979 llvm_unreachable("unknown Opcode found in complex address");
1983 // else ... ignore constant fp. There is not any good way to
1984 // to represent them here in dwarf.
1988 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1989 Asm->OutStreamer.AddComment("Loc expr size");
1990 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1991 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1992 Asm->EmitLabelDifference(end, begin, 2);
1993 Asm->OutStreamer.EmitLabel(begin);
1995 APByteStreamer Streamer(*Asm);
1996 emitDebugLocEntry(Streamer, Entry);
1998 Asm->OutStreamer.EmitLabel(end);
2001 // Emit locations into the debug loc section.
2002 void DwarfDebug::emitDebugLoc() {
2003 // Start the dwarf loc section.
2004 Asm->OutStreamer.SwitchSection(
2005 Asm->getObjFileLowering().getDwarfLocSection());
2006 unsigned char Size = Asm->getDataLayout().getPointerSize();
2007 for (const auto &DebugLoc : DotDebugLocEntries) {
2008 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2009 for (const auto &Entry : DebugLoc.List) {
2010 // Set up the range. This range is relative to the entry point of the
2011 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2012 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2013 const DwarfCompileUnit *CU = Entry.getCU();
2014 if (CU->getRanges().size() == 1) {
2015 // Grab the begin symbol from the first range as our base.
2016 const MCSymbol *Base = CU->getRanges()[0].getStart();
2017 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2018 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2020 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2021 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2024 emitDebugLocEntryLocation(Entry);
2026 Asm->OutStreamer.EmitIntValue(0, Size);
2027 Asm->OutStreamer.EmitIntValue(0, Size);
2031 void DwarfDebug::emitDebugLocDWO() {
2032 Asm->OutStreamer.SwitchSection(
2033 Asm->getObjFileLowering().getDwarfLocDWOSection());
2034 for (const auto &DebugLoc : DotDebugLocEntries) {
2035 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2036 for (const auto &Entry : DebugLoc.List) {
2037 // Just always use start_length for now - at least that's one address
2038 // rather than two. We could get fancier and try to, say, reuse an
2039 // address we know we've emitted elsewhere (the start of the function?
2040 // The start of the CU or CU subrange that encloses this range?)
2041 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2042 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2043 Asm->EmitULEB128(idx);
2044 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2046 emitDebugLocEntryLocation(Entry);
2048 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2053 const MCSymbol *Start, *End;
2056 // Emit a debug aranges section, containing a CU lookup for any
2057 // address we can tie back to a CU.
2058 void DwarfDebug::emitDebugARanges() {
2059 // Start the dwarf aranges section.
2060 Asm->OutStreamer.SwitchSection(
2061 Asm->getObjFileLowering().getDwarfARangesSection());
2063 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2067 // Build a list of sections used.
2068 std::vector<const MCSection *> Sections;
2069 for (const auto &it : SectionMap) {
2070 const MCSection *Section = it.first;
2071 Sections.push_back(Section);
2074 // Sort the sections into order.
2075 // This is only done to ensure consistent output order across different runs.
2076 std::sort(Sections.begin(), Sections.end(), SectionSort);
2078 // Build a set of address spans, sorted by CU.
2079 for (const MCSection *Section : Sections) {
2080 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2081 if (List.size() < 2)
2084 // Sort the symbols by offset within the section.
2085 std::sort(List.begin(), List.end(),
2086 [&](const SymbolCU &A, const SymbolCU &B) {
2087 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2088 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2090 // Symbols with no order assigned should be placed at the end.
2091 // (e.g. section end labels)
2099 // If we have no section (e.g. common), just write out
2100 // individual spans for each symbol.
2102 for (const SymbolCU &Cur : List) {
2104 Span.Start = Cur.Sym;
2107 Spans[Cur.CU].push_back(Span);
2110 // Build spans between each label.
2111 const MCSymbol *StartSym = List[0].Sym;
2112 for (size_t n = 1, e = List.size(); n < e; n++) {
2113 const SymbolCU &Prev = List[n - 1];
2114 const SymbolCU &Cur = List[n];
2116 // Try and build the longest span we can within the same CU.
2117 if (Cur.CU != Prev.CU) {
2119 Span.Start = StartSym;
2121 Spans[Prev.CU].push_back(Span);
2128 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2130 // Build a list of CUs used.
2131 std::vector<DwarfCompileUnit *> CUs;
2132 for (const auto &it : Spans) {
2133 DwarfCompileUnit *CU = it.first;
2137 // Sort the CU list (again, to ensure consistent output order).
2138 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2139 return A->getUniqueID() < B->getUniqueID();
2142 // Emit an arange table for each CU we used.
2143 for (DwarfCompileUnit *CU : CUs) {
2144 std::vector<ArangeSpan> &List = Spans[CU];
2146 // Emit size of content not including length itself.
2147 unsigned ContentSize =
2148 sizeof(int16_t) + // DWARF ARange version number
2149 sizeof(int32_t) + // Offset of CU in the .debug_info section
2150 sizeof(int8_t) + // Pointer Size (in bytes)
2151 sizeof(int8_t); // Segment Size (in bytes)
2153 unsigned TupleSize = PtrSize * 2;
2155 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2157 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2159 ContentSize += Padding;
2160 ContentSize += (List.size() + 1) * TupleSize;
2162 // For each compile unit, write the list of spans it covers.
2163 Asm->OutStreamer.AddComment("Length of ARange Set");
2164 Asm->EmitInt32(ContentSize);
2165 Asm->OutStreamer.AddComment("DWARF Arange version number");
2166 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2167 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2168 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2169 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2170 Asm->EmitInt8(PtrSize);
2171 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2174 Asm->OutStreamer.EmitFill(Padding, 0xff);
2176 for (const ArangeSpan &Span : List) {
2177 Asm->EmitLabelReference(Span.Start, PtrSize);
2179 // Calculate the size as being from the span start to it's end.
2181 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2183 // For symbols without an end marker (e.g. common), we
2184 // write a single arange entry containing just that one symbol.
2185 uint64_t Size = SymSize[Span.Start];
2189 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2193 Asm->OutStreamer.AddComment("ARange terminator");
2194 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2195 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2199 // Emit visible names into a debug ranges section.
2200 void DwarfDebug::emitDebugRanges() {
2201 // Start the dwarf ranges section.
2202 Asm->OutStreamer.SwitchSection(
2203 Asm->getObjFileLowering().getDwarfRangesSection());
2205 // Size for our labels.
2206 unsigned char Size = Asm->getDataLayout().getPointerSize();
2208 // Grab the specific ranges for the compile units in the module.
2209 for (const auto &I : CUMap) {
2210 DwarfCompileUnit *TheCU = I.second;
2212 // Iterate over the misc ranges for the compile units in the module.
2213 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2214 // Emit our symbol so we can find the beginning of the range.
2215 Asm->OutStreamer.EmitLabel(List.getSym());
2217 for (const RangeSpan &Range : List.getRanges()) {
2218 const MCSymbol *Begin = Range.getStart();
2219 const MCSymbol *End = Range.getEnd();
2220 assert(Begin && "Range without a begin symbol?");
2221 assert(End && "Range without an end symbol?");
2222 if (TheCU->getRanges().size() == 1) {
2223 // Grab the begin symbol from the first range as our base.
2224 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2225 Asm->EmitLabelDifference(Begin, Base, Size);
2226 Asm->EmitLabelDifference(End, Base, Size);
2228 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2229 Asm->OutStreamer.EmitSymbolValue(End, Size);
2233 // And terminate the list with two 0 values.
2234 Asm->OutStreamer.EmitIntValue(0, Size);
2235 Asm->OutStreamer.EmitIntValue(0, Size);
2238 // Now emit a range for the CU itself.
2239 if (TheCU->getRanges().size() > 1) {
2240 Asm->OutStreamer.EmitLabel(
2241 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2242 for (const RangeSpan &Range : TheCU->getRanges()) {
2243 const MCSymbol *Begin = Range.getStart();
2244 const MCSymbol *End = Range.getEnd();
2245 assert(Begin && "Range without a begin symbol?");
2246 assert(End && "Range without an end symbol?");
2247 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2248 Asm->OutStreamer.EmitSymbolValue(End, Size);
2250 // And terminate the list with two 0 values.
2251 Asm->OutStreamer.EmitIntValue(0, Size);
2252 Asm->OutStreamer.EmitIntValue(0, Size);
2257 // DWARF5 Experimental Separate Dwarf emitters.
2259 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2260 std::unique_ptr<DwarfUnit> NewU) {
2261 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2262 U.getCUNode().getSplitDebugFilename());
2264 if (!CompilationDir.empty())
2265 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2267 addGnuPubAttributes(*NewU, Die);
2269 SkeletonHolder.addUnit(std::move(NewU));
2272 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2273 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2274 // DW_AT_addr_base, DW_AT_ranges_base.
2275 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2277 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2278 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2279 DwarfCompileUnit &NewCU = *OwnedUnit;
2280 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2281 DwarfInfoSectionSym);
2283 NewCU.initStmtList(DwarfLineSectionSym);
2285 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2290 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2292 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2293 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2294 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2296 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), CU, Asm, this,
2298 DwarfTypeUnit &NewTU = *OwnedUnit;
2299 NewTU.setTypeSignature(TU.getTypeSignature());
2300 NewTU.setType(nullptr);
2302 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2304 initSkeletonUnit(TU, NewTU.getUnitDie(), std::move(OwnedUnit));
2308 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2309 // compile units that would normally be in debug_info.
2310 void DwarfDebug::emitDebugInfoDWO() {
2311 assert(useSplitDwarf() && "No split dwarf debug info?");
2312 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2313 // emit relocations into the dwo file.
2314 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2317 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2318 // abbreviations for the .debug_info.dwo section.
2319 void DwarfDebug::emitDebugAbbrevDWO() {
2320 assert(useSplitDwarf() && "No split dwarf?");
2321 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2324 void DwarfDebug::emitDebugLineDWO() {
2325 assert(useSplitDwarf() && "No split dwarf?");
2326 Asm->OutStreamer.SwitchSection(
2327 Asm->getObjFileLowering().getDwarfLineDWOSection());
2328 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2331 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2332 // string section and is identical in format to traditional .debug_str
2334 void DwarfDebug::emitDebugStrDWO() {
2335 assert(useSplitDwarf() && "No split dwarf?");
2336 const MCSection *OffSec =
2337 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2338 const MCSymbol *StrSym = DwarfStrSectionSym;
2339 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2343 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2344 if (!useSplitDwarf())
2347 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2348 return &SplitTypeUnitFileTable;
2351 static uint64_t makeTypeSignature(StringRef Identifier) {
2353 Hash.update(Identifier);
2354 // ... take the least significant 8 bytes and return those. Our MD5
2355 // implementation always returns its results in little endian, swap bytes
2357 MD5::MD5Result Result;
2359 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2362 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2363 StringRef Identifier, DIE &RefDie,
2364 DICompositeType CTy) {
2365 // Fast path if we're building some type units and one has already used the
2366 // address pool we know we're going to throw away all this work anyway, so
2367 // don't bother building dependent types.
2368 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2371 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2373 CU.addDIETypeSignature(RefDie, *TU);
2377 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2378 AddrPool.resetUsedFlag();
2381 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), CU, Asm, this,
2382 &InfoHolder, getDwoLineTable(CU));
2383 DwarfTypeUnit &NewTU = *OwnedUnit;
2384 DIE &UnitDie = NewTU.getUnitDie();
2386 TypeUnitsUnderConstruction.push_back(
2387 std::make_pair(std::move(OwnedUnit), CTy));
2389 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2392 uint64_t Signature = makeTypeSignature(Identifier);
2393 NewTU.setTypeSignature(Signature);
2395 if (!useSplitDwarf())
2396 CU.applyStmtList(UnitDie);
2398 // FIXME: Skip using COMDAT groups for type units in the .dwo file once tools
2399 // such as DWP ( http://gcc.gnu.org/wiki/DebugFissionDWP ) can cope with it.
2402 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2403 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2405 NewTU.setType(NewTU.createTypeDIE(CTy));
2408 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2409 TypeUnitsUnderConstruction.clear();
2411 // Types referencing entries in the address table cannot be placed in type
2413 if (AddrPool.hasBeenUsed()) {
2415 // Remove all the types built while building this type.
2416 // This is pessimistic as some of these types might not be dependent on
2417 // the type that used an address.
2418 for (const auto &TU : TypeUnitsToAdd)
2419 DwarfTypeUnits.erase(TU.second);
2421 // Construct this type in the CU directly.
2422 // This is inefficient because all the dependent types will be rebuilt
2423 // from scratch, including building them in type units, discovering that
2424 // they depend on addresses, throwing them out and rebuilding them.
2425 CU.constructTypeDIE(RefDie, CTy);
2429 // If the type wasn't dependent on fission addresses, finish adding the type
2430 // and all its dependent types.
2431 for (auto &TU : TypeUnitsToAdd) {
2432 if (useSplitDwarf())
2433 TU.first->setSkeleton(constructSkeletonTU(*TU.first));
2434 InfoHolder.addUnit(std::move(TU.first));
2437 CU.addDIETypeSignature(RefDie, NewTU);
2440 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2441 MCSymbol *Begin, MCSymbol *End) {
2442 assert(Begin && "Begin label should not be null!");
2443 assert(End && "End label should not be null!");
2444 assert(Begin->isDefined() && "Invalid starting label");
2445 assert(End->isDefined() && "Invalid end label");
2447 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2448 if (DwarfVersion < 4)
2449 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2451 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2454 // Accelerator table mutators - add each name along with its companion
2455 // DIE to the proper table while ensuring that the name that we're going
2456 // to reference is in the string table. We do this since the names we
2457 // add may not only be identical to the names in the DIE.
2458 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2459 if (!useDwarfAccelTables())
2461 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2465 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2466 if (!useDwarfAccelTables())
2468 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2472 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2473 if (!useDwarfAccelTables())
2475 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2479 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2480 if (!useDwarfAccelTables())
2482 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),