1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "ByteStreamer.h"
15 #include "DwarfDebug.h"
18 #include "DwarfUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DIBuilder.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/Endian.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MD5.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Target/TargetFrameLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
54 #define DEBUG_TYPE "dwarfdebug"
57 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
58 cl::desc("Disable debug info printing"));
60 static cl::opt<bool> UnknownLocations(
61 "use-unknown-locations", cl::Hidden,
62 cl::desc("Make an absence of debug location information explicit."),
66 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
67 cl::desc("Generate GNU-style pubnames and pubtypes"),
70 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
72 cl::desc("Generate dwarf aranges"),
76 enum DefaultOnOff { Default, Enable, Disable };
79 static cl::opt<DefaultOnOff>
80 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
81 cl::desc("Output prototype dwarf accelerator tables."),
82 cl::values(clEnumVal(Default, "Default for platform"),
83 clEnumVal(Enable, "Enabled"),
84 clEnumVal(Disable, "Disabled"), clEnumValEnd),
87 static cl::opt<DefaultOnOff>
88 SplitDwarf("split-dwarf", cl::Hidden,
89 cl::desc("Output DWARF5 split debug info."),
90 cl::values(clEnumVal(Default, "Default for platform"),
91 clEnumVal(Enable, "Enabled"),
92 clEnumVal(Disable, "Disabled"), clEnumValEnd),
95 static cl::opt<DefaultOnOff>
96 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
97 cl::desc("Generate DWARF pubnames and pubtypes sections"),
98 cl::values(clEnumVal(Default, "Default for platform"),
99 clEnumVal(Enable, "Enabled"),
100 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 static const char *const DWARFGroupName = "DWARF Emission";
104 static const char *const DbgTimerName = "DWARF Debug Writer";
106 //===----------------------------------------------------------------------===//
108 /// resolve - Look in the DwarfDebug map for the MDNode that
109 /// corresponds to the reference.
110 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
111 return DD->resolve(Ref);
114 bool DbgVariable::isBlockByrefVariable() const {
115 assert(Var.isVariable() && "Invalid complex DbgVariable!");
116 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
119 DIType DbgVariable::getType() const {
120 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
121 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
122 // addresses instead.
123 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
124 /* Byref variables, in Blocks, are declared by the programmer as
125 "SomeType VarName;", but the compiler creates a
126 __Block_byref_x_VarName struct, and gives the variable VarName
127 either the struct, or a pointer to the struct, as its type. This
128 is necessary for various behind-the-scenes things the compiler
129 needs to do with by-reference variables in blocks.
131 However, as far as the original *programmer* is concerned, the
132 variable should still have type 'SomeType', as originally declared.
134 The following function dives into the __Block_byref_x_VarName
135 struct to find the original type of the variable. This will be
136 passed back to the code generating the type for the Debug
137 Information Entry for the variable 'VarName'. 'VarName' will then
138 have the original type 'SomeType' in its debug information.
140 The original type 'SomeType' will be the type of the field named
141 'VarName' inside the __Block_byref_x_VarName struct.
143 NOTE: In order for this to not completely fail on the debugger
144 side, the Debug Information Entry for the variable VarName needs to
145 have a DW_AT_location that tells the debugger how to unwind through
146 the pointers and __Block_byref_x_VarName struct to find the actual
147 value of the variable. The function addBlockByrefType does this. */
149 uint16_t tag = Ty.getTag();
151 if (tag == dwarf::DW_TAG_pointer_type)
152 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
154 DIArray Elements = DICompositeType(subType).getElements();
155 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
156 DIDerivedType DT(Elements.getElement(i));
157 if (getName() == DT.getName())
158 return (resolve(DT.getTypeDerivedFrom()));
164 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
165 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
166 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
169 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
170 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
171 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
172 UsedNonDefaultText(false),
173 SkeletonHolder(A, "skel_string", DIEValueAllocator),
174 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
175 dwarf::DW_FORM_data4)),
176 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
177 dwarf::DW_FORM_data4)),
178 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
179 dwarf::DW_FORM_data4)),
180 AccelTypes(TypeAtoms) {
182 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
183 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
184 DwarfLineSectionSym = nullptr;
185 DwarfAddrSectionSym = nullptr;
186 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
187 FunctionBeginSym = FunctionEndSym = nullptr;
191 // Turn on accelerator tables for Darwin by default, pubnames by
192 // default for non-Darwin, and handle split dwarf.
193 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
195 if (DwarfAccelTables == Default)
196 HasDwarfAccelTables = IsDarwin;
198 HasDwarfAccelTables = DwarfAccelTables == Enable;
200 if (SplitDwarf == Default)
201 HasSplitDwarf = false;
203 HasSplitDwarf = SplitDwarf == Enable;
205 if (DwarfPubSections == Default)
206 HasDwarfPubSections = !IsDarwin;
208 HasDwarfPubSections = DwarfPubSections == Enable;
210 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
211 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
212 : MMI->getModule()->getDwarfVersion();
214 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
217 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
222 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
223 DwarfDebug::~DwarfDebug() { }
225 // Switch to the specified MCSection and emit an assembler
226 // temporary label to it if SymbolStem is specified.
227 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
228 const char *SymbolStem = nullptr) {
229 Asm->OutStreamer.SwitchSection(Section);
233 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
234 Asm->OutStreamer.EmitLabel(TmpSym);
238 static bool isObjCClass(StringRef Name) {
239 return Name.startswith("+") || Name.startswith("-");
242 static bool hasObjCCategory(StringRef Name) {
243 if (!isObjCClass(Name))
246 return Name.find(") ") != StringRef::npos;
249 static void getObjCClassCategory(StringRef In, StringRef &Class,
250 StringRef &Category) {
251 if (!hasObjCCategory(In)) {
252 Class = In.slice(In.find('[') + 1, In.find(' '));
257 Class = In.slice(In.find('[') + 1, In.find('('));
258 Category = In.slice(In.find('[') + 1, In.find(' '));
262 static StringRef getObjCMethodName(StringRef In) {
263 return In.slice(In.find(' ') + 1, In.find(']'));
266 // Helper for sorting sections into a stable output order.
267 static bool SectionSort(const MCSection *A, const MCSection *B) {
268 std::string LA = (A ? A->getLabelBeginName() : "");
269 std::string LB = (B ? B->getLabelBeginName() : "");
273 // Add the various names to the Dwarf accelerator table names.
274 // TODO: Determine whether or not we should add names for programs
275 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
276 // is only slightly different than the lookup of non-standard ObjC names.
277 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
278 if (!SP.isDefinition())
280 addAccelName(SP.getName(), Die);
282 // If the linkage name is different than the name, go ahead and output
283 // that as well into the name table.
284 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
285 addAccelName(SP.getLinkageName(), Die);
287 // If this is an Objective-C selector name add it to the ObjC accelerator
289 if (isObjCClass(SP.getName())) {
290 StringRef Class, Category;
291 getObjCClassCategory(SP.getName(), Class, Category);
292 addAccelObjC(Class, Die);
294 addAccelObjC(Category, Die);
295 // Also add the base method name to the name table.
296 addAccelName(getObjCMethodName(SP.getName()), Die);
300 /// isSubprogramContext - Return true if Context is either a subprogram
301 /// or another context nested inside a subprogram.
302 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
305 DIDescriptor D(Context);
306 if (D.isSubprogram())
309 return isSubprogramContext(resolve(DIType(Context).getContext()));
313 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
314 // and DW_AT_high_pc attributes. If there are global variables in this
315 // scope then create and insert DIEs for these variables.
316 DIE &DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
318 DIE *SPDie = SPCU.getOrCreateSubprogramDIE(SP);
320 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
322 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
323 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
324 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
326 // Add name to the name table, we do this here because we're guaranteed
327 // to have concrete versions of our DW_TAG_subprogram nodes.
328 addSubprogramNames(SP, *SPDie);
333 /// Check whether we should create a DIE for the given Scope, return true
334 /// if we don't create a DIE (the corresponding DIE is null).
335 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
336 if (Scope->isAbstractScope())
339 // We don't create a DIE if there is no Range.
340 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
344 if (Ranges.size() > 1)
347 // We don't create a DIE if we have a single Range and the end label
349 return !getLabelAfterInsn(Ranges.front().second);
352 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
353 dwarf::Attribute A, const MCSymbol *L,
354 const MCSymbol *Sec) {
355 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
356 U.addSectionLabel(D, A, L);
358 U.addSectionDelta(D, A, L, Sec);
361 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
362 const SmallVectorImpl<InsnRange> &Range) {
363 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
364 // emitting it appropriately.
365 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
367 // Under fission, ranges are specified by constant offsets relative to the
368 // CU's DW_AT_GNU_ranges_base.
370 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
371 DwarfDebugRangeSectionSym);
373 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
374 DwarfDebugRangeSectionSym);
376 RangeSpanList List(RangeSym);
377 for (const InsnRange &R : Range) {
378 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
379 List.addRange(std::move(Span));
382 // Add the range list to the set of ranges to be emitted.
383 TheCU.addRangeList(std::move(List));
386 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
387 const SmallVectorImpl<InsnRange> &Ranges) {
388 assert(!Ranges.empty());
389 if (Ranges.size() == 1)
390 attachLowHighPC(TheCU, Die, getLabelBeforeInsn(Ranges.front().first),
391 getLabelAfterInsn(Ranges.front().second));
393 addScopeRangeList(TheCU, Die, Ranges);
396 // Construct new DW_TAG_lexical_block for this scope and attach
397 // DW_AT_low_pc/DW_AT_high_pc labels.
399 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
400 LexicalScope *Scope) {
401 if (isLexicalScopeDIENull(Scope))
404 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
405 if (Scope->isAbstractScope())
408 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
413 // This scope represents inlined body of a function. Construct DIE to
414 // represent this concrete inlined copy of the function.
416 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
417 LexicalScope *Scope) {
418 assert(Scope->getScopeNode());
419 DIScope DS(Scope->getScopeNode());
420 DISubprogram InlinedSP = getDISubprogram(DS);
421 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
422 // was inlined from another compile unit.
423 DIE *OriginDIE = AbstractSPDies[InlinedSP];
424 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
426 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
427 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
429 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
431 InlinedSubprogramDIEs.insert(OriginDIE);
433 // Add the call site information to the DIE.
434 DILocation DL(Scope->getInlinedAt());
435 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
436 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
437 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
439 // Add name to the name table, we do this here because we're guaranteed
440 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
441 addSubprogramNames(InlinedSP, *ScopeDIE);
446 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
448 const LexicalScope &Scope,
449 DIE *&ObjectPointer) {
450 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
451 if (DV.isObjectPointer())
452 ObjectPointer = Var.get();
456 DIE *DwarfDebug::createScopeChildrenDIE(
457 DwarfCompileUnit &TheCU, LexicalScope *Scope,
458 SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
459 DIE *ObjectPointer = nullptr;
461 // Collect arguments for current function.
462 if (LScopes.isCurrentFunctionScope(Scope)) {
463 for (DbgVariable *ArgDV : CurrentFnArguments)
466 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
468 // If this is a variadic function, add an unspecified parameter.
469 DISubprogram SP(Scope->getScopeNode());
470 DITypeArray FnArgs = SP.getType().getTypeArray();
471 // If we have a single element of null, it is a function that returns void.
472 // If we have more than one elements and the last one is null, it is a
473 // variadic function.
474 if (FnArgs.getNumElements() > 1 &&
475 !FnArgs.getElement(FnArgs.getNumElements() - 1))
477 make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
480 // Collect lexical scope children first.
481 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
482 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
484 for (LexicalScope *LS : Scope->getChildren())
485 if (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
486 Children.push_back(std::move(Nested));
487 return ObjectPointer;
490 void DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
491 LexicalScope *Scope, DIE &ScopeDIE) {
492 // We create children when the scope DIE is not null.
493 SmallVector<std::unique_ptr<DIE>, 8> Children;
494 if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
495 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
498 for (auto &I : Children)
499 ScopeDIE.addChild(std::move(I));
502 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
503 LexicalScope *Scope) {
504 assert(Scope && Scope->getScopeNode());
505 assert(Scope->isAbstractScope());
506 assert(!Scope->getInlinedAt());
508 DISubprogram SP(Scope->getScopeNode());
510 ProcessedSPNodes.insert(SP);
512 DIE *&AbsDef = AbstractSPDies[SP];
516 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
517 // was inlined from another compile unit.
518 DwarfCompileUnit &SPCU = *SPMap[SP];
521 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
522 // the important distinction that the DIDescriptor is not associated with the
523 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
524 // any). It could be refactored to some common utility function.
525 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
526 ContextDIE = &SPCU.getUnitDie();
527 SPCU.getOrCreateSubprogramDIE(SPDecl);
529 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
531 // Passing null as the associated DIDescriptor because the abstract definition
532 // shouldn't be found by lookup.
533 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
535 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
537 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
538 createAndAddScopeChildren(SPCU, Scope, *AbsDef);
541 DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
542 LexicalScope *Scope) {
543 assert(Scope && Scope->getScopeNode());
544 assert(!Scope->getInlinedAt());
545 assert(!Scope->isAbstractScope());
546 DISubprogram Sub(Scope->getScopeNode());
548 assert(Sub.isSubprogram());
550 ProcessedSPNodes.insert(Sub);
552 DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
554 createAndAddScopeChildren(TheCU, Scope, ScopeDIE);
559 // Construct a DIE for this scope.
560 std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
561 LexicalScope *Scope) {
562 if (!Scope || !Scope->getScopeNode())
565 DIScope DS(Scope->getScopeNode());
567 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
568 "Only handle inlined subprograms here, use "
569 "constructSubprogramScopeDIE for non-inlined "
572 SmallVector<std::unique_ptr<DIE>, 8> Children;
574 // We try to create the scope DIE first, then the children DIEs. This will
575 // avoid creating un-used children then removing them later when we find out
576 // the scope DIE is null.
577 std::unique_ptr<DIE> ScopeDIE;
578 if (Scope->getParent() && DS.isSubprogram()) {
579 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
582 // We create children when the scope DIE is not null.
583 createScopeChildrenDIE(TheCU, Scope, Children);
585 // Early exit when we know the scope DIE is going to be null.
586 if (isLexicalScopeDIENull(Scope))
589 // We create children here when we know the scope DIE is not going to be
590 // null and the children will be added to the scope DIE.
591 createScopeChildrenDIE(TheCU, Scope, Children);
593 // There is no need to emit empty lexical block DIE.
594 std::pair<ImportedEntityMap::const_iterator,
595 ImportedEntityMap::const_iterator> Range =
596 std::equal_range(ScopesWithImportedEntities.begin(),
597 ScopesWithImportedEntities.end(),
598 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
600 if (Children.empty() && Range.first == Range.second)
602 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
603 assert(ScopeDIE && "Scope DIE should not be null.");
604 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
607 constructImportedEntityDIE(TheCU, DIImportedEntity(i->second)));
611 for (auto &I : Children)
612 ScopeDIE->addChild(std::move(I));
617 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
618 if (!GenerateGnuPubSections)
621 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
624 // Create new DwarfCompileUnit for the given metadata node with tag
625 // DW_TAG_compile_unit.
626 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
627 StringRef FN = DIUnit.getFilename();
628 CompilationDir = DIUnit.getDirectory();
630 auto OwnedUnit = make_unique<DwarfCompileUnit>(
631 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
632 DwarfCompileUnit &NewCU = *OwnedUnit;
633 DIE &Die = NewCU.getUnitDie();
634 InfoHolder.addUnit(std::move(OwnedUnit));
636 // LTO with assembly output shares a single line table amongst multiple CUs.
637 // To avoid the compilation directory being ambiguous, let the line table
638 // explicitly describe the directory of all files, never relying on the
639 // compilation directory.
640 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
641 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
642 NewCU.getUniqueID(), CompilationDir);
644 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
645 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
646 DIUnit.getLanguage());
647 NewCU.addString(Die, dwarf::DW_AT_name, FN);
649 if (!useSplitDwarf()) {
650 NewCU.initStmtList(DwarfLineSectionSym);
652 // If we're using split dwarf the compilation dir is going to be in the
653 // skeleton CU and so we don't need to duplicate it here.
654 if (!CompilationDir.empty())
655 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
657 addGnuPubAttributes(NewCU, Die);
660 if (DIUnit.isOptimized())
661 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
663 StringRef Flags = DIUnit.getFlags();
665 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
667 if (unsigned RVer = DIUnit.getRunTimeVersion())
668 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
669 dwarf::DW_FORM_data1, RVer);
674 if (useSplitDwarf()) {
675 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
676 DwarfInfoDWOSectionSym);
677 NewCU.setSkeleton(constructSkeletonCU(NewCU));
679 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
680 DwarfInfoSectionSym);
682 CUMap.insert(std::make_pair(DIUnit, &NewCU));
683 CUDieMap.insert(std::make_pair(&Die, &NewCU));
687 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
689 DIImportedEntity Module(N);
690 assert(Module.Verify());
691 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
692 D->addChild(constructImportedEntityDIE(TheCU, Module));
696 DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
697 const DIImportedEntity &Module) {
698 assert(Module.Verify() &&
699 "Use one of the MDNode * overloads to handle invalid metadata");
700 std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
701 TheCU.insertDIE(Module, IMDie.get());
703 DIDescriptor Entity = resolve(Module.getEntity());
704 if (Entity.isNameSpace())
705 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
706 else if (Entity.isSubprogram())
707 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
708 else if (Entity.isType())
709 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
711 EntityDie = TheCU.getDIE(Entity);
713 TheCU.addSourceLine(*IMDie, Module.getLineNumber(),
714 Module.getContext().getFilename(),
715 Module.getContext().getDirectory());
716 TheCU.addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
717 StringRef Name = Module.getName();
719 TheCU.addString(*IMDie, dwarf::DW_AT_name, Name);
724 // Emit all Dwarf sections that should come prior to the content. Create
725 // global DIEs and emit initial debug info sections. This is invoked by
726 // the target AsmPrinter.
727 void DwarfDebug::beginModule() {
728 if (DisableDebugInfoPrinting)
731 const Module *M = MMI->getModule();
733 FunctionDIs = makeSubprogramMap(*M);
735 // If module has named metadata anchors then use them, otherwise scan the
736 // module using debug info finder to collect debug info.
737 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
740 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
742 // Emit initial sections so we can reference labels later.
745 SingleCU = CU_Nodes->getNumOperands() == 1;
747 for (MDNode *N : CU_Nodes->operands()) {
748 DICompileUnit CUNode(N);
749 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
750 DIArray ImportedEntities = CUNode.getImportedEntities();
751 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
752 ScopesWithImportedEntities.push_back(std::make_pair(
753 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
754 ImportedEntities.getElement(i)));
755 std::sort(ScopesWithImportedEntities.begin(),
756 ScopesWithImportedEntities.end(), less_first());
757 DIArray GVs = CUNode.getGlobalVariables();
758 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
759 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
760 DIArray SPs = CUNode.getSubprograms();
761 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
762 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
763 DIArray EnumTypes = CUNode.getEnumTypes();
764 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
765 DIType Ty(EnumTypes.getElement(i));
766 // The enum types array by design contains pointers to
767 // MDNodes rather than DIRefs. Unique them here.
768 DIType UniqueTy(resolve(Ty.getRef()));
769 CU.getOrCreateTypeDIE(UniqueTy);
771 DIArray RetainedTypes = CUNode.getRetainedTypes();
772 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
773 DIType Ty(RetainedTypes.getElement(i));
774 // The retained types array by design contains pointers to
775 // MDNodes rather than DIRefs. Unique them here.
776 DIType UniqueTy(resolve(Ty.getRef()));
777 CU.getOrCreateTypeDIE(UniqueTy);
779 // Emit imported_modules last so that the relevant context is already
781 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
782 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
785 // Tell MMI that we have debug info.
786 MMI->setDebugInfoAvailability(true);
788 // Prime section data.
789 SectionMap[Asm->getObjFileLowering().getTextSection()];
792 void DwarfDebug::finishVariableDefinitions() {
793 for (const auto &Var : ConcreteVariables) {
794 DIE *VariableDie = Var->getDIE();
796 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
797 // in the ConcreteVariables list, rather than looking it up again here.
798 // DIE::getUnit isn't simple - it walks parent pointers, etc.
799 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
801 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
802 if (AbsVar && AbsVar->getDIE()) {
803 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
806 Unit->applyVariableAttributes(*Var, *VariableDie);
810 void DwarfDebug::finishSubprogramDefinitions() {
811 const Module *M = MMI->getModule();
813 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
814 for (MDNode *N : CU_Nodes->operands()) {
815 DICompileUnit TheCU(N);
816 // Construct subprogram DIE and add variables DIEs.
817 DwarfCompileUnit *SPCU =
818 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
819 DIArray Subprograms = TheCU.getSubprograms();
820 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
821 DISubprogram SP(Subprograms.getElement(i));
822 // Perhaps the subprogram is in another CU (such as due to comdat
823 // folding, etc), in which case ignore it here.
824 if (SPMap[SP] != SPCU)
826 DIE *D = SPCU->getDIE(SP);
827 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
829 // If this subprogram has an abstract definition, reference that
830 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
833 // Lazily construct the subprogram if we didn't see either concrete or
834 // inlined versions during codegen.
835 D = SPCU->getOrCreateSubprogramDIE(SP);
836 // And attach the attributes
837 SPCU->applySubprogramAttributesToDefinition(SP, *D);
844 // Collect info for variables that were optimized out.
845 void DwarfDebug::collectDeadVariables() {
846 const Module *M = MMI->getModule();
848 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
849 for (MDNode *N : CU_Nodes->operands()) {
850 DICompileUnit TheCU(N);
851 // Construct subprogram DIE and add variables DIEs.
852 DwarfCompileUnit *SPCU =
853 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
854 assert(SPCU && "Unable to find Compile Unit!");
855 DIArray Subprograms = TheCU.getSubprograms();
856 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
857 DISubprogram SP(Subprograms.getElement(i));
858 if (ProcessedSPNodes.count(SP) != 0)
860 assert(SP.isSubprogram() &&
861 "CU's subprogram list contains a non-subprogram");
862 assert(SP.isDefinition() &&
863 "CU's subprogram list contains a subprogram declaration");
864 DIArray Variables = SP.getVariables();
865 if (Variables.getNumElements() == 0)
868 DIE *SPDIE = AbstractSPDies.lookup(SP);
870 SPDIE = SPCU->getDIE(SP);
872 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
873 DIVariable DV(Variables.getElement(vi));
874 assert(DV.isVariable());
875 DbgVariable NewVar(DV, this);
876 auto VariableDie = SPCU->constructVariableDIE(NewVar);
877 SPCU->applyVariableAttributes(NewVar, *VariableDie);
878 SPDIE->addChild(std::move(VariableDie));
885 void DwarfDebug::finalizeModuleInfo() {
886 finishSubprogramDefinitions();
888 finishVariableDefinitions();
890 // Collect info for variables that were optimized out.
891 collectDeadVariables();
893 // Handle anything that needs to be done on a per-unit basis after
894 // all other generation.
895 for (const auto &TheU : getUnits()) {
896 // Emit DW_AT_containing_type attribute to connect types with their
897 // vtable holding type.
898 TheU->constructContainingTypeDIEs();
900 // Add CU specific attributes if we need to add any.
901 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
902 // If we're splitting the dwarf out now that we've got the entire
903 // CU then add the dwo id to it.
904 DwarfCompileUnit *SkCU =
905 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
906 if (useSplitDwarf()) {
907 // Emit a unique identifier for this CU.
908 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
909 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
910 dwarf::DW_FORM_data8, ID);
911 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
912 dwarf::DW_FORM_data8, ID);
914 // We don't keep track of which addresses are used in which CU so this
915 // is a bit pessimistic under LTO.
916 if (!AddrPool.isEmpty())
917 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
918 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
919 DwarfAddrSectionSym);
920 if (!TheU->getRangeLists().empty())
921 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
922 dwarf::DW_AT_GNU_ranges_base,
923 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
926 // If we have code split among multiple sections or non-contiguous
927 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
928 // remain in the .o file, otherwise add a DW_AT_low_pc.
929 // FIXME: We should use ranges allow reordering of code ala
930 // .subsections_via_symbols in mach-o. This would mean turning on
931 // ranges for all subprogram DIEs for mach-o.
932 DwarfCompileUnit &U =
933 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
934 unsigned NumRanges = TheU->getRanges().size();
937 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
938 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
939 DwarfDebugRangeSectionSym);
941 // A DW_AT_low_pc attribute may also be specified in combination with
942 // DW_AT_ranges to specify the default base address for use in
943 // location lists (see Section 2.6.2) and range lists (see Section
945 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
948 RangeSpan &Range = TheU->getRanges().back();
949 attachLowHighPC(U, U.getUnitDie(), Range.getStart(), Range.getEnd());
955 // Compute DIE offsets and sizes.
956 InfoHolder.computeSizeAndOffsets();
958 SkeletonHolder.computeSizeAndOffsets();
961 void DwarfDebug::endSections() {
962 // Filter labels by section.
963 for (const SymbolCU &SCU : ArangeLabels) {
964 if (SCU.Sym->isInSection()) {
965 // Make a note of this symbol and it's section.
966 const MCSection *Section = &SCU.Sym->getSection();
967 if (!Section->getKind().isMetadata())
968 SectionMap[Section].push_back(SCU);
970 // Some symbols (e.g. common/bss on mach-o) can have no section but still
971 // appear in the output. This sucks as we rely on sections to build
972 // arange spans. We can do it without, but it's icky.
973 SectionMap[nullptr].push_back(SCU);
977 // Build a list of sections used.
978 std::vector<const MCSection *> Sections;
979 for (const auto &it : SectionMap) {
980 const MCSection *Section = it.first;
981 Sections.push_back(Section);
984 // Sort the sections into order.
985 // This is only done to ensure consistent output order across different runs.
986 std::sort(Sections.begin(), Sections.end(), SectionSort);
988 // Add terminating symbols for each section.
989 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
990 const MCSection *Section = Sections[ID];
991 MCSymbol *Sym = nullptr;
994 // We can't call MCSection::getLabelEndName, as it's only safe to do so
995 // if we know the section name up-front. For user-created sections, the
996 // resulting label may not be valid to use as a label. (section names can
997 // use a greater set of characters on some systems)
998 Sym = Asm->GetTempSymbol("debug_end", ID);
999 Asm->OutStreamer.SwitchSection(Section);
1000 Asm->OutStreamer.EmitLabel(Sym);
1003 // Insert a final terminator.
1004 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1008 // Emit all Dwarf sections that should come after the content.
1009 void DwarfDebug::endModule() {
1010 assert(CurFn == nullptr);
1011 assert(CurMI == nullptr);
1016 // End any existing sections.
1017 // TODO: Does this need to happen?
1020 // Finalize the debug info for the module.
1021 finalizeModuleInfo();
1025 // Emit all the DIEs into a debug info section.
1028 // Corresponding abbreviations into a abbrev section.
1029 emitAbbreviations();
1031 // Emit info into a debug aranges section.
1032 if (GenerateARangeSection)
1035 // Emit info into a debug ranges section.
1038 if (useSplitDwarf()) {
1041 emitDebugAbbrevDWO();
1044 // Emit DWO addresses.
1045 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1047 // Emit info into a debug loc section.
1050 // Emit info into the dwarf accelerator table sections.
1051 if (useDwarfAccelTables()) {
1054 emitAccelNamespaces();
1058 // Emit the pubnames and pubtypes sections if requested.
1059 if (HasDwarfPubSections) {
1060 emitDebugPubNames(GenerateGnuPubSections);
1061 emitDebugPubTypes(GenerateGnuPubSections);
1066 AbstractVariables.clear();
1068 // Reset these for the next Module if we have one.
1072 // Find abstract variable, if any, associated with Var.
1073 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
1074 DIVariable &Cleansed) {
1075 LLVMContext &Ctx = DV->getContext();
1076 // More then one inlined variable corresponds to one abstract variable.
1077 // FIXME: This duplication of variables when inlining should probably be
1078 // removed. It's done to allow each DIVariable to describe its location
1079 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
1080 // make it accurate then remove this duplication/cleansing stuff.
1081 Cleansed = cleanseInlinedVariable(DV, Ctx);
1082 auto I = AbstractVariables.find(Cleansed);
1083 if (I != AbstractVariables.end())
1084 return I->second.get();
1088 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
1089 DIVariable Cleansed;
1090 return getExistingAbstractVariable(DV, Cleansed);
1093 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
1094 LexicalScope *Scope) {
1095 auto AbsDbgVariable = make_unique<DbgVariable>(Var, this);
1096 addScopeVariable(Scope, AbsDbgVariable.get());
1097 AbstractVariables[Var] = std::move(AbsDbgVariable);
1100 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
1101 const MDNode *ScopeNode) {
1102 DIVariable Cleansed = DV;
1103 if (getExistingAbstractVariable(DV, Cleansed))
1106 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
1110 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
1111 const MDNode *ScopeNode) {
1112 DIVariable Cleansed = DV;
1113 if (getExistingAbstractVariable(DV, Cleansed))
1116 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
1117 createAbstractVariable(Cleansed, Scope);
1120 // If Var is a current function argument then add it to CurrentFnArguments list.
1121 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1122 if (!LScopes.isCurrentFunctionScope(Scope))
1124 DIVariable DV = Var->getVariable();
1125 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1127 unsigned ArgNo = DV.getArgNumber();
1131 size_t Size = CurrentFnArguments.size();
1133 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1134 // llvm::Function argument size is not good indicator of how many
1135 // arguments does the function have at source level.
1137 CurrentFnArguments.resize(ArgNo * 2);
1138 assert(!CurrentFnArguments[ArgNo - 1]);
1139 CurrentFnArguments[ArgNo - 1] = Var;
1143 // Collect variable information from side table maintained by MMI.
1144 void DwarfDebug::collectVariableInfoFromMMITable(
1145 SmallPtrSetImpl<const MDNode *> &Processed) {
1146 for (const auto &VI : MMI->getVariableDbgInfo()) {
1149 Processed.insert(VI.Var);
1150 DIVariable DV(VI.Var);
1151 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1153 // If variable scope is not found then skip this variable.
1157 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1158 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, this));
1159 DbgVariable *RegVar = ConcreteVariables.back().get();
1160 RegVar->setFrameIndex(VI.Slot);
1161 addScopeVariable(Scope, RegVar);
1165 // Get .debug_loc entry for the instruction range starting at MI.
1166 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1167 const MDNode *Var = MI->getDebugVariable();
1169 assert(MI->getNumOperands() == 3);
1170 if (MI->getOperand(0).isReg()) {
1171 MachineLocation MLoc;
1172 // If the second operand is an immediate, this is a
1173 // register-indirect address.
1174 if (!MI->getOperand(1).isImm())
1175 MLoc.set(MI->getOperand(0).getReg());
1177 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1178 return DebugLocEntry::Value(Var, MLoc);
1180 if (MI->getOperand(0).isImm())
1181 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1182 if (MI->getOperand(0).isFPImm())
1183 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1184 if (MI->getOperand(0).isCImm())
1185 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1187 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1190 /// Determine whether two variable pieces overlap.
1191 static bool piecesOverlap(DIVariable P1, DIVariable P2) {
1192 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1194 unsigned l1 = P1.getPieceOffset();
1195 unsigned l2 = P2.getPieceOffset();
1196 unsigned r1 = l1 + P1.getPieceSize();
1197 unsigned r2 = l2 + P2.getPieceSize();
1198 // True where [l1,r1[ and [r1,r2[ overlap.
1199 return (l1 < r2) && (l2 < r1);
1202 /// Build the location list for all DBG_VALUEs in the function that
1203 /// describe the same variable. If the ranges of several independent
1204 /// pieces of the same variable overlap partially, split them up and
1205 /// combine the ranges. The resulting DebugLocEntries are will have
1206 /// strict monotonically increasing begin addresses and will never
1211 // Ranges History [var, loc, piece ofs size]
1212 // 0 | [x, (reg0, piece 0, 32)]
1213 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1215 // 3 | [clobber reg0]
1216 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1220 // [0-1] [x, (reg0, piece 0, 32)]
1221 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1222 // [3-4] [x, (reg1, piece 32, 32)]
1223 // [4- ] [x, (mem, piece 0, 64)]
1225 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1226 const DbgValueHistoryMap::InstrRanges &Ranges) {
1227 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1229 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1230 const MachineInstr *Begin = I->first;
1231 const MachineInstr *End = I->second;
1232 assert(Begin->isDebugValue() && "Invalid History entry");
1234 // Check if a variable is inaccessible in this range.
1235 if (Begin->getNumOperands() > 1 &&
1236 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1241 // If this piece overlaps with any open ranges, truncate them.
1242 DIVariable DIVar = Begin->getDebugVariable();
1243 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1244 [&](DebugLocEntry::Value R) {
1245 return piecesOverlap(DIVar, R.getVariable());
1247 OpenRanges.erase(Last, OpenRanges.end());
1249 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1250 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1252 const MCSymbol *EndLabel;
1254 EndLabel = getLabelAfterInsn(End);
1255 else if (std::next(I) == Ranges.end())
1256 EndLabel = FunctionEndSym;
1258 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1259 assert(EndLabel && "Forgot label after instruction ending a range!");
1261 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1263 auto Value = getDebugLocValue(Begin);
1264 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1265 bool couldMerge = false;
1267 // If this is a piece, it may belong to the current DebugLocEntry.
1268 if (DIVar.isVariablePiece()) {
1269 // Add this value to the list of open ranges.
1270 OpenRanges.push_back(Value);
1272 // Attempt to add the piece to the last entry.
1273 if (!DebugLoc.empty())
1274 if (DebugLoc.back().MergeValues(Loc))
1279 // Need to add a new DebugLocEntry. Add all values from still
1280 // valid non-overlapping pieces.
1281 if (OpenRanges.size())
1282 Loc.addValues(OpenRanges);
1284 DebugLoc.push_back(std::move(Loc));
1287 // Attempt to coalesce the ranges of two otherwise identical
1289 auto CurEntry = DebugLoc.rbegin();
1290 auto PrevEntry = std::next(CurEntry);
1291 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1292 DebugLoc.pop_back();
1294 DEBUG(dbgs() << "Values:\n";
1295 for (auto Value : CurEntry->getValues())
1296 Value.getVariable()->dump();
1297 dbgs() << "-----\n");
1302 // Find variables for each lexical scope.
1304 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1305 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1306 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1308 // Grab the variable info that was squirreled away in the MMI side-table.
1309 collectVariableInfoFromMMITable(Processed);
1311 for (const auto &I : DbgValues) {
1312 DIVariable DV(I.first);
1313 if (Processed.count(DV))
1316 // Instruction ranges, specifying where DV is accessible.
1317 const auto &Ranges = I.second;
1321 LexicalScope *Scope = nullptr;
1322 if (MDNode *IA = DV.getInlinedAt()) {
1323 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1324 Scope = LScopes.findInlinedScope(DebugLoc::get(
1325 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1327 Scope = LScopes.findLexicalScope(DV.getContext());
1328 // If variable scope is not found then skip this variable.
1332 Processed.insert(getEntireVariable(DV));
1333 const MachineInstr *MInsn = Ranges.front().first;
1334 assert(MInsn->isDebugValue() && "History must begin with debug value");
1335 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1336 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1337 DbgVariable *RegVar = ConcreteVariables.back().get();
1338 addScopeVariable(Scope, RegVar);
1340 // Check if the first DBG_VALUE is valid for the rest of the function.
1341 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1344 // Handle multiple DBG_VALUE instructions describing one variable.
1345 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1347 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1348 DebugLocList &LocList = DotDebugLocEntries.back();
1351 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1353 // Build the location list for this variable.
1354 buildLocationList(LocList.List, Ranges);
1357 // Collect info for variables that were optimized out.
1358 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1359 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1360 DIVariable DV(Variables.getElement(i));
1361 assert(DV.isVariable());
1362 if (!Processed.insert(DV))
1364 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1365 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1366 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, this));
1367 addScopeVariable(Scope, ConcreteVariables.back().get());
1372 // Return Label preceding the instruction.
1373 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1374 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1375 assert(Label && "Didn't insert label before instruction");
1379 // Return Label immediately following the instruction.
1380 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1381 return LabelsAfterInsn.lookup(MI);
1384 // Process beginning of an instruction.
1385 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1386 assert(CurMI == nullptr);
1388 // Check if source location changes, but ignore DBG_VALUE locations.
1389 if (!MI->isDebugValue()) {
1390 DebugLoc DL = MI->getDebugLoc();
1391 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1394 if (DL == PrologEndLoc) {
1395 Flags |= DWARF2_FLAG_PROLOGUE_END;
1396 PrologEndLoc = DebugLoc();
1398 if (PrologEndLoc.isUnknown())
1399 Flags |= DWARF2_FLAG_IS_STMT;
1401 if (!DL.isUnknown()) {
1402 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1403 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1405 recordSourceLine(0, 0, nullptr, 0);
1409 // Insert labels where requested.
1410 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1411 LabelsBeforeInsn.find(MI);
1414 if (I == LabelsBeforeInsn.end())
1417 // Label already assigned.
1422 PrevLabel = MMI->getContext().CreateTempSymbol();
1423 Asm->OutStreamer.EmitLabel(PrevLabel);
1425 I->second = PrevLabel;
1428 // Process end of an instruction.
1429 void DwarfDebug::endInstruction() {
1430 assert(CurMI != nullptr);
1431 // Don't create a new label after DBG_VALUE instructions.
1432 // They don't generate code.
1433 if (!CurMI->isDebugValue())
1434 PrevLabel = nullptr;
1436 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1437 LabelsAfterInsn.find(CurMI);
1441 if (I == LabelsAfterInsn.end())
1444 // Label already assigned.
1448 // We need a label after this instruction.
1450 PrevLabel = MMI->getContext().CreateTempSymbol();
1451 Asm->OutStreamer.EmitLabel(PrevLabel);
1453 I->second = PrevLabel;
1456 // Each LexicalScope has first instruction and last instruction to mark
1457 // beginning and end of a scope respectively. Create an inverse map that list
1458 // scopes starts (and ends) with an instruction. One instruction may start (or
1459 // end) multiple scopes. Ignore scopes that are not reachable.
1460 void DwarfDebug::identifyScopeMarkers() {
1461 SmallVector<LexicalScope *, 4> WorkList;
1462 WorkList.push_back(LScopes.getCurrentFunctionScope());
1463 while (!WorkList.empty()) {
1464 LexicalScope *S = WorkList.pop_back_val();
1466 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1467 if (!Children.empty())
1468 WorkList.append(Children.begin(), Children.end());
1470 if (S->isAbstractScope())
1473 for (const InsnRange &R : S->getRanges()) {
1474 assert(R.first && "InsnRange does not have first instruction!");
1475 assert(R.second && "InsnRange does not have second instruction!");
1476 requestLabelBeforeInsn(R.first);
1477 requestLabelAfterInsn(R.second);
1482 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1483 // First known non-DBG_VALUE and non-frame setup location marks
1484 // the beginning of the function body.
1485 for (const auto &MBB : *MF)
1486 for (const auto &MI : MBB)
1487 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1488 !MI.getDebugLoc().isUnknown())
1489 return MI.getDebugLoc();
1493 // Gather pre-function debug information. Assumes being called immediately
1494 // after the function entry point has been emitted.
1495 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1498 // If there's no debug info for the function we're not going to do anything.
1499 if (!MMI->hasDebugInfo())
1502 auto DI = FunctionDIs.find(MF->getFunction());
1503 if (DI == FunctionDIs.end())
1506 // Grab the lexical scopes for the function, if we don't have any of those
1507 // then we're not going to be able to do anything.
1508 LScopes.initialize(*MF);
1509 if (LScopes.empty())
1512 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1514 // Make sure that each lexical scope will have a begin/end label.
1515 identifyScopeMarkers();
1517 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1518 // belongs to so that we add to the correct per-cu line table in the
1520 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1521 // FnScope->getScopeNode() and DI->second should represent the same function,
1522 // though they may not be the same MDNode due to inline functions merged in
1523 // LTO where the debug info metadata still differs (either due to distinct
1524 // written differences - two versions of a linkonce_odr function
1525 // written/copied into two separate files, or some sub-optimal metadata that
1526 // isn't structurally identical (see: file path/name info from clang, which
1527 // includes the directory of the cpp file being built, even when the file name
1528 // is absolute (such as an <> lookup header)))
1529 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1530 assert(TheCU && "Unable to find compile unit!");
1531 if (Asm->OutStreamer.hasRawTextSupport())
1532 // Use a single line table if we are generating assembly.
1533 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1535 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1537 // Emit a label for the function so that we have a beginning address.
1538 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1539 // Assumes in correct section after the entry point.
1540 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1542 // Calculate history for local variables.
1543 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1546 // Request labels for the full history.
1547 for (const auto &I : DbgValues) {
1548 const auto &Ranges = I.second;
1552 // The first mention of a function argument gets the FunctionBeginSym
1553 // label, so arguments are visible when breaking at function entry.
1554 DIVariable DV(Ranges.front().first->getDebugVariable());
1555 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1556 getDISubprogram(DV.getContext()).describes(MF->getFunction())) {
1557 if (!DV.isVariablePiece())
1558 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1560 // Mark all non-overlapping initial pieces.
1561 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1562 DIVariable Piece = I->first->getDebugVariable();
1563 if (std::all_of(Ranges.begin(), I,
1564 [&](DbgValueHistoryMap::InstrRange Pred){
1565 return !piecesOverlap(Piece, Pred.first->getDebugVariable());
1567 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1574 for (const auto &Range : Ranges) {
1575 requestLabelBeforeInsn(Range.first);
1577 requestLabelAfterInsn(Range.second);
1581 PrevInstLoc = DebugLoc();
1582 PrevLabel = FunctionBeginSym;
1584 // Record beginning of function.
1585 PrologEndLoc = findPrologueEndLoc(MF);
1586 if (!PrologEndLoc.isUnknown()) {
1587 DebugLoc FnStartDL =
1588 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1590 FnStartDL.getLine(), FnStartDL.getCol(),
1591 FnStartDL.getScope(MF->getFunction()->getContext()),
1592 // We'd like to list the prologue as "not statements" but GDB behaves
1593 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1594 DWARF2_FLAG_IS_STMT);
1598 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1599 if (addCurrentFnArgument(Var, LS))
1601 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1602 DIVariable DV = Var->getVariable();
1603 // Variables with positive arg numbers are parameters.
1604 if (unsigned ArgNum = DV.getArgNumber()) {
1605 // Keep all parameters in order at the start of the variable list to ensure
1606 // function types are correct (no out-of-order parameters)
1608 // This could be improved by only doing it for optimized builds (unoptimized
1609 // builds have the right order to begin with), searching from the back (this
1610 // would catch the unoptimized case quickly), or doing a binary search
1611 // rather than linear search.
1612 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1613 while (I != Vars.end()) {
1614 unsigned CurNum = (*I)->getVariable().getArgNumber();
1615 // A local (non-parameter) variable has been found, insert immediately
1619 // A later indexed parameter has been found, insert immediately before it.
1620 if (CurNum > ArgNum)
1624 Vars.insert(I, Var);
1628 Vars.push_back(Var);
1631 // Gather and emit post-function debug information.
1632 void DwarfDebug::endFunction(const MachineFunction *MF) {
1633 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1634 // though the beginFunction may not be called at all.
1635 // We should handle both cases.
1639 assert(CurFn == MF);
1640 assert(CurFn != nullptr);
1642 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1643 !FunctionDIs.count(MF->getFunction())) {
1644 // If we don't have a lexical scope for this function then there will
1645 // be a hole in the range information. Keep note of this by setting the
1646 // previously used section to nullptr.
1647 PrevSection = nullptr;
1653 // Define end label for subprogram.
1654 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1655 // Assumes in correct section after the entry point.
1656 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1658 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1659 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1661 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1662 collectVariableInfo(ProcessedVars);
1664 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1665 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1667 // Construct abstract scopes.
1668 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1669 DISubprogram SP(AScope->getScopeNode());
1670 assert(SP.isSubprogram());
1671 // Collect info for variables that were optimized out.
1672 DIArray Variables = SP.getVariables();
1673 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1674 DIVariable DV(Variables.getElement(i));
1675 assert(DV && DV.isVariable());
1676 if (!ProcessedVars.insert(DV))
1678 ensureAbstractVariableIsCreated(DV, DV.getContext());
1680 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1683 DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
1684 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1685 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1687 // Add the range of this function to the list of ranges for the CU.
1688 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1689 TheCU.addRange(std::move(Span));
1690 PrevSection = Asm->getCurrentSection();
1694 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1695 // DbgVariables except those that are also in AbstractVariables (since they
1696 // can be used cross-function)
1697 ScopeVariables.clear();
1698 CurrentFnArguments.clear();
1700 LabelsBeforeInsn.clear();
1701 LabelsAfterInsn.clear();
1702 PrevLabel = nullptr;
1706 // Register a source line with debug info. Returns the unique label that was
1707 // emitted and which provides correspondence to the source line list.
1708 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1713 unsigned Discriminator = 0;
1714 if (DIScope Scope = DIScope(S)) {
1715 assert(Scope.isScope());
1716 Fn = Scope.getFilename();
1717 Dir = Scope.getDirectory();
1718 if (Scope.isLexicalBlockFile())
1719 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1721 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1722 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1723 .getOrCreateSourceID(Fn, Dir);
1725 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1729 //===----------------------------------------------------------------------===//
1731 //===----------------------------------------------------------------------===//
1733 // Emit initial Dwarf sections with a label at the start of each one.
1734 void DwarfDebug::emitSectionLabels() {
1735 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1737 // Dwarf sections base addresses.
1738 DwarfInfoSectionSym =
1739 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1740 if (useSplitDwarf()) {
1741 DwarfInfoDWOSectionSym =
1742 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1743 DwarfTypesDWOSectionSym =
1744 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1746 DwarfAbbrevSectionSym =
1747 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1748 if (useSplitDwarf())
1749 DwarfAbbrevDWOSectionSym = emitSectionSym(
1750 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1751 if (GenerateARangeSection)
1752 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1754 DwarfLineSectionSym =
1755 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1756 if (GenerateGnuPubSections) {
1757 DwarfGnuPubNamesSectionSym =
1758 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1759 DwarfGnuPubTypesSectionSym =
1760 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1761 } else if (HasDwarfPubSections) {
1762 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1763 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1766 DwarfStrSectionSym =
1767 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1768 if (useSplitDwarf()) {
1769 DwarfStrDWOSectionSym =
1770 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1771 DwarfAddrSectionSym =
1772 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1773 DwarfDebugLocSectionSym =
1774 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1776 DwarfDebugLocSectionSym =
1777 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1778 DwarfDebugRangeSectionSym =
1779 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1782 // Recursively emits a debug information entry.
1783 void DwarfDebug::emitDIE(DIE &Die) {
1784 // Get the abbreviation for this DIE.
1785 const DIEAbbrev &Abbrev = Die.getAbbrev();
1787 // Emit the code (index) for the abbreviation.
1788 if (Asm->isVerbose())
1789 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1790 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1791 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1792 dwarf::TagString(Abbrev.getTag()));
1793 Asm->EmitULEB128(Abbrev.getNumber());
1795 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1796 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1798 // Emit the DIE attribute values.
1799 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1800 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1801 dwarf::Form Form = AbbrevData[i].getForm();
1802 assert(Form && "Too many attributes for DIE (check abbreviation)");
1804 if (Asm->isVerbose()) {
1805 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1806 if (Attr == dwarf::DW_AT_accessibility)
1807 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1808 cast<DIEInteger>(Values[i])->getValue()));
1811 // Emit an attribute using the defined form.
1812 Values[i]->EmitValue(Asm, Form);
1815 // Emit the DIE children if any.
1816 if (Abbrev.hasChildren()) {
1817 for (auto &Child : Die.getChildren())
1820 Asm->OutStreamer.AddComment("End Of Children Mark");
1825 // Emit the debug info section.
1826 void DwarfDebug::emitDebugInfo() {
1827 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1829 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1832 // Emit the abbreviation section.
1833 void DwarfDebug::emitAbbreviations() {
1834 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1836 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1839 // Emit the last address of the section and the end of the line matrix.
1840 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1841 // Define last address of section.
1842 Asm->OutStreamer.AddComment("Extended Op");
1845 Asm->OutStreamer.AddComment("Op size");
1846 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1847 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1848 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1850 Asm->OutStreamer.AddComment("Section end label");
1852 Asm->OutStreamer.EmitSymbolValue(
1853 Asm->GetTempSymbol("section_end", SectionEnd),
1854 Asm->getDataLayout().getPointerSize());
1856 // Mark end of matrix.
1857 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1863 // Emit visible names into a hashed accelerator table section.
1864 void DwarfDebug::emitAccelNames() {
1865 AccelNames.FinalizeTable(Asm, "Names");
1866 Asm->OutStreamer.SwitchSection(
1867 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1868 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1869 Asm->OutStreamer.EmitLabel(SectionBegin);
1871 // Emit the full data.
1872 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1875 // Emit objective C classes and categories into a hashed accelerator table
1877 void DwarfDebug::emitAccelObjC() {
1878 AccelObjC.FinalizeTable(Asm, "ObjC");
1879 Asm->OutStreamer.SwitchSection(
1880 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1881 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1882 Asm->OutStreamer.EmitLabel(SectionBegin);
1884 // Emit the full data.
1885 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1888 // Emit namespace dies into a hashed accelerator table.
1889 void DwarfDebug::emitAccelNamespaces() {
1890 AccelNamespace.FinalizeTable(Asm, "namespac");
1891 Asm->OutStreamer.SwitchSection(
1892 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1893 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1894 Asm->OutStreamer.EmitLabel(SectionBegin);
1896 // Emit the full data.
1897 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1900 // Emit type dies into a hashed accelerator table.
1901 void DwarfDebug::emitAccelTypes() {
1903 AccelTypes.FinalizeTable(Asm, "types");
1904 Asm->OutStreamer.SwitchSection(
1905 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1906 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1907 Asm->OutStreamer.EmitLabel(SectionBegin);
1909 // Emit the full data.
1910 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1913 // Public name handling.
1914 // The format for the various pubnames:
1916 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1917 // for the DIE that is named.
1919 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1920 // into the CU and the index value is computed according to the type of value
1921 // for the DIE that is named.
1923 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1924 // it's the offset within the debug_info/debug_types dwo section, however, the
1925 // reference in the pubname header doesn't change.
1927 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1928 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1930 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1932 // We could have a specification DIE that has our most of our knowledge,
1933 // look for that now.
1934 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1936 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1937 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1938 Linkage = dwarf::GIEL_EXTERNAL;
1939 } else if (Die->findAttribute(dwarf::DW_AT_external))
1940 Linkage = dwarf::GIEL_EXTERNAL;
1942 switch (Die->getTag()) {
1943 case dwarf::DW_TAG_class_type:
1944 case dwarf::DW_TAG_structure_type:
1945 case dwarf::DW_TAG_union_type:
1946 case dwarf::DW_TAG_enumeration_type:
1947 return dwarf::PubIndexEntryDescriptor(
1948 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1949 ? dwarf::GIEL_STATIC
1950 : dwarf::GIEL_EXTERNAL);
1951 case dwarf::DW_TAG_typedef:
1952 case dwarf::DW_TAG_base_type:
1953 case dwarf::DW_TAG_subrange_type:
1954 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1955 case dwarf::DW_TAG_namespace:
1956 return dwarf::GIEK_TYPE;
1957 case dwarf::DW_TAG_subprogram:
1958 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1959 case dwarf::DW_TAG_constant:
1960 case dwarf::DW_TAG_variable:
1961 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1962 case dwarf::DW_TAG_enumerator:
1963 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1964 dwarf::GIEL_STATIC);
1966 return dwarf::GIEK_NONE;
1970 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1972 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1973 const MCSection *PSec =
1974 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1975 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1977 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1980 void DwarfDebug::emitDebugPubSection(
1981 bool GnuStyle, const MCSection *PSec, StringRef Name,
1982 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1983 for (const auto &NU : CUMap) {
1984 DwarfCompileUnit *TheU = NU.second;
1986 const auto &Globals = (TheU->*Accessor)();
1988 if (Globals.empty())
1991 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1993 unsigned ID = TheU->getUniqueID();
1995 // Start the dwarf pubnames section.
1996 Asm->OutStreamer.SwitchSection(PSec);
1999 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2000 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2001 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2002 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2004 Asm->OutStreamer.EmitLabel(BeginLabel);
2006 Asm->OutStreamer.AddComment("DWARF Version");
2007 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2009 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2010 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2012 Asm->OutStreamer.AddComment("Compilation Unit Length");
2013 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2015 // Emit the pubnames for this compilation unit.
2016 for (const auto &GI : Globals) {
2017 const char *Name = GI.getKeyData();
2018 const DIE *Entity = GI.second;
2020 Asm->OutStreamer.AddComment("DIE offset");
2021 Asm->EmitInt32(Entity->getOffset());
2024 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2025 Asm->OutStreamer.AddComment(
2026 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2027 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2028 Asm->EmitInt8(Desc.toBits());
2031 Asm->OutStreamer.AddComment("External Name");
2032 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2035 Asm->OutStreamer.AddComment("End Mark");
2037 Asm->OutStreamer.EmitLabel(EndLabel);
2041 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2042 const MCSection *PSec =
2043 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2044 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2046 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2049 // Emit visible names into a debug str section.
2050 void DwarfDebug::emitDebugStr() {
2051 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2052 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2055 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
2056 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
2057 const DITypeIdentifierMap &Map,
2058 ArrayRef<DebugLocEntry::Value> Values) {
2059 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
2060 return P.isVariablePiece();
2061 }) && "all values are expected to be pieces");
2062 assert(std::is_sorted(Values.begin(), Values.end()) &&
2063 "pieces are expected to be sorted");
2065 unsigned Offset = 0;
2066 for (auto Piece : Values) {
2067 DIVariable Var = Piece.getVariable();
2068 unsigned PieceOffset = Var.getPieceOffset();
2069 unsigned PieceSize = Var.getPieceSize();
2070 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
2071 if (Offset < PieceOffset) {
2072 // The DWARF spec seriously mandates pieces with no locations for gaps.
2073 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
2074 Offset += PieceOffset-Offset;
2077 Offset += PieceSize;
2079 const unsigned SizeOfByte = 8;
2080 assert(!Var.isIndirect() && "indirect address for piece");
2082 unsigned VarSize = Var.getSizeInBits(Map);
2083 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
2084 && "piece is larger than or outside of variable");
2085 assert(PieceSize*SizeOfByte != VarSize
2086 && "piece covers entire variable");
2088 if (Piece.isLocation() && Piece.getLoc().isReg())
2089 Asm->EmitDwarfRegOpPiece(Streamer,
2091 PieceSize*SizeOfByte);
2093 emitDebugLocValue(Streamer, Piece);
2094 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
2100 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2101 const DebugLocEntry &Entry) {
2102 const DebugLocEntry::Value Value = Entry.getValues()[0];
2103 if (Value.isVariablePiece())
2104 // Emit all pieces that belong to the same variable and range.
2105 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
2107 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
2108 emitDebugLocValue(Streamer, Value);
2111 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
2112 const DebugLocEntry::Value &Value) {
2113 DIVariable DV = Value.getVariable();
2115 if (Value.isInt()) {
2116 DIBasicType BTy(resolve(DV.getType()));
2117 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2118 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2119 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2120 Streamer.EmitSLEB128(Value.getInt());
2122 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2123 Streamer.EmitULEB128(Value.getInt());
2125 } else if (Value.isLocation()) {
2126 MachineLocation Loc = Value.getLoc();
2127 if (!DV.hasComplexAddress())
2129 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2131 // Complex address entry.
2132 unsigned N = DV.getNumAddrElements();
2134 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2135 if (Loc.getOffset()) {
2137 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2138 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2139 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2140 Streamer.EmitSLEB128(DV.getAddrElement(1));
2142 // If first address element is OpPlus then emit
2143 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2144 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2145 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2149 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2152 // Emit remaining complex address elements.
2153 for (; i < N; ++i) {
2154 uint64_t Element = DV.getAddrElement(i);
2155 if (Element == DIBuilder::OpPlus) {
2156 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2157 Streamer.EmitULEB128(DV.getAddrElement(++i));
2158 } else if (Element == DIBuilder::OpDeref) {
2160 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2161 } else if (Element == DIBuilder::OpPiece) {
2163 // handled in emitDebugLocEntry.
2165 llvm_unreachable("unknown Opcode found in complex address");
2169 // else ... ignore constant fp. There is not any good way to
2170 // to represent them here in dwarf.
2174 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2175 Asm->OutStreamer.AddComment("Loc expr size");
2176 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2177 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2178 Asm->EmitLabelDifference(end, begin, 2);
2179 Asm->OutStreamer.EmitLabel(begin);
2181 APByteStreamer Streamer(*Asm);
2182 emitDebugLocEntry(Streamer, Entry);
2184 Asm->OutStreamer.EmitLabel(end);
2187 // Emit locations into the debug loc section.
2188 void DwarfDebug::emitDebugLoc() {
2189 // Start the dwarf loc section.
2190 Asm->OutStreamer.SwitchSection(
2191 Asm->getObjFileLowering().getDwarfLocSection());
2192 unsigned char Size = Asm->getDataLayout().getPointerSize();
2193 for (const auto &DebugLoc : DotDebugLocEntries) {
2194 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2195 const DwarfCompileUnit *CU = DebugLoc.CU;
2196 assert(!CU->getRanges().empty());
2197 for (const auto &Entry : DebugLoc.List) {
2198 // Set up the range. This range is relative to the entry point of the
2199 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2200 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2201 if (CU->getRanges().size() == 1) {
2202 // Grab the begin symbol from the first range as our base.
2203 const MCSymbol *Base = CU->getRanges()[0].getStart();
2204 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2205 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2207 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2208 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2211 emitDebugLocEntryLocation(Entry);
2213 Asm->OutStreamer.EmitIntValue(0, Size);
2214 Asm->OutStreamer.EmitIntValue(0, Size);
2218 void DwarfDebug::emitDebugLocDWO() {
2219 Asm->OutStreamer.SwitchSection(
2220 Asm->getObjFileLowering().getDwarfLocDWOSection());
2221 for (const auto &DebugLoc : DotDebugLocEntries) {
2222 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2223 for (const auto &Entry : DebugLoc.List) {
2224 // Just always use start_length for now - at least that's one address
2225 // rather than two. We could get fancier and try to, say, reuse an
2226 // address we know we've emitted elsewhere (the start of the function?
2227 // The start of the CU or CU subrange that encloses this range?)
2228 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2229 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2230 Asm->EmitULEB128(idx);
2231 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2233 emitDebugLocEntryLocation(Entry);
2235 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2240 const MCSymbol *Start, *End;
2243 // Emit a debug aranges section, containing a CU lookup for any
2244 // address we can tie back to a CU.
2245 void DwarfDebug::emitDebugARanges() {
2246 // Start the dwarf aranges section.
2247 Asm->OutStreamer.SwitchSection(
2248 Asm->getObjFileLowering().getDwarfARangesSection());
2250 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2254 // Build a list of sections used.
2255 std::vector<const MCSection *> Sections;
2256 for (const auto &it : SectionMap) {
2257 const MCSection *Section = it.first;
2258 Sections.push_back(Section);
2261 // Sort the sections into order.
2262 // This is only done to ensure consistent output order across different runs.
2263 std::sort(Sections.begin(), Sections.end(), SectionSort);
2265 // Build a set of address spans, sorted by CU.
2266 for (const MCSection *Section : Sections) {
2267 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2268 if (List.size() < 2)
2271 // Sort the symbols by offset within the section.
2272 std::sort(List.begin(), List.end(),
2273 [&](const SymbolCU &A, const SymbolCU &B) {
2274 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2275 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2277 // Symbols with no order assigned should be placed at the end.
2278 // (e.g. section end labels)
2286 // If we have no section (e.g. common), just write out
2287 // individual spans for each symbol.
2289 for (const SymbolCU &Cur : List) {
2291 Span.Start = Cur.Sym;
2294 Spans[Cur.CU].push_back(Span);
2297 // Build spans between each label.
2298 const MCSymbol *StartSym = List[0].Sym;
2299 for (size_t n = 1, e = List.size(); n < e; n++) {
2300 const SymbolCU &Prev = List[n - 1];
2301 const SymbolCU &Cur = List[n];
2303 // Try and build the longest span we can within the same CU.
2304 if (Cur.CU != Prev.CU) {
2306 Span.Start = StartSym;
2308 Spans[Prev.CU].push_back(Span);
2315 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2317 // Build a list of CUs used.
2318 std::vector<DwarfCompileUnit *> CUs;
2319 for (const auto &it : Spans) {
2320 DwarfCompileUnit *CU = it.first;
2324 // Sort the CU list (again, to ensure consistent output order).
2325 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2326 return A->getUniqueID() < B->getUniqueID();
2329 // Emit an arange table for each CU we used.
2330 for (DwarfCompileUnit *CU : CUs) {
2331 std::vector<ArangeSpan> &List = Spans[CU];
2333 // Emit size of content not including length itself.
2334 unsigned ContentSize =
2335 sizeof(int16_t) + // DWARF ARange version number
2336 sizeof(int32_t) + // Offset of CU in the .debug_info section
2337 sizeof(int8_t) + // Pointer Size (in bytes)
2338 sizeof(int8_t); // Segment Size (in bytes)
2340 unsigned TupleSize = PtrSize * 2;
2342 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2344 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2346 ContentSize += Padding;
2347 ContentSize += (List.size() + 1) * TupleSize;
2349 // For each compile unit, write the list of spans it covers.
2350 Asm->OutStreamer.AddComment("Length of ARange Set");
2351 Asm->EmitInt32(ContentSize);
2352 Asm->OutStreamer.AddComment("DWARF Arange version number");
2353 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2354 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2355 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2356 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2357 Asm->EmitInt8(PtrSize);
2358 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2361 Asm->OutStreamer.EmitFill(Padding, 0xff);
2363 for (const ArangeSpan &Span : List) {
2364 Asm->EmitLabelReference(Span.Start, PtrSize);
2366 // Calculate the size as being from the span start to it's end.
2368 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2370 // For symbols without an end marker (e.g. common), we
2371 // write a single arange entry containing just that one symbol.
2372 uint64_t Size = SymSize[Span.Start];
2376 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2380 Asm->OutStreamer.AddComment("ARange terminator");
2381 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2382 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2386 // Emit visible names into a debug ranges section.
2387 void DwarfDebug::emitDebugRanges() {
2388 // Start the dwarf ranges section.
2389 Asm->OutStreamer.SwitchSection(
2390 Asm->getObjFileLowering().getDwarfRangesSection());
2392 // Size for our labels.
2393 unsigned char Size = Asm->getDataLayout().getPointerSize();
2395 // Grab the specific ranges for the compile units in the module.
2396 for (const auto &I : CUMap) {
2397 DwarfCompileUnit *TheCU = I.second;
2399 // Iterate over the misc ranges for the compile units in the module.
2400 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2401 // Emit our symbol so we can find the beginning of the range.
2402 Asm->OutStreamer.EmitLabel(List.getSym());
2404 for (const RangeSpan &Range : List.getRanges()) {
2405 const MCSymbol *Begin = Range.getStart();
2406 const MCSymbol *End = Range.getEnd();
2407 assert(Begin && "Range without a begin symbol?");
2408 assert(End && "Range without an end symbol?");
2409 if (TheCU->getRanges().size() == 1) {
2410 // Grab the begin symbol from the first range as our base.
2411 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2412 Asm->EmitLabelDifference(Begin, Base, Size);
2413 Asm->EmitLabelDifference(End, Base, Size);
2415 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2416 Asm->OutStreamer.EmitSymbolValue(End, Size);
2420 // And terminate the list with two 0 values.
2421 Asm->OutStreamer.EmitIntValue(0, Size);
2422 Asm->OutStreamer.EmitIntValue(0, Size);
2425 // Now emit a range for the CU itself.
2426 if (TheCU->getRanges().size() > 1) {
2427 Asm->OutStreamer.EmitLabel(
2428 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2429 for (const RangeSpan &Range : TheCU->getRanges()) {
2430 const MCSymbol *Begin = Range.getStart();
2431 const MCSymbol *End = Range.getEnd();
2432 assert(Begin && "Range without a begin symbol?");
2433 assert(End && "Range without an end symbol?");
2434 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2435 Asm->OutStreamer.EmitSymbolValue(End, Size);
2437 // And terminate the list with two 0 values.
2438 Asm->OutStreamer.EmitIntValue(0, Size);
2439 Asm->OutStreamer.EmitIntValue(0, Size);
2444 // DWARF5 Experimental Separate Dwarf emitters.
2446 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2447 std::unique_ptr<DwarfUnit> NewU) {
2448 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2449 U.getCUNode().getSplitDebugFilename());
2451 if (!CompilationDir.empty())
2452 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2454 addGnuPubAttributes(*NewU, Die);
2456 SkeletonHolder.addUnit(std::move(NewU));
2459 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2460 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2461 // DW_AT_addr_base, DW_AT_ranges_base.
2462 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2464 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2465 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2466 DwarfCompileUnit &NewCU = *OwnedUnit;
2467 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2468 DwarfInfoSectionSym);
2470 NewCU.initStmtList(DwarfLineSectionSym);
2472 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2477 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2478 // compile units that would normally be in debug_info.
2479 void DwarfDebug::emitDebugInfoDWO() {
2480 assert(useSplitDwarf() && "No split dwarf debug info?");
2481 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2482 // emit relocations into the dwo file.
2483 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2486 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2487 // abbreviations for the .debug_info.dwo section.
2488 void DwarfDebug::emitDebugAbbrevDWO() {
2489 assert(useSplitDwarf() && "No split dwarf?");
2490 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2493 void DwarfDebug::emitDebugLineDWO() {
2494 assert(useSplitDwarf() && "No split dwarf?");
2495 Asm->OutStreamer.SwitchSection(
2496 Asm->getObjFileLowering().getDwarfLineDWOSection());
2497 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2500 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2501 // string section and is identical in format to traditional .debug_str
2503 void DwarfDebug::emitDebugStrDWO() {
2504 assert(useSplitDwarf() && "No split dwarf?");
2505 const MCSection *OffSec =
2506 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2507 const MCSymbol *StrSym = DwarfStrSectionSym;
2508 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2512 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2513 if (!useSplitDwarf())
2516 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2517 return &SplitTypeUnitFileTable;
2520 static uint64_t makeTypeSignature(StringRef Identifier) {
2522 Hash.update(Identifier);
2523 // ... take the least significant 8 bytes and return those. Our MD5
2524 // implementation always returns its results in little endian, swap bytes
2526 MD5::MD5Result Result;
2528 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2531 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2532 StringRef Identifier, DIE &RefDie,
2533 DICompositeType CTy) {
2534 // Fast path if we're building some type units and one has already used the
2535 // address pool we know we're going to throw away all this work anyway, so
2536 // don't bother building dependent types.
2537 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2540 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2542 CU.addDIETypeSignature(RefDie, *TU);
2546 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2547 AddrPool.resetUsedFlag();
2549 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2550 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2551 this, &InfoHolder, getDwoLineTable(CU));
2552 DwarfTypeUnit &NewTU = *OwnedUnit;
2553 DIE &UnitDie = NewTU.getUnitDie();
2555 TypeUnitsUnderConstruction.push_back(
2556 std::make_pair(std::move(OwnedUnit), CTy));
2558 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2561 uint64_t Signature = makeTypeSignature(Identifier);
2562 NewTU.setTypeSignature(Signature);
2564 if (useSplitDwarf())
2565 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2566 DwarfTypesDWOSectionSym);
2568 CU.applyStmtList(UnitDie);
2570 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2573 NewTU.setType(NewTU.createTypeDIE(CTy));
2576 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2577 TypeUnitsUnderConstruction.clear();
2579 // Types referencing entries in the address table cannot be placed in type
2581 if (AddrPool.hasBeenUsed()) {
2583 // Remove all the types built while building this type.
2584 // This is pessimistic as some of these types might not be dependent on
2585 // the type that used an address.
2586 for (const auto &TU : TypeUnitsToAdd)
2587 DwarfTypeUnits.erase(TU.second);
2589 // Construct this type in the CU directly.
2590 // This is inefficient because all the dependent types will be rebuilt
2591 // from scratch, including building them in type units, discovering that
2592 // they depend on addresses, throwing them out and rebuilding them.
2593 CU.constructTypeDIE(RefDie, CTy);
2597 // If the type wasn't dependent on fission addresses, finish adding the type
2598 // and all its dependent types.
2599 for (auto &TU : TypeUnitsToAdd)
2600 InfoHolder.addUnit(std::move(TU.first));
2602 CU.addDIETypeSignature(RefDie, NewTU);
2605 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2606 const MCSymbol *Begin, const MCSymbol *End) {
2607 assert(Begin && "Begin label should not be null!");
2608 assert(End && "End label should not be null!");
2609 assert(Begin->isDefined() && "Invalid starting label");
2610 assert(End->isDefined() && "Invalid end label");
2612 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2613 if (DwarfVersion < 4)
2614 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2616 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2619 // Accelerator table mutators - add each name along with its companion
2620 // DIE to the proper table while ensuring that the name that we're going
2621 // to reference is in the string table. We do this since the names we
2622 // add may not only be identical to the names in the DIE.
2623 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2624 if (!useDwarfAccelTables())
2626 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2630 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2631 if (!useDwarfAccelTables())
2633 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2637 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2638 if (!useDwarfAccelTables())
2640 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2644 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2645 if (!useDwarfAccelTables())
2647 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),