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 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
334 const SmallVectorImpl<InsnRange> &Range) {
335 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
336 // emitting it appropriately.
337 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
339 // Under fission, ranges are specified by constant offsets relative to the
340 // CU's DW_AT_GNU_ranges_base.
342 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
343 DwarfDebugRangeSectionSym);
345 TheCU.addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
346 DwarfDebugRangeSectionSym);
348 RangeSpanList List(RangeSym);
349 for (const InsnRange &R : Range) {
350 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
351 List.addRange(std::move(Span));
354 // Add the range list to the set of ranges to be emitted.
355 TheCU.addRangeList(std::move(List));
358 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
359 const SmallVectorImpl<InsnRange> &Ranges) {
360 assert(!Ranges.empty());
361 if (Ranges.size() == 1)
362 TheCU.attachLowHighPC(Die, getLabelBeforeInsn(Ranges.front().first),
363 getLabelAfterInsn(Ranges.front().second));
365 addScopeRangeList(TheCU, Die, Ranges);
368 // Construct new DW_TAG_lexical_block for this scope and attach
369 // DW_AT_low_pc/DW_AT_high_pc labels.
371 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
372 LexicalScope *Scope) {
373 if (isLexicalScopeDIENull(Scope))
376 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
377 if (Scope->isAbstractScope())
380 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
385 // This scope represents inlined body of a function. Construct DIE to
386 // represent this concrete inlined copy of the function.
388 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
389 LexicalScope *Scope) {
390 assert(Scope->getScopeNode());
391 DIScope DS(Scope->getScopeNode());
392 DISubprogram InlinedSP = getDISubprogram(DS);
393 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
394 // was inlined from another compile unit.
395 DIE *OriginDIE = AbstractSPDies[InlinedSP];
396 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
398 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
399 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
401 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
403 // Add the call site information to the DIE.
404 DILocation DL(Scope->getInlinedAt());
405 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
406 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
407 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
409 // Add name to the name table, we do this here because we're guaranteed
410 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
411 addSubprogramNames(InlinedSP, *ScopeDIE);
416 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
418 const LexicalScope &Scope,
419 DIE *&ObjectPointer) {
420 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
421 if (DV.isObjectPointer())
422 ObjectPointer = Var.get();
426 DIE *DwarfDebug::createScopeChildrenDIE(
427 DwarfCompileUnit &TheCU, LexicalScope *Scope,
428 SmallVectorImpl<std::unique_ptr<DIE>> &Children,
429 unsigned *ChildScopeCount) {
430 DIE *ObjectPointer = nullptr;
432 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
433 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
435 unsigned ChildCountWithoutScopes = Children.size();
437 for (LexicalScope *LS : Scope->getChildren())
438 TheCU.constructScopeDIE(LS, Children);
441 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
443 return ObjectPointer;
446 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
447 LexicalScope *Scope, DIE &ScopeDIE) {
448 // We create children when the scope DIE is not null.
449 SmallVector<std::unique_ptr<DIE>, 8> Children;
450 DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
453 for (auto &I : Children)
454 ScopeDIE.addChild(std::move(I));
456 return ObjectPointer;
459 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
460 LexicalScope *Scope) {
461 assert(Scope && Scope->getScopeNode());
462 assert(Scope->isAbstractScope());
463 assert(!Scope->getInlinedAt());
465 DISubprogram SP(Scope->getScopeNode());
467 ProcessedSPNodes.insert(SP);
469 DIE *&AbsDef = AbstractSPDies[SP];
473 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
474 // was inlined from another compile unit.
475 DwarfCompileUnit &SPCU = *SPMap[SP];
478 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
479 // the important distinction that the DIDescriptor is not associated with the
480 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
481 // any). It could be refactored to some common utility function.
482 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
483 ContextDIE = &SPCU.getUnitDie();
484 SPCU.getOrCreateSubprogramDIE(SPDecl);
486 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
488 // Passing null as the associated DIDescriptor because the abstract definition
489 // shouldn't be found by lookup.
490 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
492 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
494 if (TheCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
495 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
496 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
497 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
500 void DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
501 LexicalScope *Scope) {
502 assert(Scope && Scope->getScopeNode());
503 assert(!Scope->getInlinedAt());
504 assert(!Scope->isAbstractScope());
505 DISubprogram Sub(Scope->getScopeNode());
507 assert(Sub.isSubprogram());
509 ProcessedSPNodes.insert(Sub);
511 DIE &ScopeDIE = TheCU.updateSubprogramScopeDIE(Sub);
513 // Collect arguments for current function.
514 assert(LScopes.isCurrentFunctionScope(Scope));
515 DIE *ObjectPointer = nullptr;
516 for (DbgVariable *ArgDV : CurrentFnArguments)
519 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
521 // If this is a variadic function, add an unspecified parameter.
522 DITypeArray FnArgs = Sub.getType().getTypeArray();
523 // If we have a single element of null, it is a function that returns void.
524 // If we have more than one elements and the last one is null, it is a
525 // variadic function.
526 if (FnArgs.getNumElements() > 1 &&
527 !FnArgs.getElement(FnArgs.getNumElements() - 1))
528 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
530 // Collect lexical scope children first.
531 // ObjectPointer might be a local (non-argument) local variable if it's a
532 // block's synthetic this pointer.
533 if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
534 assert(!ObjectPointer && "multiple object pointers can't be described");
535 ObjectPointer = BlockObjPtr;
539 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
542 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
543 if (!GenerateGnuPubSections)
546 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
549 // Create new DwarfCompileUnit for the given metadata node with tag
550 // DW_TAG_compile_unit.
551 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
552 StringRef FN = DIUnit.getFilename();
553 CompilationDir = DIUnit.getDirectory();
555 auto OwnedUnit = make_unique<DwarfCompileUnit>(
556 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
557 DwarfCompileUnit &NewCU = *OwnedUnit;
558 DIE &Die = NewCU.getUnitDie();
559 InfoHolder.addUnit(std::move(OwnedUnit));
561 // LTO with assembly output shares a single line table amongst multiple CUs.
562 // To avoid the compilation directory being ambiguous, let the line table
563 // explicitly describe the directory of all files, never relying on the
564 // compilation directory.
565 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
566 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
567 NewCU.getUniqueID(), CompilationDir);
569 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
570 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
571 DIUnit.getLanguage());
572 NewCU.addString(Die, dwarf::DW_AT_name, FN);
574 if (!useSplitDwarf()) {
575 NewCU.initStmtList(DwarfLineSectionSym);
577 // If we're using split dwarf the compilation dir is going to be in the
578 // skeleton CU and so we don't need to duplicate it here.
579 if (!CompilationDir.empty())
580 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
582 addGnuPubAttributes(NewCU, Die);
585 if (DIUnit.isOptimized())
586 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
588 StringRef Flags = DIUnit.getFlags();
590 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
592 if (unsigned RVer = DIUnit.getRunTimeVersion())
593 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
594 dwarf::DW_FORM_data1, RVer);
599 if (useSplitDwarf()) {
600 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
601 DwarfInfoDWOSectionSym);
602 NewCU.setSkeleton(constructSkeletonCU(NewCU));
604 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
605 DwarfInfoSectionSym);
607 CUMap.insert(std::make_pair(DIUnit, &NewCU));
608 CUDieMap.insert(std::make_pair(&Die, &NewCU));
612 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
614 DIImportedEntity Module(N);
615 assert(Module.Verify());
616 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
617 D->addChild(TheCU.constructImportedEntityDIE(Module));
620 // Emit all Dwarf sections that should come prior to the content. Create
621 // global DIEs and emit initial debug info sections. This is invoked by
622 // the target AsmPrinter.
623 void DwarfDebug::beginModule() {
624 if (DisableDebugInfoPrinting)
627 const Module *M = MMI->getModule();
629 FunctionDIs = makeSubprogramMap(*M);
631 // If module has named metadata anchors then use them, otherwise scan the
632 // module using debug info finder to collect debug info.
633 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
636 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
638 // Emit initial sections so we can reference labels later.
641 SingleCU = CU_Nodes->getNumOperands() == 1;
643 for (MDNode *N : CU_Nodes->operands()) {
644 DICompileUnit CUNode(N);
645 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
646 DIArray ImportedEntities = CUNode.getImportedEntities();
647 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
648 ScopesWithImportedEntities.push_back(std::make_pair(
649 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
650 ImportedEntities.getElement(i)));
651 std::sort(ScopesWithImportedEntities.begin(),
652 ScopesWithImportedEntities.end(), less_first());
653 DIArray GVs = CUNode.getGlobalVariables();
654 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
655 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
656 DIArray SPs = CUNode.getSubprograms();
657 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
658 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
659 DIArray EnumTypes = CUNode.getEnumTypes();
660 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
661 DIType Ty(EnumTypes.getElement(i));
662 // The enum types array by design contains pointers to
663 // MDNodes rather than DIRefs. Unique them here.
664 DIType UniqueTy(resolve(Ty.getRef()));
665 CU.getOrCreateTypeDIE(UniqueTy);
667 DIArray RetainedTypes = CUNode.getRetainedTypes();
668 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
669 DIType Ty(RetainedTypes.getElement(i));
670 // The retained types array by design contains pointers to
671 // MDNodes rather than DIRefs. Unique them here.
672 DIType UniqueTy(resolve(Ty.getRef()));
673 CU.getOrCreateTypeDIE(UniqueTy);
675 // Emit imported_modules last so that the relevant context is already
677 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
678 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
681 // Tell MMI that we have debug info.
682 MMI->setDebugInfoAvailability(true);
684 // Prime section data.
685 SectionMap[Asm->getObjFileLowering().getTextSection()];
688 void DwarfDebug::finishVariableDefinitions() {
689 for (const auto &Var : ConcreteVariables) {
690 DIE *VariableDie = Var->getDIE();
692 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
693 // in the ConcreteVariables list, rather than looking it up again here.
694 // DIE::getUnit isn't simple - it walks parent pointers, etc.
695 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
697 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
698 if (AbsVar && AbsVar->getDIE()) {
699 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
702 Unit->applyVariableAttributes(*Var, *VariableDie);
706 void DwarfDebug::finishSubprogramDefinitions() {
707 const Module *M = MMI->getModule();
709 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
710 for (MDNode *N : CU_Nodes->operands()) {
711 DICompileUnit TheCU(N);
712 // Construct subprogram DIE and add variables DIEs.
713 DwarfCompileUnit *SPCU =
714 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
715 DIArray Subprograms = TheCU.getSubprograms();
716 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
717 DISubprogram SP(Subprograms.getElement(i));
718 // Perhaps the subprogram is in another CU (such as due to comdat
719 // folding, etc), in which case ignore it here.
720 if (SPMap[SP] != SPCU)
722 DIE *D = SPCU->getDIE(SP);
723 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
725 // If this subprogram has an abstract definition, reference that
726 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
728 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
729 // Lazily construct the subprogram if we didn't see either concrete or
730 // inlined versions during codegen. (except in -gmlt ^ where we want
731 // to omit these entirely)
732 D = SPCU->getOrCreateSubprogramDIE(SP);
734 // And attach the attributes
735 SPCU->applySubprogramAttributesToDefinition(SP, *D);
742 // Collect info for variables that were optimized out.
743 void DwarfDebug::collectDeadVariables() {
744 const Module *M = MMI->getModule();
746 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
747 for (MDNode *N : CU_Nodes->operands()) {
748 DICompileUnit TheCU(N);
749 // Construct subprogram DIE and add variables DIEs.
750 DwarfCompileUnit *SPCU =
751 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
752 assert(SPCU && "Unable to find Compile Unit!");
753 DIArray Subprograms = TheCU.getSubprograms();
754 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
755 DISubprogram SP(Subprograms.getElement(i));
756 if (ProcessedSPNodes.count(SP) != 0)
758 assert(SP.isSubprogram() &&
759 "CU's subprogram list contains a non-subprogram");
760 assert(SP.isDefinition() &&
761 "CU's subprogram list contains a subprogram declaration");
762 DIArray Variables = SP.getVariables();
763 if (Variables.getNumElements() == 0)
766 DIE *SPDIE = AbstractSPDies.lookup(SP);
768 SPDIE = SPCU->getDIE(SP);
770 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
771 DIVariable DV(Variables.getElement(vi));
772 assert(DV.isVariable());
773 DbgVariable NewVar(DV, DIExpression(nullptr), this);
774 auto VariableDie = SPCU->constructVariableDIE(NewVar);
775 SPCU->applyVariableAttributes(NewVar, *VariableDie);
776 SPDIE->addChild(std::move(VariableDie));
783 void DwarfDebug::finalizeModuleInfo() {
784 finishSubprogramDefinitions();
786 finishVariableDefinitions();
788 // Collect info for variables that were optimized out.
789 collectDeadVariables();
791 // Handle anything that needs to be done on a per-unit basis after
792 // all other generation.
793 for (const auto &TheU : getUnits()) {
794 // Emit DW_AT_containing_type attribute to connect types with their
795 // vtable holding type.
796 TheU->constructContainingTypeDIEs();
798 // Add CU specific attributes if we need to add any.
799 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
800 // If we're splitting the dwarf out now that we've got the entire
801 // CU then add the dwo id to it.
802 DwarfCompileUnit *SkCU =
803 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
804 if (useSplitDwarf()) {
805 // Emit a unique identifier for this CU.
806 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
807 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
808 dwarf::DW_FORM_data8, ID);
809 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
810 dwarf::DW_FORM_data8, ID);
812 // We don't keep track of which addresses are used in which CU so this
813 // is a bit pessimistic under LTO.
814 if (!AddrPool.isEmpty())
815 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
816 DwarfAddrSectionSym, DwarfAddrSectionSym);
817 if (!TheU->getRangeLists().empty())
818 SkCU->addSectionLabel(
819 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
820 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
823 // If we have code split among multiple sections or non-contiguous
824 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
825 // remain in the .o file, otherwise add a DW_AT_low_pc.
826 // FIXME: We should use ranges allow reordering of code ala
827 // .subsections_via_symbols in mach-o. This would mean turning on
828 // ranges for all subprogram DIEs for mach-o.
829 DwarfCompileUnit &U =
830 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
831 unsigned NumRanges = TheU->getRanges().size();
834 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
835 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
836 DwarfDebugRangeSectionSym);
838 // A DW_AT_low_pc attribute may also be specified in combination with
839 // DW_AT_ranges to specify the default base address for use in
840 // location lists (see Section 2.6.2) and range lists (see Section
842 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
845 RangeSpan &Range = TheU->getRanges().back();
846 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
852 // Compute DIE offsets and sizes.
853 InfoHolder.computeSizeAndOffsets();
855 SkeletonHolder.computeSizeAndOffsets();
858 void DwarfDebug::endSections() {
859 // Filter labels by section.
860 for (const SymbolCU &SCU : ArangeLabels) {
861 if (SCU.Sym->isInSection()) {
862 // Make a note of this symbol and it's section.
863 const MCSection *Section = &SCU.Sym->getSection();
864 if (!Section->getKind().isMetadata())
865 SectionMap[Section].push_back(SCU);
867 // Some symbols (e.g. common/bss on mach-o) can have no section but still
868 // appear in the output. This sucks as we rely on sections to build
869 // arange spans. We can do it without, but it's icky.
870 SectionMap[nullptr].push_back(SCU);
874 // Build a list of sections used.
875 std::vector<const MCSection *> Sections;
876 for (const auto &it : SectionMap) {
877 const MCSection *Section = it.first;
878 Sections.push_back(Section);
881 // Sort the sections into order.
882 // This is only done to ensure consistent output order across different runs.
883 std::sort(Sections.begin(), Sections.end(), SectionSort);
885 // Add terminating symbols for each section.
886 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
887 const MCSection *Section = Sections[ID];
888 MCSymbol *Sym = nullptr;
891 // We can't call MCSection::getLabelEndName, as it's only safe to do so
892 // if we know the section name up-front. For user-created sections, the
893 // resulting label may not be valid to use as a label. (section names can
894 // use a greater set of characters on some systems)
895 Sym = Asm->GetTempSymbol("debug_end", ID);
896 Asm->OutStreamer.SwitchSection(Section);
897 Asm->OutStreamer.EmitLabel(Sym);
900 // Insert a final terminator.
901 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
905 // Emit all Dwarf sections that should come after the content.
906 void DwarfDebug::endModule() {
907 assert(CurFn == nullptr);
908 assert(CurMI == nullptr);
913 // End any existing sections.
914 // TODO: Does this need to happen?
917 // Finalize the debug info for the module.
918 finalizeModuleInfo();
922 // Emit all the DIEs into a debug info section.
925 // Corresponding abbreviations into a abbrev section.
928 // Emit info into a debug aranges section.
929 if (GenerateARangeSection)
932 // Emit info into a debug ranges section.
935 if (useSplitDwarf()) {
938 emitDebugAbbrevDWO();
941 // Emit DWO addresses.
942 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
944 // Emit info into a debug loc section.
947 // Emit info into the dwarf accelerator table sections.
948 if (useDwarfAccelTables()) {
951 emitAccelNamespaces();
955 // Emit the pubnames and pubtypes sections if requested.
956 if (HasDwarfPubSections) {
957 emitDebugPubNames(GenerateGnuPubSections);
958 emitDebugPubTypes(GenerateGnuPubSections);
963 AbstractVariables.clear();
965 // Reset these for the next Module if we have one.
969 // Find abstract variable, if any, associated with Var.
970 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
971 DIVariable &Cleansed) {
972 LLVMContext &Ctx = DV->getContext();
973 // More then one inlined variable corresponds to one abstract variable.
974 // FIXME: This duplication of variables when inlining should probably be
975 // removed. It's done to allow each DIVariable to describe its location
976 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
977 // make it accurate then remove this duplication/cleansing stuff.
978 Cleansed = cleanseInlinedVariable(DV, Ctx);
979 auto I = AbstractVariables.find(Cleansed);
980 if (I != AbstractVariables.end())
981 return I->second.get();
985 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
987 return getExistingAbstractVariable(DV, Cleansed);
990 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
991 LexicalScope *Scope) {
992 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
993 addScopeVariable(Scope, AbsDbgVariable.get());
994 AbstractVariables[Var] = std::move(AbsDbgVariable);
997 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
998 const MDNode *ScopeNode) {
999 DIVariable Cleansed = DV;
1000 if (getExistingAbstractVariable(DV, Cleansed))
1003 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
1007 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
1008 const MDNode *ScopeNode) {
1009 DIVariable Cleansed = DV;
1010 if (getExistingAbstractVariable(DV, Cleansed))
1013 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
1014 createAbstractVariable(Cleansed, Scope);
1017 // If Var is a current function argument then add it to CurrentFnArguments list.
1018 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1019 if (!LScopes.isCurrentFunctionScope(Scope))
1021 DIVariable DV = Var->getVariable();
1022 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1024 unsigned ArgNo = DV.getArgNumber();
1028 size_t Size = CurrentFnArguments.size();
1030 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1031 // llvm::Function argument size is not good indicator of how many
1032 // arguments does the function have at source level.
1034 CurrentFnArguments.resize(ArgNo * 2);
1035 assert(!CurrentFnArguments[ArgNo - 1]);
1036 CurrentFnArguments[ArgNo - 1] = Var;
1040 // Collect variable information from side table maintained by MMI.
1041 void DwarfDebug::collectVariableInfoFromMMITable(
1042 SmallPtrSetImpl<const MDNode *> &Processed) {
1043 for (const auto &VI : MMI->getVariableDbgInfo()) {
1046 Processed.insert(VI.Var);
1047 DIVariable DV(VI.Var);
1048 DIExpression Expr(VI.Expr);
1049 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1051 // If variable scope is not found then skip this variable.
1055 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1056 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
1057 DbgVariable *RegVar = ConcreteVariables.back().get();
1058 RegVar->setFrameIndex(VI.Slot);
1059 addScopeVariable(Scope, RegVar);
1063 // Get .debug_loc entry for the instruction range starting at MI.
1064 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1065 const MDNode *Expr = MI->getDebugExpression();
1066 const MDNode *Var = MI->getDebugVariable();
1068 assert(MI->getNumOperands() == 4);
1069 if (MI->getOperand(0).isReg()) {
1070 MachineLocation MLoc;
1071 // If the second operand is an immediate, this is a
1072 // register-indirect address.
1073 if (!MI->getOperand(1).isImm())
1074 MLoc.set(MI->getOperand(0).getReg());
1076 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1077 return DebugLocEntry::Value(Var, Expr, MLoc);
1079 if (MI->getOperand(0).isImm())
1080 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
1081 if (MI->getOperand(0).isFPImm())
1082 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1083 if (MI->getOperand(0).isCImm())
1084 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1086 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1089 /// Determine whether two variable pieces overlap.
1090 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1091 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1093 unsigned l1 = P1.getPieceOffset();
1094 unsigned l2 = P2.getPieceOffset();
1095 unsigned r1 = l1 + P1.getPieceSize();
1096 unsigned r2 = l2 + P2.getPieceSize();
1097 // True where [l1,r1[ and [r1,r2[ overlap.
1098 return (l1 < r2) && (l2 < r1);
1101 /// Build the location list for all DBG_VALUEs in the function that
1102 /// describe the same variable. If the ranges of several independent
1103 /// pieces of the same variable overlap partially, split them up and
1104 /// combine the ranges. The resulting DebugLocEntries are will have
1105 /// strict monotonically increasing begin addresses and will never
1110 // Ranges History [var, loc, piece ofs size]
1111 // 0 | [x, (reg0, piece 0, 32)]
1112 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1114 // 3 | [clobber reg0]
1115 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1119 // [0-1] [x, (reg0, piece 0, 32)]
1120 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1121 // [3-4] [x, (reg1, piece 32, 32)]
1122 // [4- ] [x, (mem, piece 0, 64)]
1124 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1125 const DbgValueHistoryMap::InstrRanges &Ranges) {
1126 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1128 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1129 const MachineInstr *Begin = I->first;
1130 const MachineInstr *End = I->second;
1131 assert(Begin->isDebugValue() && "Invalid History entry");
1133 // Check if a variable is inaccessible in this range.
1134 if (Begin->getNumOperands() > 1 &&
1135 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1140 // If this piece overlaps with any open ranges, truncate them.
1141 DIExpression DIExpr = Begin->getDebugExpression();
1142 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1143 [&](DebugLocEntry::Value R) {
1144 return piecesOverlap(DIExpr, R.getExpression());
1146 OpenRanges.erase(Last, OpenRanges.end());
1148 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1149 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1151 const MCSymbol *EndLabel;
1153 EndLabel = getLabelAfterInsn(End);
1154 else if (std::next(I) == Ranges.end())
1155 EndLabel = FunctionEndSym;
1157 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1158 assert(EndLabel && "Forgot label after instruction ending a range!");
1160 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1162 auto Value = getDebugLocValue(Begin);
1163 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1164 bool couldMerge = false;
1166 // If this is a piece, it may belong to the current DebugLocEntry.
1167 if (DIExpr.isVariablePiece()) {
1168 // Add this value to the list of open ranges.
1169 OpenRanges.push_back(Value);
1171 // Attempt to add the piece to the last entry.
1172 if (!DebugLoc.empty())
1173 if (DebugLoc.back().MergeValues(Loc))
1178 // Need to add a new DebugLocEntry. Add all values from still
1179 // valid non-overlapping pieces.
1180 if (OpenRanges.size())
1181 Loc.addValues(OpenRanges);
1183 DebugLoc.push_back(std::move(Loc));
1186 // Attempt to coalesce the ranges of two otherwise identical
1188 auto CurEntry = DebugLoc.rbegin();
1189 auto PrevEntry = std::next(CurEntry);
1190 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1191 DebugLoc.pop_back();
1194 dbgs() << CurEntry->getValues().size() << " Values:\n";
1195 for (auto Value : CurEntry->getValues()) {
1196 Value.getVariable()->dump();
1197 Value.getExpression()->dump();
1199 dbgs() << "-----\n";
1205 // Find variables for each lexical scope.
1207 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1208 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1209 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1211 // Grab the variable info that was squirreled away in the MMI side-table.
1212 collectVariableInfoFromMMITable(Processed);
1214 for (const auto &I : DbgValues) {
1215 DIVariable DV(I.first);
1216 if (Processed.count(DV))
1219 // Instruction ranges, specifying where DV is accessible.
1220 const auto &Ranges = I.second;
1224 LexicalScope *Scope = nullptr;
1225 if (MDNode *IA = DV.getInlinedAt()) {
1226 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1227 Scope = LScopes.findInlinedScope(DebugLoc::get(
1228 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1230 Scope = LScopes.findLexicalScope(DV.getContext());
1231 // If variable scope is not found then skip this variable.
1235 Processed.insert(DV);
1236 const MachineInstr *MInsn = Ranges.front().first;
1237 assert(MInsn->isDebugValue() && "History must begin with debug value");
1238 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1239 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1240 DbgVariable *RegVar = ConcreteVariables.back().get();
1241 addScopeVariable(Scope, RegVar);
1243 // Check if the first DBG_VALUE is valid for the rest of the function.
1244 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1247 // Handle multiple DBG_VALUE instructions describing one variable.
1248 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1250 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1251 DebugLocList &LocList = DotDebugLocEntries.back();
1254 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1256 // Build the location list for this variable.
1257 buildLocationList(LocList.List, Ranges);
1260 // Collect info for variables that were optimized out.
1261 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1262 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1263 DIVariable DV(Variables.getElement(i));
1264 assert(DV.isVariable());
1265 if (!Processed.insert(DV))
1267 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1268 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1269 DIExpression NoExpr;
1270 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1271 addScopeVariable(Scope, ConcreteVariables.back().get());
1276 // Return Label preceding the instruction.
1277 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1278 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1279 assert(Label && "Didn't insert label before instruction");
1283 // Return Label immediately following the instruction.
1284 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1285 return LabelsAfterInsn.lookup(MI);
1288 // Process beginning of an instruction.
1289 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1290 assert(CurMI == nullptr);
1292 // Check if source location changes, but ignore DBG_VALUE locations.
1293 if (!MI->isDebugValue()) {
1294 DebugLoc DL = MI->getDebugLoc();
1295 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1298 if (DL == PrologEndLoc) {
1299 Flags |= DWARF2_FLAG_PROLOGUE_END;
1300 PrologEndLoc = DebugLoc();
1302 if (PrologEndLoc.isUnknown())
1303 Flags |= DWARF2_FLAG_IS_STMT;
1305 if (!DL.isUnknown()) {
1306 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1307 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1309 recordSourceLine(0, 0, nullptr, 0);
1313 // Insert labels where requested.
1314 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1315 LabelsBeforeInsn.find(MI);
1318 if (I == LabelsBeforeInsn.end())
1321 // Label already assigned.
1326 PrevLabel = MMI->getContext().CreateTempSymbol();
1327 Asm->OutStreamer.EmitLabel(PrevLabel);
1329 I->second = PrevLabel;
1332 // Process end of an instruction.
1333 void DwarfDebug::endInstruction() {
1334 assert(CurMI != nullptr);
1335 // Don't create a new label after DBG_VALUE instructions.
1336 // They don't generate code.
1337 if (!CurMI->isDebugValue())
1338 PrevLabel = nullptr;
1340 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1341 LabelsAfterInsn.find(CurMI);
1345 if (I == LabelsAfterInsn.end())
1348 // Label already assigned.
1352 // We need a label after this instruction.
1354 PrevLabel = MMI->getContext().CreateTempSymbol();
1355 Asm->OutStreamer.EmitLabel(PrevLabel);
1357 I->second = PrevLabel;
1360 // Each LexicalScope has first instruction and last instruction to mark
1361 // beginning and end of a scope respectively. Create an inverse map that list
1362 // scopes starts (and ends) with an instruction. One instruction may start (or
1363 // end) multiple scopes. Ignore scopes that are not reachable.
1364 void DwarfDebug::identifyScopeMarkers() {
1365 SmallVector<LexicalScope *, 4> WorkList;
1366 WorkList.push_back(LScopes.getCurrentFunctionScope());
1367 while (!WorkList.empty()) {
1368 LexicalScope *S = WorkList.pop_back_val();
1370 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1371 if (!Children.empty())
1372 WorkList.append(Children.begin(), Children.end());
1374 if (S->isAbstractScope())
1377 for (const InsnRange &R : S->getRanges()) {
1378 assert(R.first && "InsnRange does not have first instruction!");
1379 assert(R.second && "InsnRange does not have second instruction!");
1380 requestLabelBeforeInsn(R.first);
1381 requestLabelAfterInsn(R.second);
1386 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1387 // First known non-DBG_VALUE and non-frame setup location marks
1388 // the beginning of the function body.
1389 for (const auto &MBB : *MF)
1390 for (const auto &MI : MBB)
1391 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1392 !MI.getDebugLoc().isUnknown())
1393 return MI.getDebugLoc();
1397 // Gather pre-function debug information. Assumes being called immediately
1398 // after the function entry point has been emitted.
1399 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1402 // If there's no debug info for the function we're not going to do anything.
1403 if (!MMI->hasDebugInfo())
1406 auto DI = FunctionDIs.find(MF->getFunction());
1407 if (DI == FunctionDIs.end())
1410 // Grab the lexical scopes for the function, if we don't have any of those
1411 // then we're not going to be able to do anything.
1412 LScopes.initialize(*MF);
1413 if (LScopes.empty())
1416 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1418 // Make sure that each lexical scope will have a begin/end label.
1419 identifyScopeMarkers();
1421 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1422 // belongs to so that we add to the correct per-cu line table in the
1424 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1425 // FnScope->getScopeNode() and DI->second should represent the same function,
1426 // though they may not be the same MDNode due to inline functions merged in
1427 // LTO where the debug info metadata still differs (either due to distinct
1428 // written differences - two versions of a linkonce_odr function
1429 // written/copied into two separate files, or some sub-optimal metadata that
1430 // isn't structurally identical (see: file path/name info from clang, which
1431 // includes the directory of the cpp file being built, even when the file name
1432 // is absolute (such as an <> lookup header)))
1433 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1434 assert(TheCU && "Unable to find compile unit!");
1435 if (Asm->OutStreamer.hasRawTextSupport())
1436 // Use a single line table if we are generating assembly.
1437 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1439 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1441 // Emit a label for the function so that we have a beginning address.
1442 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1443 // Assumes in correct section after the entry point.
1444 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1446 // Calculate history for local variables.
1447 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1450 // Request labels for the full history.
1451 for (const auto &I : DbgValues) {
1452 const auto &Ranges = I.second;
1456 // The first mention of a function argument gets the FunctionBeginSym
1457 // label, so arguments are visible when breaking at function entry.
1458 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1459 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1460 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1461 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1462 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1463 // Mark all non-overlapping initial pieces.
1464 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1465 DIExpression Piece = I->first->getDebugExpression();
1466 if (std::all_of(Ranges.begin(), I,
1467 [&](DbgValueHistoryMap::InstrRange Pred) {
1468 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1470 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1477 for (const auto &Range : Ranges) {
1478 requestLabelBeforeInsn(Range.first);
1480 requestLabelAfterInsn(Range.second);
1484 PrevInstLoc = DebugLoc();
1485 PrevLabel = FunctionBeginSym;
1487 // Record beginning of function.
1488 PrologEndLoc = findPrologueEndLoc(MF);
1489 if (!PrologEndLoc.isUnknown()) {
1490 DebugLoc FnStartDL =
1491 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1493 FnStartDL.getLine(), FnStartDL.getCol(),
1494 FnStartDL.getScope(MF->getFunction()->getContext()),
1495 // We'd like to list the prologue as "not statements" but GDB behaves
1496 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1497 DWARF2_FLAG_IS_STMT);
1501 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1502 if (addCurrentFnArgument(Var, LS))
1504 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1505 DIVariable DV = Var->getVariable();
1506 // Variables with positive arg numbers are parameters.
1507 if (unsigned ArgNum = DV.getArgNumber()) {
1508 // Keep all parameters in order at the start of the variable list to ensure
1509 // function types are correct (no out-of-order parameters)
1511 // This could be improved by only doing it for optimized builds (unoptimized
1512 // builds have the right order to begin with), searching from the back (this
1513 // would catch the unoptimized case quickly), or doing a binary search
1514 // rather than linear search.
1515 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1516 while (I != Vars.end()) {
1517 unsigned CurNum = (*I)->getVariable().getArgNumber();
1518 // A local (non-parameter) variable has been found, insert immediately
1522 // A later indexed parameter has been found, insert immediately before it.
1523 if (CurNum > ArgNum)
1527 Vars.insert(I, Var);
1531 Vars.push_back(Var);
1534 // Gather and emit post-function debug information.
1535 void DwarfDebug::endFunction(const MachineFunction *MF) {
1536 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1537 // though the beginFunction may not be called at all.
1538 // We should handle both cases.
1542 assert(CurFn == MF);
1543 assert(CurFn != nullptr);
1545 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1546 !FunctionDIs.count(MF->getFunction())) {
1547 // If we don't have a lexical scope for this function then there will
1548 // be a hole in the range information. Keep note of this by setting the
1549 // previously used section to nullptr.
1555 // Define end label for subprogram.
1556 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1557 // Assumes in correct section after the entry point.
1558 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1560 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1561 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1563 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1564 collectVariableInfo(ProcessedVars);
1566 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1567 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1569 // Add the range of this function to the list of ranges for the CU.
1570 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1572 // Under -gmlt, skip building the subprogram if there are no inlined
1573 // subroutines inside it.
1574 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1575 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1576 assert(ScopeVariables.empty());
1577 assert(CurrentFnArguments.empty());
1578 assert(DbgValues.empty());
1579 assert(AbstractVariables.empty());
1580 LabelsBeforeInsn.clear();
1581 LabelsAfterInsn.clear();
1582 PrevLabel = nullptr;
1587 // Construct abstract scopes.
1588 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1589 DISubprogram SP(AScope->getScopeNode());
1590 assert(SP.isSubprogram());
1591 // Collect info for variables that were optimized out.
1592 DIArray Variables = SP.getVariables();
1593 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1594 DIVariable DV(Variables.getElement(i));
1595 assert(DV && DV.isVariable());
1596 if (!ProcessedVars.insert(DV))
1598 ensureAbstractVariableIsCreated(DV, DV.getContext());
1600 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1603 constructSubprogramScopeDIE(TheCU, FnScope);
1606 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1607 // DbgVariables except those that are also in AbstractVariables (since they
1608 // can be used cross-function)
1609 ScopeVariables.clear();
1610 CurrentFnArguments.clear();
1612 LabelsBeforeInsn.clear();
1613 LabelsAfterInsn.clear();
1614 PrevLabel = nullptr;
1618 // Register a source line with debug info. Returns the unique label that was
1619 // emitted and which provides correspondence to the source line list.
1620 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1625 unsigned Discriminator = 0;
1626 if (DIScope Scope = DIScope(S)) {
1627 assert(Scope.isScope());
1628 Fn = Scope.getFilename();
1629 Dir = Scope.getDirectory();
1630 if (Scope.isLexicalBlockFile())
1631 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1633 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1634 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1635 .getOrCreateSourceID(Fn, Dir);
1637 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1641 //===----------------------------------------------------------------------===//
1643 //===----------------------------------------------------------------------===//
1645 // Emit initial Dwarf sections with a label at the start of each one.
1646 void DwarfDebug::emitSectionLabels() {
1647 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1649 // Dwarf sections base addresses.
1650 DwarfInfoSectionSym =
1651 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1652 if (useSplitDwarf()) {
1653 DwarfInfoDWOSectionSym =
1654 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1655 DwarfTypesDWOSectionSym =
1656 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1658 DwarfAbbrevSectionSym =
1659 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1660 if (useSplitDwarf())
1661 DwarfAbbrevDWOSectionSym = emitSectionSym(
1662 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1663 if (GenerateARangeSection)
1664 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1666 DwarfLineSectionSym =
1667 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1668 if (GenerateGnuPubSections) {
1669 DwarfGnuPubNamesSectionSym =
1670 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1671 DwarfGnuPubTypesSectionSym =
1672 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1673 } else if (HasDwarfPubSections) {
1674 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1675 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1678 DwarfStrSectionSym =
1679 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1680 if (useSplitDwarf()) {
1681 DwarfStrDWOSectionSym =
1682 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1683 DwarfAddrSectionSym =
1684 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1685 DwarfDebugLocSectionSym =
1686 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1688 DwarfDebugLocSectionSym =
1689 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1690 DwarfDebugRangeSectionSym =
1691 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1694 // Recursively emits a debug information entry.
1695 void DwarfDebug::emitDIE(DIE &Die) {
1696 // Get the abbreviation for this DIE.
1697 const DIEAbbrev &Abbrev = Die.getAbbrev();
1699 // Emit the code (index) for the abbreviation.
1700 if (Asm->isVerbose())
1701 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1702 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1703 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1704 dwarf::TagString(Abbrev.getTag()));
1705 Asm->EmitULEB128(Abbrev.getNumber());
1707 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1708 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1710 // Emit the DIE attribute values.
1711 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1712 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1713 dwarf::Form Form = AbbrevData[i].getForm();
1714 assert(Form && "Too many attributes for DIE (check abbreviation)");
1716 if (Asm->isVerbose()) {
1717 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1718 if (Attr == dwarf::DW_AT_accessibility)
1719 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1720 cast<DIEInteger>(Values[i])->getValue()));
1723 // Emit an attribute using the defined form.
1724 Values[i]->EmitValue(Asm, Form);
1727 // Emit the DIE children if any.
1728 if (Abbrev.hasChildren()) {
1729 for (auto &Child : Die.getChildren())
1732 Asm->OutStreamer.AddComment("End Of Children Mark");
1737 // Emit the debug info section.
1738 void DwarfDebug::emitDebugInfo() {
1739 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1741 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1744 // Emit the abbreviation section.
1745 void DwarfDebug::emitAbbreviations() {
1746 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1748 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1751 // Emit the last address of the section and the end of the line matrix.
1752 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1753 // Define last address of section.
1754 Asm->OutStreamer.AddComment("Extended Op");
1757 Asm->OutStreamer.AddComment("Op size");
1758 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1759 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1760 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1762 Asm->OutStreamer.AddComment("Section end label");
1764 Asm->OutStreamer.EmitSymbolValue(
1765 Asm->GetTempSymbol("section_end", SectionEnd),
1766 Asm->getDataLayout().getPointerSize());
1768 // Mark end of matrix.
1769 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1775 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1776 StringRef TableName, StringRef SymName) {
1777 Accel.FinalizeTable(Asm, TableName);
1778 Asm->OutStreamer.SwitchSection(Section);
1779 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1780 Asm->OutStreamer.EmitLabel(SectionBegin);
1782 // Emit the full data.
1783 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1786 // Emit visible names into a hashed accelerator table section.
1787 void DwarfDebug::emitAccelNames() {
1788 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1789 "Names", "names_begin");
1792 // Emit objective C classes and categories into a hashed accelerator table
1794 void DwarfDebug::emitAccelObjC() {
1795 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1796 "ObjC", "objc_begin");
1799 // Emit namespace dies into a hashed accelerator table.
1800 void DwarfDebug::emitAccelNamespaces() {
1801 emitAccel(AccelNamespace,
1802 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1803 "namespac", "namespac_begin");
1806 // Emit type dies into a hashed accelerator table.
1807 void DwarfDebug::emitAccelTypes() {
1808 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1809 "types", "types_begin");
1812 // Public name handling.
1813 // The format for the various pubnames:
1815 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1816 // for the DIE that is named.
1818 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1819 // into the CU and the index value is computed according to the type of value
1820 // for the DIE that is named.
1822 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1823 // it's the offset within the debug_info/debug_types dwo section, however, the
1824 // reference in the pubname header doesn't change.
1826 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1827 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1829 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1831 // We could have a specification DIE that has our most of our knowledge,
1832 // look for that now.
1833 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1835 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1836 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1837 Linkage = dwarf::GIEL_EXTERNAL;
1838 } else if (Die->findAttribute(dwarf::DW_AT_external))
1839 Linkage = dwarf::GIEL_EXTERNAL;
1841 switch (Die->getTag()) {
1842 case dwarf::DW_TAG_class_type:
1843 case dwarf::DW_TAG_structure_type:
1844 case dwarf::DW_TAG_union_type:
1845 case dwarf::DW_TAG_enumeration_type:
1846 return dwarf::PubIndexEntryDescriptor(
1847 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1848 ? dwarf::GIEL_STATIC
1849 : dwarf::GIEL_EXTERNAL);
1850 case dwarf::DW_TAG_typedef:
1851 case dwarf::DW_TAG_base_type:
1852 case dwarf::DW_TAG_subrange_type:
1853 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1854 case dwarf::DW_TAG_namespace:
1855 return dwarf::GIEK_TYPE;
1856 case dwarf::DW_TAG_subprogram:
1857 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1858 case dwarf::DW_TAG_constant:
1859 case dwarf::DW_TAG_variable:
1860 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1861 case dwarf::DW_TAG_enumerator:
1862 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1863 dwarf::GIEL_STATIC);
1865 return dwarf::GIEK_NONE;
1869 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1871 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1872 const MCSection *PSec =
1873 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1874 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1876 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1879 void DwarfDebug::emitDebugPubSection(
1880 bool GnuStyle, const MCSection *PSec, StringRef Name,
1881 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1882 for (const auto &NU : CUMap) {
1883 DwarfCompileUnit *TheU = NU.second;
1885 const auto &Globals = (TheU->*Accessor)();
1887 if (Globals.empty())
1890 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1892 unsigned ID = TheU->getUniqueID();
1894 // Start the dwarf pubnames section.
1895 Asm->OutStreamer.SwitchSection(PSec);
1898 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1899 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1900 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1901 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1903 Asm->OutStreamer.EmitLabel(BeginLabel);
1905 Asm->OutStreamer.AddComment("DWARF Version");
1906 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1908 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1909 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1911 Asm->OutStreamer.AddComment("Compilation Unit Length");
1912 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1914 // Emit the pubnames for this compilation unit.
1915 for (const auto &GI : Globals) {
1916 const char *Name = GI.getKeyData();
1917 const DIE *Entity = GI.second;
1919 Asm->OutStreamer.AddComment("DIE offset");
1920 Asm->EmitInt32(Entity->getOffset());
1923 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1924 Asm->OutStreamer.AddComment(
1925 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1926 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1927 Asm->EmitInt8(Desc.toBits());
1930 Asm->OutStreamer.AddComment("External Name");
1931 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1934 Asm->OutStreamer.AddComment("End Mark");
1936 Asm->OutStreamer.EmitLabel(EndLabel);
1940 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1941 const MCSection *PSec =
1942 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1943 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1945 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1948 // Emit visible names into a debug str section.
1949 void DwarfDebug::emitDebugStr() {
1950 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1951 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1954 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1955 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1956 const DITypeIdentifierMap &Map,
1957 ArrayRef<DebugLocEntry::Value> Values) {
1958 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1959 return P.isVariablePiece();
1960 }) && "all values are expected to be pieces");
1961 assert(std::is_sorted(Values.begin(), Values.end()) &&
1962 "pieces are expected to be sorted");
1964 unsigned Offset = 0;
1965 for (auto Piece : Values) {
1966 DIExpression Expr = Piece.getExpression();
1967 unsigned PieceOffset = Expr.getPieceOffset();
1968 unsigned PieceSize = Expr.getPieceSize();
1969 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1970 if (Offset < PieceOffset) {
1971 // The DWARF spec seriously mandates pieces with no locations for gaps.
1972 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1973 Offset += PieceOffset-Offset;
1976 Offset += PieceSize;
1978 const unsigned SizeOfByte = 8;
1980 DIVariable Var = Piece.getVariable();
1981 assert(!Var.isIndirect() && "indirect address for piece");
1982 unsigned VarSize = Var.getSizeInBits(Map);
1983 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1984 && "piece is larger than or outside of variable");
1985 assert(PieceSize*SizeOfByte != VarSize
1986 && "piece covers entire variable");
1988 if (Piece.isLocation() && Piece.getLoc().isReg())
1989 Asm->EmitDwarfRegOpPiece(Streamer,
1991 PieceSize*SizeOfByte);
1993 emitDebugLocValue(Streamer, Piece);
1994 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
2000 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2001 const DebugLocEntry &Entry) {
2002 const DebugLocEntry::Value Value = Entry.getValues()[0];
2003 if (Value.isVariablePiece())
2004 // Emit all pieces that belong to the same variable and range.
2005 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
2007 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
2008 emitDebugLocValue(Streamer, Value);
2011 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
2012 const DebugLocEntry::Value &Value) {
2013 DIVariable DV = Value.getVariable();
2015 if (Value.isInt()) {
2016 DIBasicType BTy(resolve(DV.getType()));
2017 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2018 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2019 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2020 Streamer.EmitSLEB128(Value.getInt());
2022 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2023 Streamer.EmitULEB128(Value.getInt());
2025 } else if (Value.isLocation()) {
2026 MachineLocation Loc = Value.getLoc();
2027 DIExpression Expr = Value.getExpression();
2030 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2032 // Complex address entry.
2033 unsigned N = Expr.getNumElements();
2035 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
2036 if (Loc.getOffset()) {
2038 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2039 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2040 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2041 Streamer.EmitSLEB128(Expr.getElement(1));
2043 // If first address element is OpPlus then emit
2044 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2045 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
2046 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2050 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2053 // Emit remaining complex address elements.
2054 for (; i < N; ++i) {
2055 uint64_t Element = Expr.getElement(i);
2056 if (Element == dwarf::DW_OP_plus) {
2057 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2058 Streamer.EmitULEB128(Expr.getElement(++i));
2059 } else if (Element == dwarf::DW_OP_deref) {
2061 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2062 } else if (Element == dwarf::DW_OP_piece) {
2064 // handled in emitDebugLocEntry.
2066 llvm_unreachable("unknown Opcode found in complex address");
2070 // else ... ignore constant fp. There is not any good way to
2071 // to represent them here in dwarf.
2075 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2076 Asm->OutStreamer.AddComment("Loc expr size");
2077 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2078 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2079 Asm->EmitLabelDifference(end, begin, 2);
2080 Asm->OutStreamer.EmitLabel(begin);
2082 APByteStreamer Streamer(*Asm);
2083 emitDebugLocEntry(Streamer, Entry);
2085 Asm->OutStreamer.EmitLabel(end);
2088 // Emit locations into the debug loc section.
2089 void DwarfDebug::emitDebugLoc() {
2090 // Start the dwarf loc section.
2091 Asm->OutStreamer.SwitchSection(
2092 Asm->getObjFileLowering().getDwarfLocSection());
2093 unsigned char Size = Asm->getDataLayout().getPointerSize();
2094 for (const auto &DebugLoc : DotDebugLocEntries) {
2095 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2096 const DwarfCompileUnit *CU = DebugLoc.CU;
2097 assert(!CU->getRanges().empty());
2098 for (const auto &Entry : DebugLoc.List) {
2099 // Set up the range. This range is relative to the entry point of the
2100 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2101 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2102 if (CU->getRanges().size() == 1) {
2103 // Grab the begin symbol from the first range as our base.
2104 const MCSymbol *Base = CU->getRanges()[0].getStart();
2105 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2106 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2108 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2109 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2112 emitDebugLocEntryLocation(Entry);
2114 Asm->OutStreamer.EmitIntValue(0, Size);
2115 Asm->OutStreamer.EmitIntValue(0, Size);
2119 void DwarfDebug::emitDebugLocDWO() {
2120 Asm->OutStreamer.SwitchSection(
2121 Asm->getObjFileLowering().getDwarfLocDWOSection());
2122 for (const auto &DebugLoc : DotDebugLocEntries) {
2123 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2124 for (const auto &Entry : DebugLoc.List) {
2125 // Just always use start_length for now - at least that's one address
2126 // rather than two. We could get fancier and try to, say, reuse an
2127 // address we know we've emitted elsewhere (the start of the function?
2128 // The start of the CU or CU subrange that encloses this range?)
2129 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2130 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2131 Asm->EmitULEB128(idx);
2132 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2134 emitDebugLocEntryLocation(Entry);
2136 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2141 const MCSymbol *Start, *End;
2144 // Emit a debug aranges section, containing a CU lookup for any
2145 // address we can tie back to a CU.
2146 void DwarfDebug::emitDebugARanges() {
2147 // Start the dwarf aranges section.
2148 Asm->OutStreamer.SwitchSection(
2149 Asm->getObjFileLowering().getDwarfARangesSection());
2151 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2155 // Build a list of sections used.
2156 std::vector<const MCSection *> Sections;
2157 for (const auto &it : SectionMap) {
2158 const MCSection *Section = it.first;
2159 Sections.push_back(Section);
2162 // Sort the sections into order.
2163 // This is only done to ensure consistent output order across different runs.
2164 std::sort(Sections.begin(), Sections.end(), SectionSort);
2166 // Build a set of address spans, sorted by CU.
2167 for (const MCSection *Section : Sections) {
2168 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2169 if (List.size() < 2)
2172 // Sort the symbols by offset within the section.
2173 std::sort(List.begin(), List.end(),
2174 [&](const SymbolCU &A, const SymbolCU &B) {
2175 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2176 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2178 // Symbols with no order assigned should be placed at the end.
2179 // (e.g. section end labels)
2187 // If we have no section (e.g. common), just write out
2188 // individual spans for each symbol.
2190 for (const SymbolCU &Cur : List) {
2192 Span.Start = Cur.Sym;
2195 Spans[Cur.CU].push_back(Span);
2198 // Build spans between each label.
2199 const MCSymbol *StartSym = List[0].Sym;
2200 for (size_t n = 1, e = List.size(); n < e; n++) {
2201 const SymbolCU &Prev = List[n - 1];
2202 const SymbolCU &Cur = List[n];
2204 // Try and build the longest span we can within the same CU.
2205 if (Cur.CU != Prev.CU) {
2207 Span.Start = StartSym;
2209 Spans[Prev.CU].push_back(Span);
2216 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2218 // Build a list of CUs used.
2219 std::vector<DwarfCompileUnit *> CUs;
2220 for (const auto &it : Spans) {
2221 DwarfCompileUnit *CU = it.first;
2225 // Sort the CU list (again, to ensure consistent output order).
2226 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2227 return A->getUniqueID() < B->getUniqueID();
2230 // Emit an arange table for each CU we used.
2231 for (DwarfCompileUnit *CU : CUs) {
2232 std::vector<ArangeSpan> &List = Spans[CU];
2234 // Emit size of content not including length itself.
2235 unsigned ContentSize =
2236 sizeof(int16_t) + // DWARF ARange version number
2237 sizeof(int32_t) + // Offset of CU in the .debug_info section
2238 sizeof(int8_t) + // Pointer Size (in bytes)
2239 sizeof(int8_t); // Segment Size (in bytes)
2241 unsigned TupleSize = PtrSize * 2;
2243 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2245 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2247 ContentSize += Padding;
2248 ContentSize += (List.size() + 1) * TupleSize;
2250 // For each compile unit, write the list of spans it covers.
2251 Asm->OutStreamer.AddComment("Length of ARange Set");
2252 Asm->EmitInt32(ContentSize);
2253 Asm->OutStreamer.AddComment("DWARF Arange version number");
2254 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2255 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2256 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2257 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2258 Asm->EmitInt8(PtrSize);
2259 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2262 Asm->OutStreamer.EmitFill(Padding, 0xff);
2264 for (const ArangeSpan &Span : List) {
2265 Asm->EmitLabelReference(Span.Start, PtrSize);
2267 // Calculate the size as being from the span start to it's end.
2269 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2271 // For symbols without an end marker (e.g. common), we
2272 // write a single arange entry containing just that one symbol.
2273 uint64_t Size = SymSize[Span.Start];
2277 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2281 Asm->OutStreamer.AddComment("ARange terminator");
2282 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2283 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2287 // Emit visible names into a debug ranges section.
2288 void DwarfDebug::emitDebugRanges() {
2289 // Start the dwarf ranges section.
2290 Asm->OutStreamer.SwitchSection(
2291 Asm->getObjFileLowering().getDwarfRangesSection());
2293 // Size for our labels.
2294 unsigned char Size = Asm->getDataLayout().getPointerSize();
2296 // Grab the specific ranges for the compile units in the module.
2297 for (const auto &I : CUMap) {
2298 DwarfCompileUnit *TheCU = I.second;
2300 // Iterate over the misc ranges for the compile units in the module.
2301 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2302 // Emit our symbol so we can find the beginning of the range.
2303 Asm->OutStreamer.EmitLabel(List.getSym());
2305 for (const RangeSpan &Range : List.getRanges()) {
2306 const MCSymbol *Begin = Range.getStart();
2307 const MCSymbol *End = Range.getEnd();
2308 assert(Begin && "Range without a begin symbol?");
2309 assert(End && "Range without an end symbol?");
2310 if (TheCU->getRanges().size() == 1) {
2311 // Grab the begin symbol from the first range as our base.
2312 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2313 Asm->EmitLabelDifference(Begin, Base, Size);
2314 Asm->EmitLabelDifference(End, Base, Size);
2316 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2317 Asm->OutStreamer.EmitSymbolValue(End, Size);
2321 // And terminate the list with two 0 values.
2322 Asm->OutStreamer.EmitIntValue(0, Size);
2323 Asm->OutStreamer.EmitIntValue(0, Size);
2326 // Now emit a range for the CU itself.
2327 if (TheCU->getRanges().size() > 1) {
2328 Asm->OutStreamer.EmitLabel(
2329 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2330 for (const RangeSpan &Range : TheCU->getRanges()) {
2331 const MCSymbol *Begin = Range.getStart();
2332 const MCSymbol *End = Range.getEnd();
2333 assert(Begin && "Range without a begin symbol?");
2334 assert(End && "Range without an end symbol?");
2335 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2336 Asm->OutStreamer.EmitSymbolValue(End, Size);
2338 // And terminate the list with two 0 values.
2339 Asm->OutStreamer.EmitIntValue(0, Size);
2340 Asm->OutStreamer.EmitIntValue(0, Size);
2345 // DWARF5 Experimental Separate Dwarf emitters.
2347 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2348 std::unique_ptr<DwarfUnit> NewU) {
2349 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2350 U.getCUNode().getSplitDebugFilename());
2352 if (!CompilationDir.empty())
2353 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2355 addGnuPubAttributes(*NewU, Die);
2357 SkeletonHolder.addUnit(std::move(NewU));
2360 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2361 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2362 // DW_AT_addr_base, DW_AT_ranges_base.
2363 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2365 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2366 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2367 DwarfCompileUnit &NewCU = *OwnedUnit;
2368 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2369 DwarfInfoSectionSym);
2371 NewCU.initStmtList(DwarfLineSectionSym);
2373 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2378 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2379 // compile units that would normally be in debug_info.
2380 void DwarfDebug::emitDebugInfoDWO() {
2381 assert(useSplitDwarf() && "No split dwarf debug info?");
2382 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2383 // emit relocations into the dwo file.
2384 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2387 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2388 // abbreviations for the .debug_info.dwo section.
2389 void DwarfDebug::emitDebugAbbrevDWO() {
2390 assert(useSplitDwarf() && "No split dwarf?");
2391 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2394 void DwarfDebug::emitDebugLineDWO() {
2395 assert(useSplitDwarf() && "No split dwarf?");
2396 Asm->OutStreamer.SwitchSection(
2397 Asm->getObjFileLowering().getDwarfLineDWOSection());
2398 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2401 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2402 // string section and is identical in format to traditional .debug_str
2404 void DwarfDebug::emitDebugStrDWO() {
2405 assert(useSplitDwarf() && "No split dwarf?");
2406 const MCSection *OffSec =
2407 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2408 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2412 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2413 if (!useSplitDwarf())
2416 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2417 return &SplitTypeUnitFileTable;
2420 static uint64_t makeTypeSignature(StringRef Identifier) {
2422 Hash.update(Identifier);
2423 // ... take the least significant 8 bytes and return those. Our MD5
2424 // implementation always returns its results in little endian, swap bytes
2426 MD5::MD5Result Result;
2428 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2431 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2432 StringRef Identifier, DIE &RefDie,
2433 DICompositeType CTy) {
2434 // Fast path if we're building some type units and one has already used the
2435 // address pool we know we're going to throw away all this work anyway, so
2436 // don't bother building dependent types.
2437 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2440 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2442 CU.addDIETypeSignature(RefDie, *TU);
2446 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2447 AddrPool.resetUsedFlag();
2449 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2450 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2451 this, &InfoHolder, getDwoLineTable(CU));
2452 DwarfTypeUnit &NewTU = *OwnedUnit;
2453 DIE &UnitDie = NewTU.getUnitDie();
2455 TypeUnitsUnderConstruction.push_back(
2456 std::make_pair(std::move(OwnedUnit), CTy));
2458 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2461 uint64_t Signature = makeTypeSignature(Identifier);
2462 NewTU.setTypeSignature(Signature);
2464 if (useSplitDwarf())
2465 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2466 DwarfTypesDWOSectionSym);
2468 CU.applyStmtList(UnitDie);
2470 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2473 NewTU.setType(NewTU.createTypeDIE(CTy));
2476 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2477 TypeUnitsUnderConstruction.clear();
2479 // Types referencing entries in the address table cannot be placed in type
2481 if (AddrPool.hasBeenUsed()) {
2483 // Remove all the types built while building this type.
2484 // This is pessimistic as some of these types might not be dependent on
2485 // the type that used an address.
2486 for (const auto &TU : TypeUnitsToAdd)
2487 DwarfTypeUnits.erase(TU.second);
2489 // Construct this type in the CU directly.
2490 // This is inefficient because all the dependent types will be rebuilt
2491 // from scratch, including building them in type units, discovering that
2492 // they depend on addresses, throwing them out and rebuilding them.
2493 CU.constructTypeDIE(RefDie, CTy);
2497 // If the type wasn't dependent on fission addresses, finish adding the type
2498 // and all its dependent types.
2499 for (auto &TU : TypeUnitsToAdd)
2500 InfoHolder.addUnit(std::move(TU.first));
2502 CU.addDIETypeSignature(RefDie, NewTU);
2505 // Accelerator table mutators - add each name along with its companion
2506 // DIE to the proper table while ensuring that the name that we're going
2507 // to reference is in the string table. We do this since the names we
2508 // add may not only be identical to the names in the DIE.
2509 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2510 if (!useDwarfAccelTables())
2512 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2516 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2517 if (!useDwarfAccelTables())
2519 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2523 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2524 if (!useDwarfAccelTables())
2526 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2530 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2531 if (!useDwarfAccelTables())
2533 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),