1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "ByteStreamer.h"
15 #include "DwarfDebug.h"
18 #include "DwarfUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DIBuilder.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MD5.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
52 #define DEBUG_TYPE "dwarfdebug"
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
70 cl::desc("Generate dwarf aranges"),
74 enum DefaultOnOff { Default, Enable, Disable };
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113 return DD->resolve(Ref);
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type)
154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156 DIArray Elements = DICompositeType(subType).getTypeArray();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
173 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, "skel_string", DIEValueAllocator),
176 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
177 dwarf::DW_FORM_data4)),
178 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
179 dwarf::DW_FORM_data4)),
180 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
181 dwarf::DW_FORM_data4)),
182 AccelTypes(TypeAtoms) {
184 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
185 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
186 DwarfLineSectionSym = nullptr;
187 DwarfAddrSectionSym = nullptr;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
189 FunctionBeginSym = FunctionEndSym = nullptr;
193 // Turn on accelerator tables for Darwin by default, pubnames by
194 // default for non-Darwin, and handle split dwarf.
195 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
197 if (DwarfAccelTables == Default)
198 HasDwarfAccelTables = IsDarwin;
200 HasDwarfAccelTables = DwarfAccelTables == Enable;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable;
207 if (DwarfPubSections == Default)
208 HasDwarfPubSections = !IsDarwin;
210 HasDwarfPubSections = DwarfPubSections == Enable;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
216 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
221 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
222 DwarfDebug::~DwarfDebug() { }
224 // Switch to the specified MCSection and emit an assembler
225 // temporary label to it if SymbolStem is specified.
226 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
227 const char *SymbolStem = nullptr) {
228 Asm->OutStreamer.SwitchSection(Section);
232 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
233 Asm->OutStreamer.EmitLabel(TmpSym);
237 static bool isObjCClass(StringRef Name) {
238 return Name.startswith("+") || Name.startswith("-");
241 static bool hasObjCCategory(StringRef Name) {
242 if (!isObjCClass(Name))
245 return Name.find(") ") != StringRef::npos;
248 static void getObjCClassCategory(StringRef In, StringRef &Class,
249 StringRef &Category) {
250 if (!hasObjCCategory(In)) {
251 Class = In.slice(In.find('[') + 1, In.find(' '));
256 Class = In.slice(In.find('[') + 1, In.find('('));
257 Category = In.slice(In.find('[') + 1, In.find(' '));
261 static StringRef getObjCMethodName(StringRef In) {
262 return In.slice(In.find(' ') + 1, In.find(']'));
265 // Helper for sorting sections into a stable output order.
266 static bool SectionSort(const MCSection *A, const MCSection *B) {
267 std::string LA = (A ? A->getLabelBeginName() : "");
268 std::string LB = (B ? B->getLabelBeginName() : "");
272 // Add the various names to the Dwarf accelerator table names.
273 // TODO: Determine whether or not we should add names for programs
274 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
275 // is only slightly different than the lookup of non-standard ObjC names.
276 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
277 if (!SP.isDefinition())
279 addAccelName(SP.getName(), Die);
281 // If the linkage name is different than the name, go ahead and output
282 // that as well into the name table.
283 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
284 addAccelName(SP.getLinkageName(), Die);
286 // If this is an Objective-C selector name add it to the ObjC accelerator
288 if (isObjCClass(SP.getName())) {
289 StringRef Class, Category;
290 getObjCClassCategory(SP.getName(), Class, Category);
291 addAccelObjC(Class, Die);
293 addAccelObjC(Category, Die);
294 // Also add the base method name to the name table.
295 addAccelName(getObjCMethodName(SP.getName()), Die);
299 /// isSubprogramContext - Return true if Context is either a subprogram
300 /// or another context nested inside a subprogram.
301 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
304 DIDescriptor D(Context);
305 if (D.isSubprogram())
308 return isSubprogramContext(resolve(DIType(Context).getContext()));
312 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
313 // and DW_AT_high_pc attributes. If there are global variables in this
314 // scope then create and insert DIEs for these variables.
315 DIE &DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
317 DIE *SPDie = SPCU.getDIE(SP);
319 assert(SPDie && "Unable to find subprogram DIE!");
321 // If we're updating an abstract DIE, then we will be adding the children and
322 // object pointer later on. But what we don't want to do is process the
323 // concrete DIE twice.
324 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
325 assert(SPDie == AbsSPDIE);
326 // Pick up abstract subprogram DIE.
327 SPDie = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
328 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
329 } else if (!SP.getFunctionDeclaration()) {
330 // There is not any need to generate specification DIE for a function
331 // defined at compile unit level. If a function is defined inside another
332 // function then gdb prefers the definition at top level and but does not
333 // expect specification DIE in parent function. So avoid creating
334 // specification DIE for a function defined inside a function.
335 DIScope SPContext = resolve(SP.getContext());
336 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
337 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
338 SPCU.addFlag(*SPDie, dwarf::DW_AT_declaration);
341 DICompositeType SPTy = SP.getType();
342 DIArray Args = SPTy.getTypeArray();
343 uint16_t SPTag = SPTy.getTag();
344 if (SPTag == dwarf::DW_TAG_subroutine_type)
345 SPCU.constructSubprogramArguments(*SPDie, Args);
346 DIE *SPDeclDie = SPDie;
348 &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
349 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_specification, *SPDeclDie);
353 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
355 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
356 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
357 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
359 // Add name to the name table, we do this here because we're guaranteed
360 // to have concrete versions of our DW_TAG_subprogram nodes.
361 addSubprogramNames(SP, *SPDie);
366 /// Check whether we should create a DIE for the given Scope, return true
367 /// if we don't create a DIE (the corresponding DIE is null).
368 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
369 if (Scope->isAbstractScope())
372 // We don't create a DIE if there is no Range.
373 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
377 if (Ranges.size() > 1)
380 // We don't create a DIE if we have a single Range and the end label
382 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
383 MCSymbol *End = getLabelAfterInsn(RI->second);
387 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
388 dwarf::Attribute A, const MCSymbol *L,
389 const MCSymbol *Sec) {
390 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
391 U.addSectionLabel(D, A, L);
393 U.addSectionDelta(D, A, L, Sec);
396 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
397 const SmallVectorImpl<InsnRange> &Range) {
398 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
399 // emitting it appropriately.
400 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
402 // Under fission, ranges are specified by constant offsets relative to the
403 // CU's DW_AT_GNU_ranges_base.
405 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
406 DwarfDebugRangeSectionSym);
408 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
409 DwarfDebugRangeSectionSym);
411 RangeSpanList List(RangeSym);
412 for (const InsnRange &R : Range) {
413 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
414 List.addRange(std::move(Span));
417 // Add the range list to the set of ranges to be emitted.
418 TheCU.addRangeList(std::move(List));
421 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
422 const SmallVectorImpl<InsnRange> &Ranges) {
423 assert(!Ranges.empty());
424 if (Ranges.size() == 1)
425 attachLowHighPC(TheCU, Die, getLabelBeforeInsn(Ranges.front().first),
426 getLabelAfterInsn(Ranges.front().second));
428 addScopeRangeList(TheCU, Die, Ranges);
431 // Construct new DW_TAG_lexical_block for this scope and attach
432 // DW_AT_low_pc/DW_AT_high_pc labels.
434 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
435 LexicalScope *Scope) {
436 if (isLexicalScopeDIENull(Scope))
439 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
440 if (Scope->isAbstractScope())
443 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
448 // This scope represents inlined body of a function. Construct DIE to
449 // represent this concrete inlined copy of the function.
451 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
452 LexicalScope *Scope) {
453 assert(Scope->getScopeNode());
454 DIScope DS(Scope->getScopeNode());
455 DISubprogram InlinedSP = getDISubprogram(DS);
456 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
457 // FIXME: This should be an assert (or possibly a
458 // getOrCreateSubprogram(InlinedSP)) otherwise we're just failing to emit
459 // inlining information.
461 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
465 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
466 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
468 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
470 InlinedSubprogramDIEs.insert(OriginDIE);
471 TheCU.addUInt(*OriginDIE, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
473 // Add the call site information to the DIE.
474 DILocation DL(Scope->getInlinedAt());
475 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
476 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
477 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
479 // Add name to the name table, we do this here because we're guaranteed
480 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
481 addSubprogramNames(InlinedSP, *ScopeDIE);
486 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
488 const LexicalScope &Scope,
489 DIE *&ObjectPointer) {
490 AbstractOrInlined AOI = AOI_None;
491 if (Scope.isAbstractScope())
493 else if (Scope.getInlinedAt())
495 auto Var = TheCU.constructVariableDIE(DV, AOI);
496 if (DV.isObjectPointer())
497 ObjectPointer = Var.get();
501 DIE *DwarfDebug::createScopeChildrenDIE(
502 DwarfCompileUnit &TheCU, LexicalScope *Scope,
503 SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
504 DIE *ObjectPointer = nullptr;
506 // Collect arguments for current function.
507 if (LScopes.isCurrentFunctionScope(Scope)) {
508 for (DbgVariable *ArgDV : CurrentFnArguments)
511 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
513 // If this is a variadic function, add an unspecified parameter.
514 DISubprogram SP(Scope->getScopeNode());
515 DIArray FnArgs = SP.getType().getTypeArray();
516 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
517 .isUnspecifiedParameter()) {
519 make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
523 // Collect lexical scope children first.
524 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
525 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
527 for (LexicalScope *LS : Scope->getChildren())
528 if (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
529 Children.push_back(std::move(Nested));
530 return ObjectPointer;
533 void DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
534 LexicalScope *Scope, DIE &ScopeDIE) {
535 // We create children when the scope DIE is not null.
536 SmallVector<std::unique_ptr<DIE>, 8> Children;
537 if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
538 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
541 for (auto &I : Children)
542 ScopeDIE.addChild(std::move(I));
545 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
546 LexicalScope *Scope) {
547 assert(Scope && Scope->getScopeNode());
548 assert(Scope->isAbstractScope());
549 assert(!Scope->getInlinedAt());
551 DISubprogram Sub(Scope->getScopeNode());
553 if (!ProcessedSPNodes.insert(Sub))
556 if (DIE *ScopeDIE = TheCU.getDIE(Sub)) {
557 AbstractSPDies.insert(std::make_pair(Sub, ScopeDIE));
558 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
559 createAndAddScopeChildren(TheCU, Scope, *ScopeDIE);
563 DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
564 LexicalScope *Scope) {
565 assert(Scope && Scope->getScopeNode());
566 assert(!Scope->getInlinedAt());
567 assert(!Scope->isAbstractScope());
568 DISubprogram Sub(Scope->getScopeNode());
570 assert(Sub.isSubprogram());
572 ProcessedSPNodes.insert(Sub);
574 DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
576 createAndAddScopeChildren(TheCU, Scope, ScopeDIE);
581 // Construct a DIE for this scope.
582 std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
583 LexicalScope *Scope) {
584 if (!Scope || !Scope->getScopeNode())
587 DIScope DS(Scope->getScopeNode());
589 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
590 "Only handle inlined subprograms here, use "
591 "constructSubprogramScopeDIE for non-inlined "
594 SmallVector<std::unique_ptr<DIE>, 8> Children;
596 // We try to create the scope DIE first, then the children DIEs. This will
597 // avoid creating un-used children then removing them later when we find out
598 // the scope DIE is null.
599 std::unique_ptr<DIE> ScopeDIE;
600 if (DS.getContext() && DS.isSubprogram()) {
601 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
604 // We create children when the scope DIE is not null.
605 createScopeChildrenDIE(TheCU, Scope, Children);
607 // Early exit when we know the scope DIE is going to be null.
608 if (isLexicalScopeDIENull(Scope))
611 // We create children here when we know the scope DIE is not going to be
612 // null and the children will be added to the scope DIE.
613 createScopeChildrenDIE(TheCU, Scope, Children);
615 // There is no need to emit empty lexical block DIE.
616 std::pair<ImportedEntityMap::const_iterator,
617 ImportedEntityMap::const_iterator> Range =
618 std::equal_range(ScopesWithImportedEntities.begin(),
619 ScopesWithImportedEntities.end(),
620 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
622 if (Children.empty() && Range.first == Range.second)
624 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
625 assert(ScopeDIE && "Scope DIE should not be null.");
626 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
628 constructImportedEntityDIE(TheCU, i->second, *ScopeDIE);
632 for (auto &I : Children)
633 ScopeDIE->addChild(std::move(I));
638 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
639 if (!GenerateGnuPubSections)
642 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
645 // Create new DwarfCompileUnit for the given metadata node with tag
646 // DW_TAG_compile_unit.
647 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
648 StringRef FN = DIUnit.getFilename();
649 CompilationDir = DIUnit.getDirectory();
651 auto OwnedUnit = make_unique<DwarfCompileUnit>(
652 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
653 DwarfCompileUnit &NewCU = *OwnedUnit;
654 DIE &Die = NewCU.getUnitDie();
655 InfoHolder.addUnit(std::move(OwnedUnit));
657 // LTO with assembly output shares a single line table amongst multiple CUs.
658 // To avoid the compilation directory being ambiguous, let the line table
659 // explicitly describe the directory of all files, never relying on the
660 // compilation directory.
661 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
662 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
663 NewCU.getUniqueID(), CompilationDir);
665 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
666 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
667 DIUnit.getLanguage());
668 NewCU.addString(Die, dwarf::DW_AT_name, FN);
670 if (!useSplitDwarf()) {
671 NewCU.initStmtList(DwarfLineSectionSym);
673 // If we're using split dwarf the compilation dir is going to be in the
674 // skeleton CU and so we don't need to duplicate it here.
675 if (!CompilationDir.empty())
676 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
678 addGnuPubAttributes(NewCU, Die);
681 if (DIUnit.isOptimized())
682 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
684 StringRef Flags = DIUnit.getFlags();
686 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
688 if (unsigned RVer = DIUnit.getRunTimeVersion())
689 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
690 dwarf::DW_FORM_data1, RVer);
695 if (useSplitDwarf()) {
696 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
697 DwarfInfoDWOSectionSym);
698 NewCU.setSkeleton(constructSkeletonCU(NewCU));
700 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
701 DwarfInfoSectionSym);
703 CUMap.insert(std::make_pair(DIUnit, &NewCU));
704 CUDieMap.insert(std::make_pair(&Die, &NewCU));
708 // Construct subprogram DIE.
709 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
711 // FIXME: We should only call this routine once, however, during LTO if a
712 // program is defined in multiple CUs we could end up calling it out of
713 // beginModule as we walk the CUs.
715 DwarfCompileUnit *&CURef = SPMap[N];
721 assert(SP.isSubprogram());
722 assert(SP.isDefinition());
724 DIE &SubprogramDie = *TheCU.getOrCreateSubprogramDIE(SP);
726 // Expose as a global name.
727 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
730 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
732 DIImportedEntity Module(N);
733 assert(Module.Verify());
734 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
735 constructImportedEntityDIE(TheCU, Module, *D);
738 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
739 const MDNode *N, DIE &Context) {
740 DIImportedEntity Module(N);
741 assert(Module.Verify());
742 return constructImportedEntityDIE(TheCU, Module, Context);
745 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
746 const DIImportedEntity &Module,
748 assert(Module.Verify() &&
749 "Use one of the MDNode * overloads to handle invalid metadata");
750 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), Context, Module);
752 DIDescriptor Entity = resolve(Module.getEntity());
753 if (Entity.isNameSpace())
754 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
755 else if (Entity.isSubprogram())
756 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
757 else if (Entity.isType())
758 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
760 EntityDie = TheCU.getDIE(Entity);
761 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
762 Module.getContext().getFilename(),
763 Module.getContext().getDirectory());
764 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
765 StringRef Name = Module.getName();
767 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
770 // Emit all Dwarf sections that should come prior to the content. Create
771 // global DIEs and emit initial debug info sections. This is invoked by
772 // the target AsmPrinter.
773 void DwarfDebug::beginModule() {
774 if (DisableDebugInfoPrinting)
777 const Module *M = MMI->getModule();
779 // If module has named metadata anchors then use them, otherwise scan the
780 // module using debug info finder to collect debug info.
781 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
784 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
786 // Emit initial sections so we can reference labels later.
789 SingleCU = CU_Nodes->getNumOperands() == 1;
791 for (MDNode *N : CU_Nodes->operands()) {
792 DICompileUnit CUNode(N);
793 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
794 DIArray ImportedEntities = CUNode.getImportedEntities();
795 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
796 ScopesWithImportedEntities.push_back(std::make_pair(
797 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
798 ImportedEntities.getElement(i)));
799 std::sort(ScopesWithImportedEntities.begin(),
800 ScopesWithImportedEntities.end(), less_first());
801 DIArray GVs = CUNode.getGlobalVariables();
802 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
803 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
804 DIArray SPs = CUNode.getSubprograms();
805 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
806 constructSubprogramDIE(CU, SPs.getElement(i));
807 DIArray EnumTypes = CUNode.getEnumTypes();
808 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
809 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
810 DIArray RetainedTypes = CUNode.getRetainedTypes();
811 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
812 DIType Ty(RetainedTypes.getElement(i));
813 // The retained types array by design contains pointers to
814 // MDNodes rather than DIRefs. Unique them here.
815 DIType UniqueTy(resolve(Ty.getRef()));
816 CU.getOrCreateTypeDIE(UniqueTy);
818 // Emit imported_modules last so that the relevant context is already
820 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
821 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
824 // Tell MMI that we have debug info.
825 MMI->setDebugInfoAvailability(true);
827 // Prime section data.
828 SectionMap[Asm->getObjFileLowering().getTextSection()];
831 // Collect info for variables that were optimized out.
832 void DwarfDebug::collectDeadVariables() {
833 const Module *M = MMI->getModule();
835 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
836 for (MDNode *N : CU_Nodes->operands()) {
837 DICompileUnit TheCU(N);
838 // Construct subprogram DIE and add variables DIEs.
839 DwarfCompileUnit *SPCU =
840 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
841 assert(SPCU && "Unable to find Compile Unit!");
842 DIArray Subprograms = TheCU.getSubprograms();
843 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
844 DISubprogram SP(Subprograms.getElement(i));
845 if (ProcessedSPNodes.count(SP) != 0)
847 assert(SP.isSubprogram() &&
848 "CU's subprogram list contains a non-subprogram");
849 assert(SP.isDefinition() &&
850 "CU's subprogram list contains a subprogram declaration");
851 DIArray Variables = SP.getVariables();
852 if (Variables.getNumElements() == 0)
855 // FIXME: See the comment in constructSubprogramDIE about duplicate
857 constructSubprogramDIE(*SPCU, SP);
858 DIE *SPDIE = SPCU->getDIE(SP);
859 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
860 DIVariable DV(Variables.getElement(vi));
861 assert(DV.isVariable());
862 DbgVariable NewVar(DV, nullptr, this);
863 SPDIE->addChild(SPCU->constructVariableDIE(NewVar));
870 void DwarfDebug::finalizeModuleInfo() {
871 // Collect info for variables that were optimized out.
872 collectDeadVariables();
874 // Handle anything that needs to be done on a per-unit basis after
875 // all other generation.
876 for (const auto &TheU : getUnits()) {
877 // Emit DW_AT_containing_type attribute to connect types with their
878 // vtable holding type.
879 TheU->constructContainingTypeDIEs();
881 // Add CU specific attributes if we need to add any.
882 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
883 // If we're splitting the dwarf out now that we've got the entire
884 // CU then add the dwo id to it.
885 DwarfCompileUnit *SkCU =
886 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
887 if (useSplitDwarf()) {
888 // Emit a unique identifier for this CU.
889 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
890 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
891 dwarf::DW_FORM_data8, ID);
892 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
893 dwarf::DW_FORM_data8, ID);
895 // We don't keep track of which addresses are used in which CU so this
896 // is a bit pessimistic under LTO.
897 if (!AddrPool.isEmpty())
898 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
899 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
900 DwarfAddrSectionSym);
901 if (!TheU->getRangeLists().empty())
902 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
903 dwarf::DW_AT_GNU_ranges_base,
904 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
907 // If we have code split among multiple sections or non-contiguous
908 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
909 // remain in the .o file, otherwise add a DW_AT_low_pc.
910 // FIXME: We should use ranges allow reordering of code ala
911 // .subsections_via_symbols in mach-o. This would mean turning on
912 // ranges for all subprogram DIEs for mach-o.
913 DwarfCompileUnit &U =
914 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
915 unsigned NumRanges = TheU->getRanges().size();
918 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
919 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
920 DwarfDebugRangeSectionSym);
922 // A DW_AT_low_pc attribute may also be specified in combination with
923 // DW_AT_ranges to specify the default base address for use in
924 // location lists (see Section 2.6.2) and range lists (see Section
926 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
929 RangeSpan &Range = TheU->getRanges().back();
930 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
932 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
939 // Compute DIE offsets and sizes.
940 InfoHolder.computeSizeAndOffsets();
942 SkeletonHolder.computeSizeAndOffsets();
945 void DwarfDebug::endSections() {
946 // Filter labels by section.
947 for (const SymbolCU &SCU : ArangeLabels) {
948 if (SCU.Sym->isInSection()) {
949 // Make a note of this symbol and it's section.
950 const MCSection *Section = &SCU.Sym->getSection();
951 if (!Section->getKind().isMetadata())
952 SectionMap[Section].push_back(SCU);
954 // Some symbols (e.g. common/bss on mach-o) can have no section but still
955 // appear in the output. This sucks as we rely on sections to build
956 // arange spans. We can do it without, but it's icky.
957 SectionMap[nullptr].push_back(SCU);
961 // Build a list of sections used.
962 std::vector<const MCSection *> Sections;
963 for (const auto &it : SectionMap) {
964 const MCSection *Section = it.first;
965 Sections.push_back(Section);
968 // Sort the sections into order.
969 // This is only done to ensure consistent output order across different runs.
970 std::sort(Sections.begin(), Sections.end(), SectionSort);
972 // Add terminating symbols for each section.
973 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
974 const MCSection *Section = Sections[ID];
975 MCSymbol *Sym = nullptr;
978 // We can't call MCSection::getLabelEndName, as it's only safe to do so
979 // if we know the section name up-front. For user-created sections, the
980 // resulting label may not be valid to use as a label. (section names can
981 // use a greater set of characters on some systems)
982 Sym = Asm->GetTempSymbol("debug_end", ID);
983 Asm->OutStreamer.SwitchSection(Section);
984 Asm->OutStreamer.EmitLabel(Sym);
987 // Insert a final terminator.
988 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
992 // Emit all Dwarf sections that should come after the content.
993 void DwarfDebug::endModule() {
994 assert(CurFn == nullptr);
995 assert(CurMI == nullptr);
1000 // End any existing sections.
1001 // TODO: Does this need to happen?
1004 // Finalize the debug info for the module.
1005 finalizeModuleInfo();
1009 // Emit all the DIEs into a debug info section.
1012 // Corresponding abbreviations into a abbrev section.
1013 emitAbbreviations();
1015 // Emit info into a debug aranges section.
1016 if (GenerateARangeSection)
1019 // Emit info into a debug ranges section.
1022 if (useSplitDwarf()) {
1025 emitDebugAbbrevDWO();
1027 // Emit DWO addresses.
1028 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1031 // Emit info into a debug loc section.
1034 // Emit info into the dwarf accelerator table sections.
1035 if (useDwarfAccelTables()) {
1038 emitAccelNamespaces();
1042 // Emit the pubnames and pubtypes sections if requested.
1043 if (HasDwarfPubSections) {
1044 emitDebugPubNames(GenerateGnuPubSections);
1045 emitDebugPubTypes(GenerateGnuPubSections);
1051 // Reset these for the next Module if we have one.
1055 // Find abstract variable, if any, associated with Var.
1056 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1057 DebugLoc ScopeLoc) {
1058 LLVMContext &Ctx = DV->getContext();
1059 // More then one inlined variable corresponds to one abstract variable.
1060 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1061 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1063 return AbsDbgVariable;
1065 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1069 AbsDbgVariable = new DbgVariable(Var, nullptr, this);
1070 addScopeVariable(Scope, AbsDbgVariable);
1071 AbstractVariables[Var] = AbsDbgVariable;
1072 return AbsDbgVariable;
1075 // If Var is a current function argument then add it to CurrentFnArguments list.
1076 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1077 if (!LScopes.isCurrentFunctionScope(Scope))
1079 DIVariable DV = Var->getVariable();
1080 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1082 unsigned ArgNo = DV.getArgNumber();
1086 size_t Size = CurrentFnArguments.size();
1088 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1089 // llvm::Function argument size is not good indicator of how many
1090 // arguments does the function have at source level.
1092 CurrentFnArguments.resize(ArgNo * 2);
1093 CurrentFnArguments[ArgNo - 1] = Var;
1097 // Collect variable information from side table maintained by MMI.
1098 void DwarfDebug::collectVariableInfoFromMMITable(
1099 SmallPtrSet<const MDNode *, 16> &Processed) {
1100 for (const auto &VI : MMI->getVariableDbgInfo()) {
1103 Processed.insert(VI.Var);
1104 DIVariable DV(VI.Var);
1105 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1107 // If variable scope is not found then skip this variable.
1111 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1112 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1113 RegVar->setFrameIndex(VI.Slot);
1114 if (!addCurrentFnArgument(RegVar, Scope))
1115 addScopeVariable(Scope, RegVar);
1119 // Get .debug_loc entry for the instruction range starting at MI.
1120 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1121 const MDNode *Var = MI->getDebugVariable();
1123 assert(MI->getNumOperands() == 3);
1124 if (MI->getOperand(0).isReg()) {
1125 MachineLocation MLoc;
1126 // If the second operand is an immediate, this is a
1127 // register-indirect address.
1128 if (!MI->getOperand(1).isImm())
1129 MLoc.set(MI->getOperand(0).getReg());
1131 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1132 return DebugLocEntry::Value(Var, MLoc);
1134 if (MI->getOperand(0).isImm())
1135 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1136 if (MI->getOperand(0).isFPImm())
1137 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1138 if (MI->getOperand(0).isCImm())
1139 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1141 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1144 // Find variables for each lexical scope.
1146 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1147 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1148 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1150 // Grab the variable info that was squirreled away in the MMI side-table.
1151 collectVariableInfoFromMMITable(Processed);
1153 for (const auto &I : DbgValues) {
1154 DIVariable DV(I.first);
1155 if (Processed.count(DV))
1158 // History contains relevant DBG_VALUE instructions for DV and instructions
1160 const SmallVectorImpl<const MachineInstr *> &History = I.second;
1161 if (History.empty())
1163 const MachineInstr *MInsn = History.front();
1165 LexicalScope *Scope = nullptr;
1166 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1167 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1168 Scope = LScopes.getCurrentFunctionScope();
1169 else if (MDNode *IA = DV.getInlinedAt()) {
1170 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1171 Scope = LScopes.findInlinedScope(DebugLoc::get(
1172 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1174 Scope = LScopes.findLexicalScope(DV.getContext());
1175 // If variable scope is not found then skip this variable.
1179 Processed.insert(DV);
1180 assert(MInsn->isDebugValue() && "History must begin with debug value");
1181 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1182 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1183 if (!addCurrentFnArgument(RegVar, Scope))
1184 addScopeVariable(Scope, RegVar);
1186 AbsVar->setMInsn(MInsn);
1188 // Simplify ranges that are fully coalesced.
1189 if (History.size() <= 1 ||
1190 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1191 RegVar->setMInsn(MInsn);
1195 // Handle multiple DBG_VALUE instructions describing one variable.
1196 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1198 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1199 DebugLocList &LocList = DotDebugLocEntries.back();
1201 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1202 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1203 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1204 HI = History.begin(),
1207 const MachineInstr *Begin = *HI;
1208 assert(Begin->isDebugValue() && "Invalid History entry");
1210 // Check if DBG_VALUE is truncating a range.
1211 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1212 !Begin->getOperand(0).getReg())
1215 // Compute the range for a register location.
1216 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1217 const MCSymbol *SLabel = nullptr;
1220 // If Begin is the last instruction in History then its value is valid
1221 // until the end of the function.
1222 SLabel = FunctionEndSym;
1224 const MachineInstr *End = HI[1];
1225 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1226 << "\t" << *Begin << "\t" << *End << "\n");
1227 if (End->isDebugValue())
1228 SLabel = getLabelBeforeInsn(End);
1230 // End is a normal instruction clobbering the range.
1231 SLabel = getLabelAfterInsn(End);
1232 assert(SLabel && "Forgot label after clobber instruction");
1237 // The value is valid until the next DBG_VALUE or clobber.
1238 DebugLocEntry Loc(FLabel, SLabel, getDebugLocValue(Begin), TheCU);
1239 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1240 DebugLoc.push_back(std::move(Loc));
1244 // Collect info for variables that were optimized out.
1245 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1246 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1247 DIVariable DV(Variables.getElement(i));
1248 assert(DV.isVariable());
1249 if (!Processed.insert(DV))
1251 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1252 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1256 // Return Label preceding the instruction.
1257 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1258 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1259 assert(Label && "Didn't insert label before instruction");
1263 // Return Label immediately following the instruction.
1264 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1265 return LabelsAfterInsn.lookup(MI);
1268 // Process beginning of an instruction.
1269 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1270 assert(CurMI == nullptr);
1272 // Check if source location changes, but ignore DBG_VALUE locations.
1273 if (!MI->isDebugValue()) {
1274 DebugLoc DL = MI->getDebugLoc();
1275 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1278 if (DL == PrologEndLoc) {
1279 Flags |= DWARF2_FLAG_PROLOGUE_END;
1280 PrologEndLoc = DebugLoc();
1282 if (PrologEndLoc.isUnknown())
1283 Flags |= DWARF2_FLAG_IS_STMT;
1285 if (!DL.isUnknown()) {
1286 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1287 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1289 recordSourceLine(0, 0, nullptr, 0);
1293 // Insert labels where requested.
1294 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1295 LabelsBeforeInsn.find(MI);
1298 if (I == LabelsBeforeInsn.end())
1301 // Label already assigned.
1306 PrevLabel = MMI->getContext().CreateTempSymbol();
1307 Asm->OutStreamer.EmitLabel(PrevLabel);
1309 I->second = PrevLabel;
1312 // Process end of an instruction.
1313 void DwarfDebug::endInstruction() {
1314 assert(CurMI != nullptr);
1315 // Don't create a new label after DBG_VALUE instructions.
1316 // They don't generate code.
1317 if (!CurMI->isDebugValue())
1318 PrevLabel = nullptr;
1320 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1321 LabelsAfterInsn.find(CurMI);
1325 if (I == LabelsAfterInsn.end())
1328 // Label already assigned.
1332 // We need a label after this instruction.
1334 PrevLabel = MMI->getContext().CreateTempSymbol();
1335 Asm->OutStreamer.EmitLabel(PrevLabel);
1337 I->second = PrevLabel;
1340 // Each LexicalScope has first instruction and last instruction to mark
1341 // beginning and end of a scope respectively. Create an inverse map that list
1342 // scopes starts (and ends) with an instruction. One instruction may start (or
1343 // end) multiple scopes. Ignore scopes that are not reachable.
1344 void DwarfDebug::identifyScopeMarkers() {
1345 SmallVector<LexicalScope *, 4> WorkList;
1346 WorkList.push_back(LScopes.getCurrentFunctionScope());
1347 while (!WorkList.empty()) {
1348 LexicalScope *S = WorkList.pop_back_val();
1350 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1351 if (!Children.empty())
1352 WorkList.append(Children.begin(), Children.end());
1354 if (S->isAbstractScope())
1357 for (const InsnRange &R : S->getRanges()) {
1358 assert(R.first && "InsnRange does not have first instruction!");
1359 assert(R.second && "InsnRange does not have second instruction!");
1360 requestLabelBeforeInsn(R.first);
1361 requestLabelAfterInsn(R.second);
1366 // Gather pre-function debug information. Assumes being called immediately
1367 // after the function entry point has been emitted.
1368 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1371 // If there's no debug info for the function we're not going to do anything.
1372 if (!MMI->hasDebugInfo())
1375 // Grab the lexical scopes for the function, if we don't have any of those
1376 // then we're not going to be able to do anything.
1377 LScopes.initialize(*MF);
1378 if (LScopes.empty())
1381 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1383 // Make sure that each lexical scope will have a begin/end label.
1384 identifyScopeMarkers();
1386 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1387 // belongs to so that we add to the correct per-cu line table in the
1389 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1390 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1391 assert(TheCU && "Unable to find compile unit!");
1392 if (Asm->OutStreamer.hasRawTextSupport())
1393 // Use a single line table if we are generating assembly.
1394 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1396 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1398 // Emit a label for the function so that we have a beginning address.
1399 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1400 // Assumes in correct section after the entry point.
1401 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1403 // Collect user variables, find the end of the prologue.
1404 for (const auto &MBB : *MF) {
1405 for (const auto &MI : MBB) {
1406 if (MI.isDebugValue()) {
1407 assert(MI.getNumOperands() > 1 && "Invalid machine instruction!");
1408 // Keep track of user variables in order of appearance. Create the
1409 // empty history for each variable so that the order of keys in
1410 // DbgValues is correct. Actual history will be populated in
1411 // calculateDbgValueHistory() function.
1412 const MDNode *Var = MI.getDebugVariable();
1414 std::make_pair(Var, SmallVector<const MachineInstr *, 4>()));
1415 } else if (!MI.getFlag(MachineInstr::FrameSetup) &&
1416 PrologEndLoc.isUnknown() && !MI.getDebugLoc().isUnknown()) {
1417 // First known non-DBG_VALUE and non-frame setup location marks
1418 // the beginning of the function body.
1419 PrologEndLoc = MI.getDebugLoc();
1424 // Calculate history for local variables.
1425 calculateDbgValueHistory(MF, Asm->TM.getRegisterInfo(), DbgValues);
1427 // Request labels for the full history.
1428 for (auto &I : DbgValues) {
1429 const SmallVectorImpl<const MachineInstr *> &History = I.second;
1430 if (History.empty())
1433 // The first mention of a function argument gets the FunctionBeginSym
1434 // label, so arguments are visible when breaking at function entry.
1435 DIVariable DV(I.first);
1436 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1437 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1438 LabelsBeforeInsn[History.front()] = FunctionBeginSym;
1440 for (const MachineInstr *MI : History) {
1441 if (MI->isDebugValue())
1442 requestLabelBeforeInsn(MI);
1444 requestLabelAfterInsn(MI);
1448 PrevInstLoc = DebugLoc();
1449 PrevLabel = FunctionBeginSym;
1451 // Record beginning of function.
1452 if (!PrologEndLoc.isUnknown()) {
1453 DebugLoc FnStartDL =
1454 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1456 FnStartDL.getLine(), FnStartDL.getCol(),
1457 FnStartDL.getScope(MF->getFunction()->getContext()),
1458 // We'd like to list the prologue as "not statements" but GDB behaves
1459 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1460 DWARF2_FLAG_IS_STMT);
1464 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1465 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1466 DIVariable DV = Var->getVariable();
1467 // Variables with positive arg numbers are parameters.
1468 if (unsigned ArgNum = DV.getArgNumber()) {
1469 // Keep all parameters in order at the start of the variable list to ensure
1470 // function types are correct (no out-of-order parameters)
1472 // This could be improved by only doing it for optimized builds (unoptimized
1473 // builds have the right order to begin with), searching from the back (this
1474 // would catch the unoptimized case quickly), or doing a binary search
1475 // rather than linear search.
1476 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1477 while (I != Vars.end()) {
1478 unsigned CurNum = (*I)->getVariable().getArgNumber();
1479 // A local (non-parameter) variable has been found, insert immediately
1483 // A later indexed parameter has been found, insert immediately before it.
1484 if (CurNum > ArgNum)
1488 Vars.insert(I, Var);
1492 Vars.push_back(Var);
1495 // Gather and emit post-function debug information.
1496 void DwarfDebug::endFunction(const MachineFunction *MF) {
1497 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1498 // though the beginFunction may not be called at all.
1499 // We should handle both cases.
1503 assert(CurFn == MF);
1504 assert(CurFn != nullptr);
1506 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1507 // If we don't have a lexical scope for this function then there will
1508 // be a hole in the range information. Keep note of this by setting the
1509 // previously used section to nullptr.
1510 PrevSection = nullptr;
1516 // Define end label for subprogram.
1517 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1518 // Assumes in correct section after the entry point.
1519 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1521 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1522 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1524 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1525 collectVariableInfo(ProcessedVars);
1527 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1528 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1530 // Construct abstract scopes.
1531 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1532 DISubprogram SP(AScope->getScopeNode());
1533 if (!SP.isSubprogram())
1535 // Collect info for variables that were optimized out.
1536 DIArray Variables = SP.getVariables();
1537 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1538 DIVariable DV(Variables.getElement(i));
1539 assert(DV && DV.isVariable());
1540 if (!ProcessedVars.insert(DV))
1542 // Check that DbgVariable for DV wasn't created earlier, when
1543 // findAbstractVariable() was called for inlined instance of DV.
1544 LLVMContext &Ctx = DV->getContext();
1545 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1546 if (AbstractVariables.lookup(CleanDV))
1548 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1549 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1551 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1554 DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
1555 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1556 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1558 // Add the range of this function to the list of ranges for the CU.
1559 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1560 TheCU.addRange(std::move(Span));
1561 PrevSection = Asm->getCurrentSection();
1565 for (auto &I : ScopeVariables)
1566 DeleteContainerPointers(I.second);
1567 ScopeVariables.clear();
1568 DeleteContainerPointers(CurrentFnArguments);
1570 AbstractVariables.clear();
1571 LabelsBeforeInsn.clear();
1572 LabelsAfterInsn.clear();
1573 PrevLabel = nullptr;
1577 // Register a source line with debug info. Returns the unique label that was
1578 // emitted and which provides correspondence to the source line list.
1579 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1584 unsigned Discriminator = 0;
1585 if (DIScope Scope = DIScope(S)) {
1586 assert(Scope.isScope());
1587 Fn = Scope.getFilename();
1588 Dir = Scope.getDirectory();
1589 if (Scope.isLexicalBlock())
1590 Discriminator = DILexicalBlock(S).getDiscriminator();
1592 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1593 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1594 .getOrCreateSourceID(Fn, Dir);
1596 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1600 //===----------------------------------------------------------------------===//
1602 //===----------------------------------------------------------------------===//
1604 // Emit initial Dwarf sections with a label at the start of each one.
1605 void DwarfDebug::emitSectionLabels() {
1606 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1608 // Dwarf sections base addresses.
1609 DwarfInfoSectionSym =
1610 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1611 if (useSplitDwarf()) {
1612 DwarfInfoDWOSectionSym =
1613 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1614 DwarfTypesDWOSectionSym =
1615 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_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();
2380 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2381 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2382 this, &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 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2397 DwarfTypesDWOSectionSym);
2399 CU.applyStmtList(UnitDie);
2401 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2404 NewTU.setType(NewTU.createTypeDIE(CTy));
2407 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2408 TypeUnitsUnderConstruction.clear();
2410 // Types referencing entries in the address table cannot be placed in type
2412 if (AddrPool.hasBeenUsed()) {
2414 // Remove all the types built while building this type.
2415 // This is pessimistic as some of these types might not be dependent on
2416 // the type that used an address.
2417 for (const auto &TU : TypeUnitsToAdd)
2418 DwarfTypeUnits.erase(TU.second);
2420 // Construct this type in the CU directly.
2421 // This is inefficient because all the dependent types will be rebuilt
2422 // from scratch, including building them in type units, discovering that
2423 // they depend on addresses, throwing them out and rebuilding them.
2424 CU.constructTypeDIE(RefDie, CTy);
2428 // If the type wasn't dependent on fission addresses, finish adding the type
2429 // and all its dependent types.
2430 for (auto &TU : TypeUnitsToAdd) {
2431 if (useSplitDwarf())
2432 TU.first->setSkeleton(constructSkeletonTU(*TU.first));
2433 InfoHolder.addUnit(std::move(TU.first));
2436 CU.addDIETypeSignature(RefDie, NewTU);
2439 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2440 MCSymbol *Begin, MCSymbol *End) {
2441 assert(Begin && "Begin label should not be null!");
2442 assert(End && "End label should not be null!");
2443 assert(Begin->isDefined() && "Invalid starting label");
2444 assert(End->isDefined() && "Invalid end label");
2446 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2447 if (DwarfVersion < 4)
2448 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2450 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2453 // Accelerator table mutators - add each name along with its companion
2454 // DIE to the proper table while ensuring that the name that we're going
2455 // to reference is in the string table. We do this since the names we
2456 // add may not only be identical to the names in the DIE.
2457 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2458 if (!useDwarfAccelTables())
2460 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2464 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2465 if (!useDwarfAccelTables())
2467 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2471 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2472 if (!useDwarfAccelTables())
2474 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2478 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2479 if (!useDwarfAccelTables())
2481 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),