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 "DwarfDebug.h"
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
56 #define DEBUG_TYPE "dwarfdebug"
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60 cl::desc("Disable debug info printing"));
62 static cl::opt<bool> UnknownLocations(
63 "use-unknown-locations", cl::Hidden,
64 cl::desc("Make an absence of debug location information explicit."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
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).getElements();
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 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = nullptr) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 static bool isObjCClass(StringRef Name) {
240 return Name.startswith("+") || Name.startswith("-");
243 static bool hasObjCCategory(StringRef Name) {
244 if (!isObjCClass(Name))
247 return Name.find(") ") != StringRef::npos;
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251 StringRef &Category) {
252 if (!hasObjCCategory(In)) {
253 Class = In.slice(In.find('[') + 1, In.find(' '));
258 Class = In.slice(In.find('[') + 1, In.find('('));
259 Category = In.slice(In.find('[') + 1, In.find(' '));
263 static StringRef getObjCMethodName(StringRef In) {
264 return In.slice(In.find(' ') + 1, In.find(']'));
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269 std::string LA = (A ? A->getLabelBeginName() : "");
270 std::string LB = (B ? B->getLabelBeginName() : "");
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279 if (!SP.isDefinition())
281 addAccelName(SP.getName(), Die);
283 // If the linkage name is different than the name, go ahead and output
284 // that as well into the name table.
285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286 addAccelName(SP.getLinkageName(), Die);
288 // If this is an Objective-C selector name add it to the ObjC accelerator
290 if (isObjCClass(SP.getName())) {
291 StringRef Class, Category;
292 getObjCClassCategory(SP.getName(), Class, Category);
293 addAccelObjC(Class, Die);
295 addAccelObjC(Category, Die);
296 // Also add the base method name to the name table.
297 addAccelName(getObjCMethodName(SP.getName()), Die);
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
306 DIDescriptor D(Context);
307 if (D.isSubprogram())
310 return isSubprogramContext(resolve(DIType(Context).getContext()));
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
325 if (Ranges.size() > 1)
328 // We don't create a DIE if we have a single Range and the end label
330 return !getLabelAfterInsn(Ranges.front().second);
333 // Construct new DW_TAG_lexical_block for this scope and attach
334 // DW_AT_low_pc/DW_AT_high_pc labels.
336 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
337 LexicalScope *Scope) {
338 if (isLexicalScopeDIENull(Scope))
341 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
342 if (Scope->isAbstractScope())
345 TheCU.attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
350 // This scope represents inlined body of a function. Construct DIE to
351 // represent this concrete inlined copy of the function.
353 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
354 LexicalScope *Scope) {
355 assert(Scope->getScopeNode());
356 DIScope DS(Scope->getScopeNode());
357 DISubprogram InlinedSP = getDISubprogram(DS);
358 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
359 // was inlined from another compile unit.
360 DIE *OriginDIE = AbstractSPDies[InlinedSP];
361 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
363 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
364 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
366 TheCU.attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
368 // Add the call site information to the DIE.
369 DILocation DL(Scope->getInlinedAt());
370 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
371 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
372 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
374 // Add name to the name table, we do this here because we're guaranteed
375 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
376 addSubprogramNames(InlinedSP, *ScopeDIE);
381 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
383 const LexicalScope &Scope,
384 DIE *&ObjectPointer) {
385 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
386 if (DV.isObjectPointer())
387 ObjectPointer = Var.get();
391 DIE *DwarfDebug::createScopeChildrenDIE(
392 DwarfCompileUnit &TheCU, LexicalScope *Scope,
393 SmallVectorImpl<std::unique_ptr<DIE>> &Children,
394 unsigned *ChildScopeCount) {
395 DIE *ObjectPointer = nullptr;
397 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
398 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
400 unsigned ChildCountWithoutScopes = Children.size();
402 for (LexicalScope *LS : Scope->getChildren())
403 TheCU.constructScopeDIE(LS, Children);
406 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
408 return ObjectPointer;
411 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
412 LexicalScope *Scope, DIE &ScopeDIE) {
413 // We create children when the scope DIE is not null.
414 SmallVector<std::unique_ptr<DIE>, 8> Children;
415 DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
418 for (auto &I : Children)
419 ScopeDIE.addChild(std::move(I));
421 return ObjectPointer;
424 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
425 LexicalScope *Scope) {
426 assert(Scope && Scope->getScopeNode());
427 assert(Scope->isAbstractScope());
428 assert(!Scope->getInlinedAt());
430 DISubprogram SP(Scope->getScopeNode());
432 ProcessedSPNodes.insert(SP);
434 DIE *&AbsDef = AbstractSPDies[SP];
438 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
439 // was inlined from another compile unit.
440 DwarfCompileUnit &SPCU = *SPMap[SP];
443 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
444 // the important distinction that the DIDescriptor is not associated with the
445 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
446 // any). It could be refactored to some common utility function.
447 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
448 ContextDIE = &SPCU.getUnitDie();
449 SPCU.getOrCreateSubprogramDIE(SPDecl);
451 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
453 // Passing null as the associated DIDescriptor because the abstract definition
454 // shouldn't be found by lookup.
455 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
457 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
459 if (TheCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
460 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
461 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
462 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
465 void DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
466 LexicalScope *Scope) {
467 assert(Scope && Scope->getScopeNode());
468 assert(!Scope->getInlinedAt());
469 assert(!Scope->isAbstractScope());
470 DISubprogram Sub(Scope->getScopeNode());
472 assert(Sub.isSubprogram());
474 ProcessedSPNodes.insert(Sub);
476 DIE &ScopeDIE = TheCU.updateSubprogramScopeDIE(Sub);
478 // Collect arguments for current function.
479 assert(LScopes.isCurrentFunctionScope(Scope));
480 DIE *ObjectPointer = nullptr;
481 for (DbgVariable *ArgDV : CurrentFnArguments)
484 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
486 // If this is a variadic function, add an unspecified parameter.
487 DITypeArray FnArgs = Sub.getType().getTypeArray();
488 // If we have a single element of null, it is a function that returns void.
489 // If we have more than one elements and the last one is null, it is a
490 // variadic function.
491 if (FnArgs.getNumElements() > 1 &&
492 !FnArgs.getElement(FnArgs.getNumElements() - 1))
493 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
495 // Collect lexical scope children first.
496 // ObjectPointer might be a local (non-argument) local variable if it's a
497 // block's synthetic this pointer.
498 if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
499 assert(!ObjectPointer && "multiple object pointers can't be described");
500 ObjectPointer = BlockObjPtr;
504 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
507 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
508 if (!GenerateGnuPubSections)
511 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
514 // Create new DwarfCompileUnit for the given metadata node with tag
515 // DW_TAG_compile_unit.
516 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
517 StringRef FN = DIUnit.getFilename();
518 CompilationDir = DIUnit.getDirectory();
520 auto OwnedUnit = make_unique<DwarfCompileUnit>(
521 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
522 DwarfCompileUnit &NewCU = *OwnedUnit;
523 DIE &Die = NewCU.getUnitDie();
524 InfoHolder.addUnit(std::move(OwnedUnit));
526 // LTO with assembly output shares a single line table amongst multiple CUs.
527 // To avoid the compilation directory being ambiguous, let the line table
528 // explicitly describe the directory of all files, never relying on the
529 // compilation directory.
530 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
531 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
532 NewCU.getUniqueID(), CompilationDir);
534 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
535 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
536 DIUnit.getLanguage());
537 NewCU.addString(Die, dwarf::DW_AT_name, FN);
539 if (!useSplitDwarf()) {
540 NewCU.initStmtList(DwarfLineSectionSym);
542 // If we're using split dwarf the compilation dir is going to be in the
543 // skeleton CU and so we don't need to duplicate it here.
544 if (!CompilationDir.empty())
545 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
547 addGnuPubAttributes(NewCU, Die);
550 if (DIUnit.isOptimized())
551 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
553 StringRef Flags = DIUnit.getFlags();
555 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
557 if (unsigned RVer = DIUnit.getRunTimeVersion())
558 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
559 dwarf::DW_FORM_data1, RVer);
564 if (useSplitDwarf()) {
565 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
566 DwarfInfoDWOSectionSym);
567 NewCU.setSkeleton(constructSkeletonCU(NewCU));
569 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
570 DwarfInfoSectionSym);
572 CUMap.insert(std::make_pair(DIUnit, &NewCU));
573 CUDieMap.insert(std::make_pair(&Die, &NewCU));
577 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
579 DIImportedEntity Module(N);
580 assert(Module.Verify());
581 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
582 D->addChild(TheCU.constructImportedEntityDIE(Module));
585 // Emit all Dwarf sections that should come prior to the content. Create
586 // global DIEs and emit initial debug info sections. This is invoked by
587 // the target AsmPrinter.
588 void DwarfDebug::beginModule() {
589 if (DisableDebugInfoPrinting)
592 const Module *M = MMI->getModule();
594 FunctionDIs = makeSubprogramMap(*M);
596 // If module has named metadata anchors then use them, otherwise scan the
597 // module using debug info finder to collect debug info.
598 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
601 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
603 // Emit initial sections so we can reference labels later.
606 SingleCU = CU_Nodes->getNumOperands() == 1;
608 for (MDNode *N : CU_Nodes->operands()) {
609 DICompileUnit CUNode(N);
610 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
611 DIArray ImportedEntities = CUNode.getImportedEntities();
612 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
613 ScopesWithImportedEntities.push_back(std::make_pair(
614 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
615 ImportedEntities.getElement(i)));
616 std::sort(ScopesWithImportedEntities.begin(),
617 ScopesWithImportedEntities.end(), less_first());
618 DIArray GVs = CUNode.getGlobalVariables();
619 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
620 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
621 DIArray SPs = CUNode.getSubprograms();
622 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
623 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
624 DIArray EnumTypes = CUNode.getEnumTypes();
625 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
626 DIType Ty(EnumTypes.getElement(i));
627 // The enum types array by design contains pointers to
628 // MDNodes rather than DIRefs. Unique them here.
629 DIType UniqueTy(resolve(Ty.getRef()));
630 CU.getOrCreateTypeDIE(UniqueTy);
632 DIArray RetainedTypes = CUNode.getRetainedTypes();
633 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
634 DIType Ty(RetainedTypes.getElement(i));
635 // The retained types array by design contains pointers to
636 // MDNodes rather than DIRefs. Unique them here.
637 DIType UniqueTy(resolve(Ty.getRef()));
638 CU.getOrCreateTypeDIE(UniqueTy);
640 // Emit imported_modules last so that the relevant context is already
642 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
643 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
646 // Tell MMI that we have debug info.
647 MMI->setDebugInfoAvailability(true);
649 // Prime section data.
650 SectionMap[Asm->getObjFileLowering().getTextSection()];
653 void DwarfDebug::finishVariableDefinitions() {
654 for (const auto &Var : ConcreteVariables) {
655 DIE *VariableDie = Var->getDIE();
657 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
658 // in the ConcreteVariables list, rather than looking it up again here.
659 // DIE::getUnit isn't simple - it walks parent pointers, etc.
660 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
662 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
663 if (AbsVar && AbsVar->getDIE()) {
664 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
667 Unit->applyVariableAttributes(*Var, *VariableDie);
671 void DwarfDebug::finishSubprogramDefinitions() {
672 const Module *M = MMI->getModule();
674 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
675 for (MDNode *N : CU_Nodes->operands()) {
676 DICompileUnit TheCU(N);
677 // Construct subprogram DIE and add variables DIEs.
678 DwarfCompileUnit *SPCU =
679 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
680 DIArray Subprograms = TheCU.getSubprograms();
681 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
682 DISubprogram SP(Subprograms.getElement(i));
683 // Perhaps the subprogram is in another CU (such as due to comdat
684 // folding, etc), in which case ignore it here.
685 if (SPMap[SP] != SPCU)
687 DIE *D = SPCU->getDIE(SP);
688 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
690 // If this subprogram has an abstract definition, reference that
691 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
693 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
694 // Lazily construct the subprogram if we didn't see either concrete or
695 // inlined versions during codegen. (except in -gmlt ^ where we want
696 // to omit these entirely)
697 D = SPCU->getOrCreateSubprogramDIE(SP);
699 // And attach the attributes
700 SPCU->applySubprogramAttributesToDefinition(SP, *D);
707 // Collect info for variables that were optimized out.
708 void DwarfDebug::collectDeadVariables() {
709 const Module *M = MMI->getModule();
711 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
712 for (MDNode *N : CU_Nodes->operands()) {
713 DICompileUnit TheCU(N);
714 // Construct subprogram DIE and add variables DIEs.
715 DwarfCompileUnit *SPCU =
716 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
717 assert(SPCU && "Unable to find Compile Unit!");
718 DIArray Subprograms = TheCU.getSubprograms();
719 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
720 DISubprogram SP(Subprograms.getElement(i));
721 if (ProcessedSPNodes.count(SP) != 0)
723 assert(SP.isSubprogram() &&
724 "CU's subprogram list contains a non-subprogram");
725 assert(SP.isDefinition() &&
726 "CU's subprogram list contains a subprogram declaration");
727 DIArray Variables = SP.getVariables();
728 if (Variables.getNumElements() == 0)
731 DIE *SPDIE = AbstractSPDies.lookup(SP);
733 SPDIE = SPCU->getDIE(SP);
735 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
736 DIVariable DV(Variables.getElement(vi));
737 assert(DV.isVariable());
738 DbgVariable NewVar(DV, DIExpression(nullptr), this);
739 auto VariableDie = SPCU->constructVariableDIE(NewVar);
740 SPCU->applyVariableAttributes(NewVar, *VariableDie);
741 SPDIE->addChild(std::move(VariableDie));
748 void DwarfDebug::finalizeModuleInfo() {
749 finishSubprogramDefinitions();
751 finishVariableDefinitions();
753 // Collect info for variables that were optimized out.
754 collectDeadVariables();
756 // Handle anything that needs to be done on a per-unit basis after
757 // all other generation.
758 for (const auto &TheU : getUnits()) {
759 // Emit DW_AT_containing_type attribute to connect types with their
760 // vtable holding type.
761 TheU->constructContainingTypeDIEs();
763 // Add CU specific attributes if we need to add any.
764 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
765 // If we're splitting the dwarf out now that we've got the entire
766 // CU then add the dwo id to it.
767 DwarfCompileUnit *SkCU =
768 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
769 if (useSplitDwarf()) {
770 // Emit a unique identifier for this CU.
771 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
772 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
773 dwarf::DW_FORM_data8, ID);
774 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
775 dwarf::DW_FORM_data8, ID);
777 // We don't keep track of which addresses are used in which CU so this
778 // is a bit pessimistic under LTO.
779 if (!AddrPool.isEmpty())
780 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
781 DwarfAddrSectionSym, DwarfAddrSectionSym);
782 if (!TheU->getRangeLists().empty())
783 SkCU->addSectionLabel(
784 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
785 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
788 // If we have code split among multiple sections or non-contiguous
789 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
790 // remain in the .o file, otherwise add a DW_AT_low_pc.
791 // FIXME: We should use ranges allow reordering of code ala
792 // .subsections_via_symbols in mach-o. This would mean turning on
793 // ranges for all subprogram DIEs for mach-o.
794 DwarfCompileUnit &U =
795 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
796 unsigned NumRanges = TheU->getRanges().size();
799 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
800 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
801 DwarfDebugRangeSectionSym);
803 // A DW_AT_low_pc attribute may also be specified in combination with
804 // DW_AT_ranges to specify the default base address for use in
805 // location lists (see Section 2.6.2) and range lists (see Section
807 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
810 RangeSpan &Range = TheU->getRanges().back();
811 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
817 // Compute DIE offsets and sizes.
818 InfoHolder.computeSizeAndOffsets();
820 SkeletonHolder.computeSizeAndOffsets();
823 void DwarfDebug::endSections() {
824 // Filter labels by section.
825 for (const SymbolCU &SCU : ArangeLabels) {
826 if (SCU.Sym->isInSection()) {
827 // Make a note of this symbol and it's section.
828 const MCSection *Section = &SCU.Sym->getSection();
829 if (!Section->getKind().isMetadata())
830 SectionMap[Section].push_back(SCU);
832 // Some symbols (e.g. common/bss on mach-o) can have no section but still
833 // appear in the output. This sucks as we rely on sections to build
834 // arange spans. We can do it without, but it's icky.
835 SectionMap[nullptr].push_back(SCU);
839 // Build a list of sections used.
840 std::vector<const MCSection *> Sections;
841 for (const auto &it : SectionMap) {
842 const MCSection *Section = it.first;
843 Sections.push_back(Section);
846 // Sort the sections into order.
847 // This is only done to ensure consistent output order across different runs.
848 std::sort(Sections.begin(), Sections.end(), SectionSort);
850 // Add terminating symbols for each section.
851 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
852 const MCSection *Section = Sections[ID];
853 MCSymbol *Sym = nullptr;
856 // We can't call MCSection::getLabelEndName, as it's only safe to do so
857 // if we know the section name up-front. For user-created sections, the
858 // resulting label may not be valid to use as a label. (section names can
859 // use a greater set of characters on some systems)
860 Sym = Asm->GetTempSymbol("debug_end", ID);
861 Asm->OutStreamer.SwitchSection(Section);
862 Asm->OutStreamer.EmitLabel(Sym);
865 // Insert a final terminator.
866 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
870 // Emit all Dwarf sections that should come after the content.
871 void DwarfDebug::endModule() {
872 assert(CurFn == nullptr);
873 assert(CurMI == nullptr);
878 // End any existing sections.
879 // TODO: Does this need to happen?
882 // Finalize the debug info for the module.
883 finalizeModuleInfo();
887 // Emit all the DIEs into a debug info section.
890 // Corresponding abbreviations into a abbrev section.
893 // Emit info into a debug aranges section.
894 if (GenerateARangeSection)
897 // Emit info into a debug ranges section.
900 if (useSplitDwarf()) {
903 emitDebugAbbrevDWO();
906 // Emit DWO addresses.
907 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
909 // Emit info into a debug loc section.
912 // Emit info into the dwarf accelerator table sections.
913 if (useDwarfAccelTables()) {
916 emitAccelNamespaces();
920 // Emit the pubnames and pubtypes sections if requested.
921 if (HasDwarfPubSections) {
922 emitDebugPubNames(GenerateGnuPubSections);
923 emitDebugPubTypes(GenerateGnuPubSections);
928 AbstractVariables.clear();
930 // Reset these for the next Module if we have one.
934 // Find abstract variable, if any, associated with Var.
935 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
936 DIVariable &Cleansed) {
937 LLVMContext &Ctx = DV->getContext();
938 // More then one inlined variable corresponds to one abstract variable.
939 // FIXME: This duplication of variables when inlining should probably be
940 // removed. It's done to allow each DIVariable to describe its location
941 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
942 // make it accurate then remove this duplication/cleansing stuff.
943 Cleansed = cleanseInlinedVariable(DV, Ctx);
944 auto I = AbstractVariables.find(Cleansed);
945 if (I != AbstractVariables.end())
946 return I->second.get();
950 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
952 return getExistingAbstractVariable(DV, Cleansed);
955 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
956 LexicalScope *Scope) {
957 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
958 addScopeVariable(Scope, AbsDbgVariable.get());
959 AbstractVariables[Var] = std::move(AbsDbgVariable);
962 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
963 const MDNode *ScopeNode) {
964 DIVariable Cleansed = DV;
965 if (getExistingAbstractVariable(DV, Cleansed))
968 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
972 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
973 const MDNode *ScopeNode) {
974 DIVariable Cleansed = DV;
975 if (getExistingAbstractVariable(DV, Cleansed))
978 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
979 createAbstractVariable(Cleansed, Scope);
982 // If Var is a current function argument then add it to CurrentFnArguments list.
983 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
984 if (!LScopes.isCurrentFunctionScope(Scope))
986 DIVariable DV = Var->getVariable();
987 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
989 unsigned ArgNo = DV.getArgNumber();
993 size_t Size = CurrentFnArguments.size();
995 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
996 // llvm::Function argument size is not good indicator of how many
997 // arguments does the function have at source level.
999 CurrentFnArguments.resize(ArgNo * 2);
1000 assert(!CurrentFnArguments[ArgNo - 1]);
1001 CurrentFnArguments[ArgNo - 1] = Var;
1005 // Collect variable information from side table maintained by MMI.
1006 void DwarfDebug::collectVariableInfoFromMMITable(
1007 SmallPtrSetImpl<const MDNode *> &Processed) {
1008 for (const auto &VI : MMI->getVariableDbgInfo()) {
1011 Processed.insert(VI.Var);
1012 DIVariable DV(VI.Var);
1013 DIExpression Expr(VI.Expr);
1014 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1016 // If variable scope is not found then skip this variable.
1020 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1021 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
1022 DbgVariable *RegVar = ConcreteVariables.back().get();
1023 RegVar->setFrameIndex(VI.Slot);
1024 addScopeVariable(Scope, RegVar);
1028 // Get .debug_loc entry for the instruction range starting at MI.
1029 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1030 const MDNode *Expr = MI->getDebugExpression();
1031 const MDNode *Var = MI->getDebugVariable();
1033 assert(MI->getNumOperands() == 4);
1034 if (MI->getOperand(0).isReg()) {
1035 MachineLocation MLoc;
1036 // If the second operand is an immediate, this is a
1037 // register-indirect address.
1038 if (!MI->getOperand(1).isImm())
1039 MLoc.set(MI->getOperand(0).getReg());
1041 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1042 return DebugLocEntry::Value(Var, Expr, MLoc);
1044 if (MI->getOperand(0).isImm())
1045 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
1046 if (MI->getOperand(0).isFPImm())
1047 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1048 if (MI->getOperand(0).isCImm())
1049 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1051 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1054 /// Determine whether two variable pieces overlap.
1055 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1056 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1058 unsigned l1 = P1.getPieceOffset();
1059 unsigned l2 = P2.getPieceOffset();
1060 unsigned r1 = l1 + P1.getPieceSize();
1061 unsigned r2 = l2 + P2.getPieceSize();
1062 // True where [l1,r1[ and [r1,r2[ overlap.
1063 return (l1 < r2) && (l2 < r1);
1066 /// Build the location list for all DBG_VALUEs in the function that
1067 /// describe the same variable. If the ranges of several independent
1068 /// pieces of the same variable overlap partially, split them up and
1069 /// combine the ranges. The resulting DebugLocEntries are will have
1070 /// strict monotonically increasing begin addresses and will never
1075 // Ranges History [var, loc, piece ofs size]
1076 // 0 | [x, (reg0, piece 0, 32)]
1077 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1079 // 3 | [clobber reg0]
1080 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1084 // [0-1] [x, (reg0, piece 0, 32)]
1085 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1086 // [3-4] [x, (reg1, piece 32, 32)]
1087 // [4- ] [x, (mem, piece 0, 64)]
1089 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1090 const DbgValueHistoryMap::InstrRanges &Ranges) {
1091 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1093 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1094 const MachineInstr *Begin = I->first;
1095 const MachineInstr *End = I->second;
1096 assert(Begin->isDebugValue() && "Invalid History entry");
1098 // Check if a variable is inaccessible in this range.
1099 if (Begin->getNumOperands() > 1 &&
1100 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1105 // If this piece overlaps with any open ranges, truncate them.
1106 DIExpression DIExpr = Begin->getDebugExpression();
1107 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1108 [&](DebugLocEntry::Value R) {
1109 return piecesOverlap(DIExpr, R.getExpression());
1111 OpenRanges.erase(Last, OpenRanges.end());
1113 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1114 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1116 const MCSymbol *EndLabel;
1118 EndLabel = getLabelAfterInsn(End);
1119 else if (std::next(I) == Ranges.end())
1120 EndLabel = FunctionEndSym;
1122 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1123 assert(EndLabel && "Forgot label after instruction ending a range!");
1125 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1127 auto Value = getDebugLocValue(Begin);
1128 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1129 bool couldMerge = false;
1131 // If this is a piece, it may belong to the current DebugLocEntry.
1132 if (DIExpr.isVariablePiece()) {
1133 // Add this value to the list of open ranges.
1134 OpenRanges.push_back(Value);
1136 // Attempt to add the piece to the last entry.
1137 if (!DebugLoc.empty())
1138 if (DebugLoc.back().MergeValues(Loc))
1143 // Need to add a new DebugLocEntry. Add all values from still
1144 // valid non-overlapping pieces.
1145 if (OpenRanges.size())
1146 Loc.addValues(OpenRanges);
1148 DebugLoc.push_back(std::move(Loc));
1151 // Attempt to coalesce the ranges of two otherwise identical
1153 auto CurEntry = DebugLoc.rbegin();
1154 auto PrevEntry = std::next(CurEntry);
1155 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1156 DebugLoc.pop_back();
1159 dbgs() << CurEntry->getValues().size() << " Values:\n";
1160 for (auto Value : CurEntry->getValues()) {
1161 Value.getVariable()->dump();
1162 Value.getExpression()->dump();
1164 dbgs() << "-----\n";
1170 // Find variables for each lexical scope.
1172 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1173 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1174 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1176 // Grab the variable info that was squirreled away in the MMI side-table.
1177 collectVariableInfoFromMMITable(Processed);
1179 for (const auto &I : DbgValues) {
1180 DIVariable DV(I.first);
1181 if (Processed.count(DV))
1184 // Instruction ranges, specifying where DV is accessible.
1185 const auto &Ranges = I.second;
1189 LexicalScope *Scope = nullptr;
1190 if (MDNode *IA = DV.getInlinedAt()) {
1191 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1192 Scope = LScopes.findInlinedScope(DebugLoc::get(
1193 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1195 Scope = LScopes.findLexicalScope(DV.getContext());
1196 // If variable scope is not found then skip this variable.
1200 Processed.insert(DV);
1201 const MachineInstr *MInsn = Ranges.front().first;
1202 assert(MInsn->isDebugValue() && "History must begin with debug value");
1203 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1204 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1205 DbgVariable *RegVar = ConcreteVariables.back().get();
1206 addScopeVariable(Scope, RegVar);
1208 // Check if the first DBG_VALUE is valid for the rest of the function.
1209 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1212 // Handle multiple DBG_VALUE instructions describing one variable.
1213 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1215 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1216 DebugLocList &LocList = DotDebugLocEntries.back();
1219 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1221 // Build the location list for this variable.
1222 buildLocationList(LocList.List, Ranges);
1225 // Collect info for variables that were optimized out.
1226 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1227 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1228 DIVariable DV(Variables.getElement(i));
1229 assert(DV.isVariable());
1230 if (!Processed.insert(DV))
1232 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1233 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1234 DIExpression NoExpr;
1235 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1236 addScopeVariable(Scope, ConcreteVariables.back().get());
1241 // Return Label preceding the instruction.
1242 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1243 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1244 assert(Label && "Didn't insert label before instruction");
1248 // Return Label immediately following the instruction.
1249 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1250 return LabelsAfterInsn.lookup(MI);
1253 // Process beginning of an instruction.
1254 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1255 assert(CurMI == nullptr);
1257 // Check if source location changes, but ignore DBG_VALUE locations.
1258 if (!MI->isDebugValue()) {
1259 DebugLoc DL = MI->getDebugLoc();
1260 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1263 if (DL == PrologEndLoc) {
1264 Flags |= DWARF2_FLAG_PROLOGUE_END;
1265 PrologEndLoc = DebugLoc();
1267 if (PrologEndLoc.isUnknown())
1268 Flags |= DWARF2_FLAG_IS_STMT;
1270 if (!DL.isUnknown()) {
1271 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1272 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1274 recordSourceLine(0, 0, nullptr, 0);
1278 // Insert labels where requested.
1279 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1280 LabelsBeforeInsn.find(MI);
1283 if (I == LabelsBeforeInsn.end())
1286 // Label already assigned.
1291 PrevLabel = MMI->getContext().CreateTempSymbol();
1292 Asm->OutStreamer.EmitLabel(PrevLabel);
1294 I->second = PrevLabel;
1297 // Process end of an instruction.
1298 void DwarfDebug::endInstruction() {
1299 assert(CurMI != nullptr);
1300 // Don't create a new label after DBG_VALUE instructions.
1301 // They don't generate code.
1302 if (!CurMI->isDebugValue())
1303 PrevLabel = nullptr;
1305 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1306 LabelsAfterInsn.find(CurMI);
1310 if (I == LabelsAfterInsn.end())
1313 // Label already assigned.
1317 // We need a label after this instruction.
1319 PrevLabel = MMI->getContext().CreateTempSymbol();
1320 Asm->OutStreamer.EmitLabel(PrevLabel);
1322 I->second = PrevLabel;
1325 // Each LexicalScope has first instruction and last instruction to mark
1326 // beginning and end of a scope respectively. Create an inverse map that list
1327 // scopes starts (and ends) with an instruction. One instruction may start (or
1328 // end) multiple scopes. Ignore scopes that are not reachable.
1329 void DwarfDebug::identifyScopeMarkers() {
1330 SmallVector<LexicalScope *, 4> WorkList;
1331 WorkList.push_back(LScopes.getCurrentFunctionScope());
1332 while (!WorkList.empty()) {
1333 LexicalScope *S = WorkList.pop_back_val();
1335 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1336 if (!Children.empty())
1337 WorkList.append(Children.begin(), Children.end());
1339 if (S->isAbstractScope())
1342 for (const InsnRange &R : S->getRanges()) {
1343 assert(R.first && "InsnRange does not have first instruction!");
1344 assert(R.second && "InsnRange does not have second instruction!");
1345 requestLabelBeforeInsn(R.first);
1346 requestLabelAfterInsn(R.second);
1351 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1352 // First known non-DBG_VALUE and non-frame setup location marks
1353 // the beginning of the function body.
1354 for (const auto &MBB : *MF)
1355 for (const auto &MI : MBB)
1356 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1357 !MI.getDebugLoc().isUnknown())
1358 return MI.getDebugLoc();
1362 // Gather pre-function debug information. Assumes being called immediately
1363 // after the function entry point has been emitted.
1364 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1367 // If there's no debug info for the function we're not going to do anything.
1368 if (!MMI->hasDebugInfo())
1371 auto DI = FunctionDIs.find(MF->getFunction());
1372 if (DI == FunctionDIs.end())
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 // FnScope->getScopeNode() and DI->second should represent the same function,
1391 // though they may not be the same MDNode due to inline functions merged in
1392 // LTO where the debug info metadata still differs (either due to distinct
1393 // written differences - two versions of a linkonce_odr function
1394 // written/copied into two separate files, or some sub-optimal metadata that
1395 // isn't structurally identical (see: file path/name info from clang, which
1396 // includes the directory of the cpp file being built, even when the file name
1397 // is absolute (such as an <> lookup header)))
1398 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1399 assert(TheCU && "Unable to find compile unit!");
1400 if (Asm->OutStreamer.hasRawTextSupport())
1401 // Use a single line table if we are generating assembly.
1402 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1404 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1406 // Emit a label for the function so that we have a beginning address.
1407 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1408 // Assumes in correct section after the entry point.
1409 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1411 // Calculate history for local variables.
1412 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1415 // Request labels for the full history.
1416 for (const auto &I : DbgValues) {
1417 const auto &Ranges = I.second;
1421 // The first mention of a function argument gets the FunctionBeginSym
1422 // label, so arguments are visible when breaking at function entry.
1423 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1424 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1425 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1426 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1427 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1428 // Mark all non-overlapping initial pieces.
1429 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1430 DIExpression Piece = I->first->getDebugExpression();
1431 if (std::all_of(Ranges.begin(), I,
1432 [&](DbgValueHistoryMap::InstrRange Pred) {
1433 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1435 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1442 for (const auto &Range : Ranges) {
1443 requestLabelBeforeInsn(Range.first);
1445 requestLabelAfterInsn(Range.second);
1449 PrevInstLoc = DebugLoc();
1450 PrevLabel = FunctionBeginSym;
1452 // Record beginning of function.
1453 PrologEndLoc = findPrologueEndLoc(MF);
1454 if (!PrologEndLoc.isUnknown()) {
1455 DebugLoc FnStartDL =
1456 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1458 FnStartDL.getLine(), FnStartDL.getCol(),
1459 FnStartDL.getScope(MF->getFunction()->getContext()),
1460 // We'd like to list the prologue as "not statements" but GDB behaves
1461 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1462 DWARF2_FLAG_IS_STMT);
1466 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1467 if (addCurrentFnArgument(Var, LS))
1469 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1470 DIVariable DV = Var->getVariable();
1471 // Variables with positive arg numbers are parameters.
1472 if (unsigned ArgNum = DV.getArgNumber()) {
1473 // Keep all parameters in order at the start of the variable list to ensure
1474 // function types are correct (no out-of-order parameters)
1476 // This could be improved by only doing it for optimized builds (unoptimized
1477 // builds have the right order to begin with), searching from the back (this
1478 // would catch the unoptimized case quickly), or doing a binary search
1479 // rather than linear search.
1480 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1481 while (I != Vars.end()) {
1482 unsigned CurNum = (*I)->getVariable().getArgNumber();
1483 // A local (non-parameter) variable has been found, insert immediately
1487 // A later indexed parameter has been found, insert immediately before it.
1488 if (CurNum > ArgNum)
1492 Vars.insert(I, Var);
1496 Vars.push_back(Var);
1499 // Gather and emit post-function debug information.
1500 void DwarfDebug::endFunction(const MachineFunction *MF) {
1501 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1502 // though the beginFunction may not be called at all.
1503 // We should handle both cases.
1507 assert(CurFn == MF);
1508 assert(CurFn != nullptr);
1510 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1511 !FunctionDIs.count(MF->getFunction())) {
1512 // If we don't have a lexical scope for this function then there will
1513 // be a hole in the range information. Keep note of this by setting the
1514 // previously used section to nullptr.
1520 // Define end label for subprogram.
1521 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1522 // Assumes in correct section after the entry point.
1523 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1525 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1526 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1528 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1529 collectVariableInfo(ProcessedVars);
1531 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1532 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1534 // Add the range of this function to the list of ranges for the CU.
1535 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1537 // Under -gmlt, skip building the subprogram if there are no inlined
1538 // subroutines inside it.
1539 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1540 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1541 assert(ScopeVariables.empty());
1542 assert(CurrentFnArguments.empty());
1543 assert(DbgValues.empty());
1544 assert(AbstractVariables.empty());
1545 LabelsBeforeInsn.clear();
1546 LabelsAfterInsn.clear();
1547 PrevLabel = nullptr;
1552 // Construct abstract scopes.
1553 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1554 DISubprogram SP(AScope->getScopeNode());
1555 assert(SP.isSubprogram());
1556 // Collect info for variables that were optimized out.
1557 DIArray Variables = SP.getVariables();
1558 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1559 DIVariable DV(Variables.getElement(i));
1560 assert(DV && DV.isVariable());
1561 if (!ProcessedVars.insert(DV))
1563 ensureAbstractVariableIsCreated(DV, DV.getContext());
1565 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1568 constructSubprogramScopeDIE(TheCU, FnScope);
1571 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1572 // DbgVariables except those that are also in AbstractVariables (since they
1573 // can be used cross-function)
1574 ScopeVariables.clear();
1575 CurrentFnArguments.clear();
1577 LabelsBeforeInsn.clear();
1578 LabelsAfterInsn.clear();
1579 PrevLabel = nullptr;
1583 // Register a source line with debug info. Returns the unique label that was
1584 // emitted and which provides correspondence to the source line list.
1585 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1590 unsigned Discriminator = 0;
1591 if (DIScope Scope = DIScope(S)) {
1592 assert(Scope.isScope());
1593 Fn = Scope.getFilename();
1594 Dir = Scope.getDirectory();
1595 if (Scope.isLexicalBlockFile())
1596 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1598 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1599 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1600 .getOrCreateSourceID(Fn, Dir);
1602 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1606 //===----------------------------------------------------------------------===//
1608 //===----------------------------------------------------------------------===//
1610 // Emit initial Dwarf sections with a label at the start of each one.
1611 void DwarfDebug::emitSectionLabels() {
1612 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1614 // Dwarf sections base addresses.
1615 DwarfInfoSectionSym =
1616 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1617 if (useSplitDwarf()) {
1618 DwarfInfoDWOSectionSym =
1619 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1620 DwarfTypesDWOSectionSym =
1621 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1623 DwarfAbbrevSectionSym =
1624 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1625 if (useSplitDwarf())
1626 DwarfAbbrevDWOSectionSym = emitSectionSym(
1627 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1628 if (GenerateARangeSection)
1629 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1631 DwarfLineSectionSym =
1632 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1633 if (GenerateGnuPubSections) {
1634 DwarfGnuPubNamesSectionSym =
1635 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1636 DwarfGnuPubTypesSectionSym =
1637 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1638 } else if (HasDwarfPubSections) {
1639 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1640 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1643 DwarfStrSectionSym =
1644 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1645 if (useSplitDwarf()) {
1646 DwarfStrDWOSectionSym =
1647 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1648 DwarfAddrSectionSym =
1649 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1650 DwarfDebugLocSectionSym =
1651 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1653 DwarfDebugLocSectionSym =
1654 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1655 DwarfDebugRangeSectionSym =
1656 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1659 // Recursively emits a debug information entry.
1660 void DwarfDebug::emitDIE(DIE &Die) {
1661 // Get the abbreviation for this DIE.
1662 const DIEAbbrev &Abbrev = Die.getAbbrev();
1664 // Emit the code (index) for the abbreviation.
1665 if (Asm->isVerbose())
1666 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1667 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1668 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1669 dwarf::TagString(Abbrev.getTag()));
1670 Asm->EmitULEB128(Abbrev.getNumber());
1672 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1673 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1675 // Emit the DIE attribute values.
1676 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1677 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1678 dwarf::Form Form = AbbrevData[i].getForm();
1679 assert(Form && "Too many attributes for DIE (check abbreviation)");
1681 if (Asm->isVerbose()) {
1682 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1683 if (Attr == dwarf::DW_AT_accessibility)
1684 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1685 cast<DIEInteger>(Values[i])->getValue()));
1688 // Emit an attribute using the defined form.
1689 Values[i]->EmitValue(Asm, Form);
1692 // Emit the DIE children if any.
1693 if (Abbrev.hasChildren()) {
1694 for (auto &Child : Die.getChildren())
1697 Asm->OutStreamer.AddComment("End Of Children Mark");
1702 // Emit the debug info section.
1703 void DwarfDebug::emitDebugInfo() {
1704 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1706 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1709 // Emit the abbreviation section.
1710 void DwarfDebug::emitAbbreviations() {
1711 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1713 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1716 // Emit the last address of the section and the end of the line matrix.
1717 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1718 // Define last address of section.
1719 Asm->OutStreamer.AddComment("Extended Op");
1722 Asm->OutStreamer.AddComment("Op size");
1723 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1724 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1725 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1727 Asm->OutStreamer.AddComment("Section end label");
1729 Asm->OutStreamer.EmitSymbolValue(
1730 Asm->GetTempSymbol("section_end", SectionEnd),
1731 Asm->getDataLayout().getPointerSize());
1733 // Mark end of matrix.
1734 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1740 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1741 StringRef TableName, StringRef SymName) {
1742 Accel.FinalizeTable(Asm, TableName);
1743 Asm->OutStreamer.SwitchSection(Section);
1744 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1745 Asm->OutStreamer.EmitLabel(SectionBegin);
1747 // Emit the full data.
1748 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1751 // Emit visible names into a hashed accelerator table section.
1752 void DwarfDebug::emitAccelNames() {
1753 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1754 "Names", "names_begin");
1757 // Emit objective C classes and categories into a hashed accelerator table
1759 void DwarfDebug::emitAccelObjC() {
1760 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1761 "ObjC", "objc_begin");
1764 // Emit namespace dies into a hashed accelerator table.
1765 void DwarfDebug::emitAccelNamespaces() {
1766 emitAccel(AccelNamespace,
1767 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1768 "namespac", "namespac_begin");
1771 // Emit type dies into a hashed accelerator table.
1772 void DwarfDebug::emitAccelTypes() {
1773 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1774 "types", "types_begin");
1777 // Public name handling.
1778 // The format for the various pubnames:
1780 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1781 // for the DIE that is named.
1783 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1784 // into the CU and the index value is computed according to the type of value
1785 // for the DIE that is named.
1787 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1788 // it's the offset within the debug_info/debug_types dwo section, however, the
1789 // reference in the pubname header doesn't change.
1791 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1792 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1794 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1796 // We could have a specification DIE that has our most of our knowledge,
1797 // look for that now.
1798 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1800 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1801 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1802 Linkage = dwarf::GIEL_EXTERNAL;
1803 } else if (Die->findAttribute(dwarf::DW_AT_external))
1804 Linkage = dwarf::GIEL_EXTERNAL;
1806 switch (Die->getTag()) {
1807 case dwarf::DW_TAG_class_type:
1808 case dwarf::DW_TAG_structure_type:
1809 case dwarf::DW_TAG_union_type:
1810 case dwarf::DW_TAG_enumeration_type:
1811 return dwarf::PubIndexEntryDescriptor(
1812 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1813 ? dwarf::GIEL_STATIC
1814 : dwarf::GIEL_EXTERNAL);
1815 case dwarf::DW_TAG_typedef:
1816 case dwarf::DW_TAG_base_type:
1817 case dwarf::DW_TAG_subrange_type:
1818 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1819 case dwarf::DW_TAG_namespace:
1820 return dwarf::GIEK_TYPE;
1821 case dwarf::DW_TAG_subprogram:
1822 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1823 case dwarf::DW_TAG_constant:
1824 case dwarf::DW_TAG_variable:
1825 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1826 case dwarf::DW_TAG_enumerator:
1827 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1828 dwarf::GIEL_STATIC);
1830 return dwarf::GIEK_NONE;
1834 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1836 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1837 const MCSection *PSec =
1838 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1839 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1841 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1844 void DwarfDebug::emitDebugPubSection(
1845 bool GnuStyle, const MCSection *PSec, StringRef Name,
1846 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1847 for (const auto &NU : CUMap) {
1848 DwarfCompileUnit *TheU = NU.second;
1850 const auto &Globals = (TheU->*Accessor)();
1852 if (Globals.empty())
1855 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1857 unsigned ID = TheU->getUniqueID();
1859 // Start the dwarf pubnames section.
1860 Asm->OutStreamer.SwitchSection(PSec);
1863 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1864 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1865 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1866 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1868 Asm->OutStreamer.EmitLabel(BeginLabel);
1870 Asm->OutStreamer.AddComment("DWARF Version");
1871 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1873 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1874 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1876 Asm->OutStreamer.AddComment("Compilation Unit Length");
1877 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1879 // Emit the pubnames for this compilation unit.
1880 for (const auto &GI : Globals) {
1881 const char *Name = GI.getKeyData();
1882 const DIE *Entity = GI.second;
1884 Asm->OutStreamer.AddComment("DIE offset");
1885 Asm->EmitInt32(Entity->getOffset());
1888 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1889 Asm->OutStreamer.AddComment(
1890 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1891 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1892 Asm->EmitInt8(Desc.toBits());
1895 Asm->OutStreamer.AddComment("External Name");
1896 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1899 Asm->OutStreamer.AddComment("End Mark");
1901 Asm->OutStreamer.EmitLabel(EndLabel);
1905 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1906 const MCSection *PSec =
1907 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1908 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1910 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1913 // Emit visible names into a debug str section.
1914 void DwarfDebug::emitDebugStr() {
1915 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1916 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1919 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1920 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1921 const DITypeIdentifierMap &Map,
1922 ArrayRef<DebugLocEntry::Value> Values) {
1923 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1924 return P.isVariablePiece();
1925 }) && "all values are expected to be pieces");
1926 assert(std::is_sorted(Values.begin(), Values.end()) &&
1927 "pieces are expected to be sorted");
1929 unsigned Offset = 0;
1930 for (auto Piece : Values) {
1931 DIExpression Expr = Piece.getExpression();
1932 unsigned PieceOffset = Expr.getPieceOffset();
1933 unsigned PieceSize = Expr.getPieceSize();
1934 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1935 if (Offset < PieceOffset) {
1936 // The DWARF spec seriously mandates pieces with no locations for gaps.
1937 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1938 Offset += PieceOffset-Offset;
1941 Offset += PieceSize;
1943 const unsigned SizeOfByte = 8;
1945 DIVariable Var = Piece.getVariable();
1946 assert(!Var.isIndirect() && "indirect address for piece");
1947 unsigned VarSize = Var.getSizeInBits(Map);
1948 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1949 && "piece is larger than or outside of variable");
1950 assert(PieceSize*SizeOfByte != VarSize
1951 && "piece covers entire variable");
1953 if (Piece.isLocation() && Piece.getLoc().isReg())
1954 Asm->EmitDwarfRegOpPiece(Streamer,
1956 PieceSize*SizeOfByte);
1958 emitDebugLocValue(Streamer, Piece);
1959 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1965 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1966 const DebugLocEntry &Entry) {
1967 const DebugLocEntry::Value Value = Entry.getValues()[0];
1968 if (Value.isVariablePiece())
1969 // Emit all pieces that belong to the same variable and range.
1970 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1972 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1973 emitDebugLocValue(Streamer, Value);
1976 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1977 const DebugLocEntry::Value &Value) {
1978 DIVariable DV = Value.getVariable();
1980 if (Value.isInt()) {
1981 DIBasicType BTy(resolve(DV.getType()));
1982 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1983 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1984 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1985 Streamer.EmitSLEB128(Value.getInt());
1987 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1988 Streamer.EmitULEB128(Value.getInt());
1990 } else if (Value.isLocation()) {
1991 MachineLocation Loc = Value.getLoc();
1992 DIExpression Expr = Value.getExpression();
1995 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1997 // Complex address entry.
1998 unsigned N = Expr.getNumElements();
2000 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
2001 if (Loc.getOffset()) {
2003 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2004 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2005 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2006 Streamer.EmitSLEB128(Expr.getElement(1));
2008 // If first address element is OpPlus then emit
2009 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2010 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
2011 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2015 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2018 // Emit remaining complex address elements.
2019 for (; i < N; ++i) {
2020 uint64_t Element = Expr.getElement(i);
2021 if (Element == dwarf::DW_OP_plus) {
2022 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2023 Streamer.EmitULEB128(Expr.getElement(++i));
2024 } else if (Element == dwarf::DW_OP_deref) {
2026 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2027 } else if (Element == dwarf::DW_OP_piece) {
2029 // handled in emitDebugLocEntry.
2031 llvm_unreachable("unknown Opcode found in complex address");
2035 // else ... ignore constant fp. There is not any good way to
2036 // to represent them here in dwarf.
2040 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2041 Asm->OutStreamer.AddComment("Loc expr size");
2042 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2043 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2044 Asm->EmitLabelDifference(end, begin, 2);
2045 Asm->OutStreamer.EmitLabel(begin);
2047 APByteStreamer Streamer(*Asm);
2048 emitDebugLocEntry(Streamer, Entry);
2050 Asm->OutStreamer.EmitLabel(end);
2053 // Emit locations into the debug loc section.
2054 void DwarfDebug::emitDebugLoc() {
2055 // Start the dwarf loc section.
2056 Asm->OutStreamer.SwitchSection(
2057 Asm->getObjFileLowering().getDwarfLocSection());
2058 unsigned char Size = Asm->getDataLayout().getPointerSize();
2059 for (const auto &DebugLoc : DotDebugLocEntries) {
2060 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2061 const DwarfCompileUnit *CU = DebugLoc.CU;
2062 assert(!CU->getRanges().empty());
2063 for (const auto &Entry : DebugLoc.List) {
2064 // Set up the range. This range is relative to the entry point of the
2065 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2066 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2067 if (CU->getRanges().size() == 1) {
2068 // Grab the begin symbol from the first range as our base.
2069 const MCSymbol *Base = CU->getRanges()[0].getStart();
2070 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2071 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2073 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2074 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2077 emitDebugLocEntryLocation(Entry);
2079 Asm->OutStreamer.EmitIntValue(0, Size);
2080 Asm->OutStreamer.EmitIntValue(0, Size);
2084 void DwarfDebug::emitDebugLocDWO() {
2085 Asm->OutStreamer.SwitchSection(
2086 Asm->getObjFileLowering().getDwarfLocDWOSection());
2087 for (const auto &DebugLoc : DotDebugLocEntries) {
2088 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2089 for (const auto &Entry : DebugLoc.List) {
2090 // Just always use start_length for now - at least that's one address
2091 // rather than two. We could get fancier and try to, say, reuse an
2092 // address we know we've emitted elsewhere (the start of the function?
2093 // The start of the CU or CU subrange that encloses this range?)
2094 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2095 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2096 Asm->EmitULEB128(idx);
2097 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2099 emitDebugLocEntryLocation(Entry);
2101 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2106 const MCSymbol *Start, *End;
2109 // Emit a debug aranges section, containing a CU lookup for any
2110 // address we can tie back to a CU.
2111 void DwarfDebug::emitDebugARanges() {
2112 // Start the dwarf aranges section.
2113 Asm->OutStreamer.SwitchSection(
2114 Asm->getObjFileLowering().getDwarfARangesSection());
2116 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2120 // Build a list of sections used.
2121 std::vector<const MCSection *> Sections;
2122 for (const auto &it : SectionMap) {
2123 const MCSection *Section = it.first;
2124 Sections.push_back(Section);
2127 // Sort the sections into order.
2128 // This is only done to ensure consistent output order across different runs.
2129 std::sort(Sections.begin(), Sections.end(), SectionSort);
2131 // Build a set of address spans, sorted by CU.
2132 for (const MCSection *Section : Sections) {
2133 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2134 if (List.size() < 2)
2137 // Sort the symbols by offset within the section.
2138 std::sort(List.begin(), List.end(),
2139 [&](const SymbolCU &A, const SymbolCU &B) {
2140 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2141 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2143 // Symbols with no order assigned should be placed at the end.
2144 // (e.g. section end labels)
2152 // If we have no section (e.g. common), just write out
2153 // individual spans for each symbol.
2155 for (const SymbolCU &Cur : List) {
2157 Span.Start = Cur.Sym;
2160 Spans[Cur.CU].push_back(Span);
2163 // Build spans between each label.
2164 const MCSymbol *StartSym = List[0].Sym;
2165 for (size_t n = 1, e = List.size(); n < e; n++) {
2166 const SymbolCU &Prev = List[n - 1];
2167 const SymbolCU &Cur = List[n];
2169 // Try and build the longest span we can within the same CU.
2170 if (Cur.CU != Prev.CU) {
2172 Span.Start = StartSym;
2174 Spans[Prev.CU].push_back(Span);
2181 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2183 // Build a list of CUs used.
2184 std::vector<DwarfCompileUnit *> CUs;
2185 for (const auto &it : Spans) {
2186 DwarfCompileUnit *CU = it.first;
2190 // Sort the CU list (again, to ensure consistent output order).
2191 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2192 return A->getUniqueID() < B->getUniqueID();
2195 // Emit an arange table for each CU we used.
2196 for (DwarfCompileUnit *CU : CUs) {
2197 std::vector<ArangeSpan> &List = Spans[CU];
2199 // Emit size of content not including length itself.
2200 unsigned ContentSize =
2201 sizeof(int16_t) + // DWARF ARange version number
2202 sizeof(int32_t) + // Offset of CU in the .debug_info section
2203 sizeof(int8_t) + // Pointer Size (in bytes)
2204 sizeof(int8_t); // Segment Size (in bytes)
2206 unsigned TupleSize = PtrSize * 2;
2208 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2210 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2212 ContentSize += Padding;
2213 ContentSize += (List.size() + 1) * TupleSize;
2215 // For each compile unit, write the list of spans it covers.
2216 Asm->OutStreamer.AddComment("Length of ARange Set");
2217 Asm->EmitInt32(ContentSize);
2218 Asm->OutStreamer.AddComment("DWARF Arange version number");
2219 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2220 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2221 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2222 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2223 Asm->EmitInt8(PtrSize);
2224 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2227 Asm->OutStreamer.EmitFill(Padding, 0xff);
2229 for (const ArangeSpan &Span : List) {
2230 Asm->EmitLabelReference(Span.Start, PtrSize);
2232 // Calculate the size as being from the span start to it's end.
2234 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2236 // For symbols without an end marker (e.g. common), we
2237 // write a single arange entry containing just that one symbol.
2238 uint64_t Size = SymSize[Span.Start];
2242 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2246 Asm->OutStreamer.AddComment("ARange terminator");
2247 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2248 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2252 // Emit visible names into a debug ranges section.
2253 void DwarfDebug::emitDebugRanges() {
2254 // Start the dwarf ranges section.
2255 Asm->OutStreamer.SwitchSection(
2256 Asm->getObjFileLowering().getDwarfRangesSection());
2258 // Size for our labels.
2259 unsigned char Size = Asm->getDataLayout().getPointerSize();
2261 // Grab the specific ranges for the compile units in the module.
2262 for (const auto &I : CUMap) {
2263 DwarfCompileUnit *TheCU = I.second;
2265 // Iterate over the misc ranges for the compile units in the module.
2266 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2267 // Emit our symbol so we can find the beginning of the range.
2268 Asm->OutStreamer.EmitLabel(List.getSym());
2270 for (const RangeSpan &Range : List.getRanges()) {
2271 const MCSymbol *Begin = Range.getStart();
2272 const MCSymbol *End = Range.getEnd();
2273 assert(Begin && "Range without a begin symbol?");
2274 assert(End && "Range without an end symbol?");
2275 if (TheCU->getRanges().size() == 1) {
2276 // Grab the begin symbol from the first range as our base.
2277 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2278 Asm->EmitLabelDifference(Begin, Base, Size);
2279 Asm->EmitLabelDifference(End, Base, Size);
2281 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2282 Asm->OutStreamer.EmitSymbolValue(End, Size);
2286 // And terminate the list with two 0 values.
2287 Asm->OutStreamer.EmitIntValue(0, Size);
2288 Asm->OutStreamer.EmitIntValue(0, Size);
2291 // Now emit a range for the CU itself.
2292 if (TheCU->getRanges().size() > 1) {
2293 Asm->OutStreamer.EmitLabel(
2294 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2295 for (const RangeSpan &Range : TheCU->getRanges()) {
2296 const MCSymbol *Begin = Range.getStart();
2297 const MCSymbol *End = Range.getEnd();
2298 assert(Begin && "Range without a begin symbol?");
2299 assert(End && "Range without an end symbol?");
2300 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2301 Asm->OutStreamer.EmitSymbolValue(End, Size);
2303 // And terminate the list with two 0 values.
2304 Asm->OutStreamer.EmitIntValue(0, Size);
2305 Asm->OutStreamer.EmitIntValue(0, Size);
2310 // DWARF5 Experimental Separate Dwarf emitters.
2312 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2313 std::unique_ptr<DwarfUnit> NewU) {
2314 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2315 U.getCUNode().getSplitDebugFilename());
2317 if (!CompilationDir.empty())
2318 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2320 addGnuPubAttributes(*NewU, Die);
2322 SkeletonHolder.addUnit(std::move(NewU));
2325 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2326 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2327 // DW_AT_addr_base, DW_AT_ranges_base.
2328 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2330 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2331 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2332 DwarfCompileUnit &NewCU = *OwnedUnit;
2333 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2334 DwarfInfoSectionSym);
2336 NewCU.initStmtList(DwarfLineSectionSym);
2338 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2343 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2344 // compile units that would normally be in debug_info.
2345 void DwarfDebug::emitDebugInfoDWO() {
2346 assert(useSplitDwarf() && "No split dwarf debug info?");
2347 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2348 // emit relocations into the dwo file.
2349 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2352 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2353 // abbreviations for the .debug_info.dwo section.
2354 void DwarfDebug::emitDebugAbbrevDWO() {
2355 assert(useSplitDwarf() && "No split dwarf?");
2356 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2359 void DwarfDebug::emitDebugLineDWO() {
2360 assert(useSplitDwarf() && "No split dwarf?");
2361 Asm->OutStreamer.SwitchSection(
2362 Asm->getObjFileLowering().getDwarfLineDWOSection());
2363 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2366 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2367 // string section and is identical in format to traditional .debug_str
2369 void DwarfDebug::emitDebugStrDWO() {
2370 assert(useSplitDwarf() && "No split dwarf?");
2371 const MCSection *OffSec =
2372 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2373 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2377 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2378 if (!useSplitDwarf())
2381 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2382 return &SplitTypeUnitFileTable;
2385 static uint64_t makeTypeSignature(StringRef Identifier) {
2387 Hash.update(Identifier);
2388 // ... take the least significant 8 bytes and return those. Our MD5
2389 // implementation always returns its results in little endian, swap bytes
2391 MD5::MD5Result Result;
2393 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2396 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2397 StringRef Identifier, DIE &RefDie,
2398 DICompositeType CTy) {
2399 // Fast path if we're building some type units and one has already used the
2400 // address pool we know we're going to throw away all this work anyway, so
2401 // don't bother building dependent types.
2402 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2405 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2407 CU.addDIETypeSignature(RefDie, *TU);
2411 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2412 AddrPool.resetUsedFlag();
2414 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2415 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2416 this, &InfoHolder, getDwoLineTable(CU));
2417 DwarfTypeUnit &NewTU = *OwnedUnit;
2418 DIE &UnitDie = NewTU.getUnitDie();
2420 TypeUnitsUnderConstruction.push_back(
2421 std::make_pair(std::move(OwnedUnit), CTy));
2423 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2426 uint64_t Signature = makeTypeSignature(Identifier);
2427 NewTU.setTypeSignature(Signature);
2429 if (useSplitDwarf())
2430 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2431 DwarfTypesDWOSectionSym);
2433 CU.applyStmtList(UnitDie);
2435 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2438 NewTU.setType(NewTU.createTypeDIE(CTy));
2441 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2442 TypeUnitsUnderConstruction.clear();
2444 // Types referencing entries in the address table cannot be placed in type
2446 if (AddrPool.hasBeenUsed()) {
2448 // Remove all the types built while building this type.
2449 // This is pessimistic as some of these types might not be dependent on
2450 // the type that used an address.
2451 for (const auto &TU : TypeUnitsToAdd)
2452 DwarfTypeUnits.erase(TU.second);
2454 // Construct this type in the CU directly.
2455 // This is inefficient because all the dependent types will be rebuilt
2456 // from scratch, including building them in type units, discovering that
2457 // they depend on addresses, throwing them out and rebuilding them.
2458 CU.constructTypeDIE(RefDie, CTy);
2462 // If the type wasn't dependent on fission addresses, finish adding the type
2463 // and all its dependent types.
2464 for (auto &TU : TypeUnitsToAdd)
2465 InfoHolder.addUnit(std::move(TU.first));
2467 CU.addDIETypeSignature(RefDie, NewTU);
2470 // Accelerator table mutators - add each name along with its companion
2471 // DIE to the proper table while ensuring that the name that we're going
2472 // to reference is in the string table. We do this since the names we
2473 // add may not only be identical to the names in the DIE.
2474 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2475 if (!useDwarfAccelTables())
2477 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2481 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2482 if (!useDwarfAccelTables())
2484 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2488 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2489 if (!useDwarfAccelTables())
2491 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2495 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2496 if (!useDwarfAccelTables())
2498 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),