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 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
175 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
176 dwarf::DW_FORM_data4)),
177 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelTypes(TypeAtoms) {
183 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
184 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
185 DwarfLineSectionSym = nullptr;
186 DwarfAddrSectionSym = nullptr;
187 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
188 FunctionBeginSym = FunctionEndSym = nullptr;
192 // Turn on accelerator tables for Darwin by default, pubnames by
193 // default for non-Darwin, and handle split dwarf.
194 if (DwarfAccelTables == Default)
195 HasDwarfAccelTables = IsDarwin;
197 HasDwarfAccelTables = DwarfAccelTables == Enable;
199 if (SplitDwarf == Default)
200 HasSplitDwarf = false;
202 HasSplitDwarf = SplitDwarf == Enable;
204 if (DwarfPubSections == Default)
205 HasDwarfPubSections = !IsDarwin;
207 HasDwarfPubSections = DwarfPubSections == Enable;
209 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
210 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
211 : MMI->getModule()->getDwarfVersion();
213 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
216 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
221 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
222 DwarfDebug::~DwarfDebug() { }
224 // Switch to the specified MCSection and emit an assembler
225 // temporary label to it if SymbolStem is specified.
226 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
227 const char *SymbolStem = nullptr) {
228 Asm->OutStreamer.SwitchSection(Section);
232 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
233 Asm->OutStreamer.EmitLabel(TmpSym);
237 static bool isObjCClass(StringRef Name) {
238 return Name.startswith("+") || Name.startswith("-");
241 static bool hasObjCCategory(StringRef Name) {
242 if (!isObjCClass(Name))
245 return Name.find(") ") != StringRef::npos;
248 static void getObjCClassCategory(StringRef In, StringRef &Class,
249 StringRef &Category) {
250 if (!hasObjCCategory(In)) {
251 Class = In.slice(In.find('[') + 1, In.find(' '));
256 Class = In.slice(In.find('[') + 1, In.find('('));
257 Category = In.slice(In.find('[') + 1, In.find(' '));
261 static StringRef getObjCMethodName(StringRef In) {
262 return In.slice(In.find(' ') + 1, In.find(']'));
265 // Helper for sorting sections into a stable output order.
266 static bool SectionSort(const MCSection *A, const MCSection *B) {
267 std::string LA = (A ? A->getLabelBeginName() : "");
268 std::string LB = (B ? B->getLabelBeginName() : "");
272 // Add the various names to the Dwarf accelerator table names.
273 // TODO: Determine whether or not we should add names for programs
274 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
275 // is only slightly different than the lookup of non-standard ObjC names.
276 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
277 if (!SP.isDefinition())
279 addAccelName(SP.getName(), Die);
281 // If the linkage name is different than the name, go ahead and output
282 // that as well into the name table.
283 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
284 addAccelName(SP.getLinkageName(), Die);
286 // If this is an Objective-C selector name add it to the ObjC accelerator
288 if (isObjCClass(SP.getName())) {
289 StringRef Class, Category;
290 getObjCClassCategory(SP.getName(), Class, Category);
291 addAccelObjC(Class, Die);
293 addAccelObjC(Category, Die);
294 // Also add the base method name to the name table.
295 addAccelName(getObjCMethodName(SP.getName()), Die);
299 /// isSubprogramContext - Return true if Context is either a subprogram
300 /// or another context nested inside a subprogram.
301 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
304 DIDescriptor D(Context);
305 if (D.isSubprogram())
308 return isSubprogramContext(resolve(DIType(Context).getContext()));
312 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
313 // and DW_AT_high_pc attributes. If there are global variables in this
314 // scope then create and insert DIEs for these variables.
315 DIE &DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
317 DIE *SPDie = SPCU.getOrCreateSubprogramDIE(SP);
319 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
321 // Only include DW_AT_frame_base in full debug info
322 if (SPCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly) {
323 const TargetRegisterInfo *RI =
324 Asm->TM.getSubtargetImpl()->getRegisterInfo();
325 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
326 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
329 // Add name to the name table, we do this here because we're guaranteed
330 // to have concrete versions of our DW_TAG_subprogram nodes.
331 addSubprogramNames(SP, *SPDie);
336 /// Check whether we should create a DIE for the given Scope, return true
337 /// if we don't create a DIE (the corresponding DIE is null).
338 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
339 if (Scope->isAbstractScope())
342 // We don't create a DIE if there is no Range.
343 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
347 if (Ranges.size() > 1)
350 // We don't create a DIE if we have a single Range and the end label
352 return !getLabelAfterInsn(Ranges.front().second);
355 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
356 dwarf::Attribute A, const MCSymbol *L,
357 const MCSymbol *Sec) {
358 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
359 U.addSectionLabel(D, A, L);
361 U.addSectionDelta(D, A, L, Sec);
364 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
365 const SmallVectorImpl<InsnRange> &Range) {
366 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
367 // emitting it appropriately.
368 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
370 // Under fission, ranges are specified by constant offsets relative to the
371 // CU's DW_AT_GNU_ranges_base.
373 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
374 DwarfDebugRangeSectionSym);
376 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
377 DwarfDebugRangeSectionSym);
379 RangeSpanList List(RangeSym);
380 for (const InsnRange &R : Range) {
381 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
382 List.addRange(std::move(Span));
385 // Add the range list to the set of ranges to be emitted.
386 TheCU.addRangeList(std::move(List));
389 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
390 const SmallVectorImpl<InsnRange> &Ranges) {
391 assert(!Ranges.empty());
392 if (Ranges.size() == 1)
393 attachLowHighPC(TheCU, Die, getLabelBeforeInsn(Ranges.front().first),
394 getLabelAfterInsn(Ranges.front().second));
396 addScopeRangeList(TheCU, Die, Ranges);
399 // Construct new DW_TAG_lexical_block for this scope and attach
400 // DW_AT_low_pc/DW_AT_high_pc labels.
402 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
403 LexicalScope *Scope) {
404 if (isLexicalScopeDIENull(Scope))
407 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
408 if (Scope->isAbstractScope())
411 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
416 // This scope represents inlined body of a function. Construct DIE to
417 // represent this concrete inlined copy of the function.
419 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
420 LexicalScope *Scope) {
421 assert(Scope->getScopeNode());
422 DIScope DS(Scope->getScopeNode());
423 DISubprogram InlinedSP = getDISubprogram(DS);
424 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
425 // was inlined from another compile unit.
426 DIE *OriginDIE = AbstractSPDies[InlinedSP];
427 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
429 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
430 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
432 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
434 InlinedSubprogramDIEs.insert(OriginDIE);
436 // Add the call site information to the DIE.
437 DILocation DL(Scope->getInlinedAt());
438 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
439 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
440 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
442 // Add name to the name table, we do this here because we're guaranteed
443 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
444 addSubprogramNames(InlinedSP, *ScopeDIE);
449 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
451 const LexicalScope &Scope,
452 DIE *&ObjectPointer) {
453 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
454 if (DV.isObjectPointer())
455 ObjectPointer = Var.get();
459 DIE *DwarfDebug::createScopeChildrenDIE(
460 DwarfCompileUnit &TheCU, LexicalScope *Scope,
461 SmallVectorImpl<std::unique_ptr<DIE>> &Children,
462 unsigned *ChildScopeCount) {
463 DIE *ObjectPointer = nullptr;
465 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
466 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
468 unsigned ChildCountWithoutScopes = Children.size();
470 for (LexicalScope *LS : Scope->getChildren())
471 constructScopeDIE(TheCU, LS, Children);
474 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
476 return ObjectPointer;
479 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
480 LexicalScope *Scope, DIE &ScopeDIE) {
481 // We create children when the scope DIE is not null.
482 SmallVector<std::unique_ptr<DIE>, 8> Children;
483 DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
486 for (auto &I : Children)
487 ScopeDIE.addChild(std::move(I));
489 return ObjectPointer;
492 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
493 LexicalScope *Scope) {
494 assert(Scope && Scope->getScopeNode());
495 assert(Scope->isAbstractScope());
496 assert(!Scope->getInlinedAt());
498 DISubprogram SP(Scope->getScopeNode());
500 ProcessedSPNodes.insert(SP);
502 DIE *&AbsDef = AbstractSPDies[SP];
506 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
507 // was inlined from another compile unit.
508 DwarfCompileUnit &SPCU = *SPMap[SP];
511 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
512 // the important distinction that the DIDescriptor is not associated with the
513 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
514 // any). It could be refactored to some common utility function.
515 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
516 ContextDIE = &SPCU.getUnitDie();
517 SPCU.getOrCreateSubprogramDIE(SPDecl);
519 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
521 // Passing null as the associated DIDescriptor because the abstract definition
522 // shouldn't be found by lookup.
523 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
525 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
527 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
528 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
529 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
532 DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
533 LexicalScope *Scope) {
534 assert(Scope && Scope->getScopeNode());
535 assert(!Scope->getInlinedAt());
536 assert(!Scope->isAbstractScope());
537 DISubprogram Sub(Scope->getScopeNode());
539 assert(Sub.isSubprogram());
541 ProcessedSPNodes.insert(Sub);
543 DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
545 // Collect arguments for current function.
546 assert(LScopes.isCurrentFunctionScope(Scope));
547 DIE *ObjectPointer = nullptr;
548 for (DbgVariable *ArgDV : CurrentFnArguments)
551 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
553 // If this is a variadic function, add an unspecified parameter.
554 DITypeArray FnArgs = Sub.getType().getTypeArray();
555 // If we have a single element of null, it is a function that returns void.
556 // If we have more than one elements and the last one is null, it is a
557 // variadic function.
558 if (FnArgs.getNumElements() > 1 &&
559 !FnArgs.getElement(FnArgs.getNumElements() - 1))
560 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
562 // Collect lexical scope children first.
563 // ObjectPointer might be a local (non-argument) local variable if it's a
564 // block's synthetic this pointer.
565 if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
566 assert(!ObjectPointer && "multiple object pointers can't be described");
567 ObjectPointer = BlockObjPtr;
571 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
576 // Construct a DIE for this scope.
577 void DwarfDebug::constructScopeDIE(
578 DwarfCompileUnit &TheCU, LexicalScope *Scope,
579 SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
580 if (!Scope || !Scope->getScopeNode())
583 DIScope DS(Scope->getScopeNode());
585 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
586 "Only handle inlined subprograms here, use "
587 "constructSubprogramScopeDIE for non-inlined "
590 SmallVector<std::unique_ptr<DIE>, 8> Children;
592 // We try to create the scope DIE first, then the children DIEs. This will
593 // avoid creating un-used children then removing them later when we find out
594 // the scope DIE is null.
595 std::unique_ptr<DIE> ScopeDIE;
596 if (Scope->getParent() && DS.isSubprogram()) {
597 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
600 // We create children when the scope DIE is not null.
601 createScopeChildrenDIE(TheCU, Scope, Children);
603 // Early exit when we know the scope DIE is going to be null.
604 if (isLexicalScopeDIENull(Scope))
607 unsigned ChildScopeCount;
609 // We create children here when we know the scope DIE is not going to be
610 // null and the children will be added to the scope DIE.
611 createScopeChildrenDIE(TheCU, Scope, Children, &ChildScopeCount);
613 // There is no need to emit empty lexical block DIE.
614 std::pair<ImportedEntityMap::const_iterator,
615 ImportedEntityMap::const_iterator> Range =
616 std::equal_range(ScopesWithImportedEntities.begin(),
617 ScopesWithImportedEntities.end(),
618 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
620 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
623 constructImportedEntityDIE(TheCU, DIImportedEntity(i->second)));
624 // If there are only other scopes as children, put them directly in the
625 // parent instead, as this scope would serve no purpose.
626 if (Children.size() == ChildScopeCount) {
627 FinalChildren.insert(FinalChildren.end(),
628 std::make_move_iterator(Children.begin()),
629 std::make_move_iterator(Children.end()));
632 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
633 assert(ScopeDIE && "Scope DIE should not be null.");
637 for (auto &I : Children)
638 ScopeDIE->addChild(std::move(I));
640 FinalChildren.push_back(std::move(ScopeDIE));
643 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
644 if (!GenerateGnuPubSections)
647 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
650 // Create new DwarfCompileUnit for the given metadata node with tag
651 // DW_TAG_compile_unit.
652 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
653 StringRef FN = DIUnit.getFilename();
654 CompilationDir = DIUnit.getDirectory();
656 auto OwnedUnit = make_unique<DwarfCompileUnit>(
657 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
658 DwarfCompileUnit &NewCU = *OwnedUnit;
659 DIE &Die = NewCU.getUnitDie();
660 InfoHolder.addUnit(std::move(OwnedUnit));
662 // LTO with assembly output shares a single line table amongst multiple CUs.
663 // To avoid the compilation directory being ambiguous, let the line table
664 // explicitly describe the directory of all files, never relying on the
665 // compilation directory.
666 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
667 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
668 NewCU.getUniqueID(), CompilationDir);
670 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
671 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
672 DIUnit.getLanguage());
673 NewCU.addString(Die, dwarf::DW_AT_name, FN);
675 if (!useSplitDwarf()) {
676 NewCU.initStmtList(DwarfLineSectionSym);
678 // If we're using split dwarf the compilation dir is going to be in the
679 // skeleton CU and so we don't need to duplicate it here.
680 if (!CompilationDir.empty())
681 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
683 addGnuPubAttributes(NewCU, Die);
686 if (DIUnit.isOptimized())
687 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
689 StringRef Flags = DIUnit.getFlags();
691 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
693 if (unsigned RVer = DIUnit.getRunTimeVersion())
694 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
695 dwarf::DW_FORM_data1, RVer);
700 if (useSplitDwarf()) {
701 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
702 DwarfInfoDWOSectionSym);
703 NewCU.setSkeleton(constructSkeletonCU(NewCU));
705 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
706 DwarfInfoSectionSym);
708 CUMap.insert(std::make_pair(DIUnit, &NewCU));
709 CUDieMap.insert(std::make_pair(&Die, &NewCU));
713 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
715 DIImportedEntity Module(N);
716 assert(Module.Verify());
717 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
718 D->addChild(constructImportedEntityDIE(TheCU, Module));
722 DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
723 const DIImportedEntity &Module) {
724 assert(Module.Verify() &&
725 "Use one of the MDNode * overloads to handle invalid metadata");
726 std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
727 TheCU.insertDIE(Module, IMDie.get());
729 DIDescriptor Entity = resolve(Module.getEntity());
730 if (Entity.isNameSpace())
731 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
732 else if (Entity.isSubprogram())
733 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
734 else if (Entity.isType())
735 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
737 EntityDie = TheCU.getDIE(Entity);
739 TheCU.addSourceLine(*IMDie, Module.getLineNumber(),
740 Module.getContext().getFilename(),
741 Module.getContext().getDirectory());
742 TheCU.addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
743 StringRef Name = Module.getName();
745 TheCU.addString(*IMDie, dwarf::DW_AT_name, Name);
750 // Emit all Dwarf sections that should come prior to the content. Create
751 // global DIEs and emit initial debug info sections. This is invoked by
752 // the target AsmPrinter.
753 void DwarfDebug::beginModule() {
754 if (DisableDebugInfoPrinting)
757 const Module *M = MMI->getModule();
759 FunctionDIs = makeSubprogramMap(*M);
761 // If module has named metadata anchors then use them, otherwise scan the
762 // module using debug info finder to collect debug info.
763 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
766 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
768 // Emit initial sections so we can reference labels later.
771 SingleCU = CU_Nodes->getNumOperands() == 1;
773 for (MDNode *N : CU_Nodes->operands()) {
774 DICompileUnit CUNode(N);
775 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
776 DIArray ImportedEntities = CUNode.getImportedEntities();
777 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
778 ScopesWithImportedEntities.push_back(std::make_pair(
779 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
780 ImportedEntities.getElement(i)));
781 std::sort(ScopesWithImportedEntities.begin(),
782 ScopesWithImportedEntities.end(), less_first());
783 DIArray GVs = CUNode.getGlobalVariables();
784 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
785 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
786 DIArray SPs = CUNode.getSubprograms();
787 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
788 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
789 DIArray EnumTypes = CUNode.getEnumTypes();
790 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
791 DIType Ty(EnumTypes.getElement(i));
792 // The enum types array by design contains pointers to
793 // MDNodes rather than DIRefs. Unique them here.
794 DIType UniqueTy(resolve(Ty.getRef()));
795 CU.getOrCreateTypeDIE(UniqueTy);
797 DIArray RetainedTypes = CUNode.getRetainedTypes();
798 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
799 DIType Ty(RetainedTypes.getElement(i));
800 // The retained types array by design contains pointers to
801 // MDNodes rather than DIRefs. Unique them here.
802 DIType UniqueTy(resolve(Ty.getRef()));
803 CU.getOrCreateTypeDIE(UniqueTy);
805 // Emit imported_modules last so that the relevant context is already
807 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
808 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
811 // Tell MMI that we have debug info.
812 MMI->setDebugInfoAvailability(true);
814 // Prime section data.
815 SectionMap[Asm->getObjFileLowering().getTextSection()];
818 void DwarfDebug::finishVariableDefinitions() {
819 for (const auto &Var : ConcreteVariables) {
820 DIE *VariableDie = Var->getDIE();
822 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
823 // in the ConcreteVariables list, rather than looking it up again here.
824 // DIE::getUnit isn't simple - it walks parent pointers, etc.
825 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
827 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
828 if (AbsVar && AbsVar->getDIE()) {
829 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
832 Unit->applyVariableAttributes(*Var, *VariableDie);
836 void DwarfDebug::finishSubprogramDefinitions() {
837 const Module *M = MMI->getModule();
839 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
840 for (MDNode *N : CU_Nodes->operands()) {
841 DICompileUnit TheCU(N);
842 // Construct subprogram DIE and add variables DIEs.
843 DwarfCompileUnit *SPCU =
844 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
845 DIArray Subprograms = TheCU.getSubprograms();
846 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
847 DISubprogram SP(Subprograms.getElement(i));
848 // Perhaps the subprogram is in another CU (such as due to comdat
849 // folding, etc), in which case ignore it here.
850 if (SPMap[SP] != SPCU)
852 DIE *D = SPCU->getDIE(SP);
853 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
855 // If this subprogram has an abstract definition, reference that
856 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
858 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
859 // Lazily construct the subprogram if we didn't see either concrete or
860 // inlined versions during codegen. (except in -gmlt ^ where we want
861 // to omit these entirely)
862 D = SPCU->getOrCreateSubprogramDIE(SP);
864 // And attach the attributes
865 SPCU->applySubprogramAttributesToDefinition(SP, *D);
872 // Collect info for variables that were optimized out.
873 void DwarfDebug::collectDeadVariables() {
874 const Module *M = MMI->getModule();
876 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
877 for (MDNode *N : CU_Nodes->operands()) {
878 DICompileUnit TheCU(N);
879 // Construct subprogram DIE and add variables DIEs.
880 DwarfCompileUnit *SPCU =
881 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
882 assert(SPCU && "Unable to find Compile Unit!");
883 DIArray Subprograms = TheCU.getSubprograms();
884 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
885 DISubprogram SP(Subprograms.getElement(i));
886 if (ProcessedSPNodes.count(SP) != 0)
888 assert(SP.isSubprogram() &&
889 "CU's subprogram list contains a non-subprogram");
890 assert(SP.isDefinition() &&
891 "CU's subprogram list contains a subprogram declaration");
892 DIArray Variables = SP.getVariables();
893 if (Variables.getNumElements() == 0)
896 DIE *SPDIE = AbstractSPDies.lookup(SP);
898 SPDIE = SPCU->getDIE(SP);
900 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
901 DIVariable DV(Variables.getElement(vi));
902 assert(DV.isVariable());
903 DbgVariable NewVar(DV, this);
904 auto VariableDie = SPCU->constructVariableDIE(NewVar);
905 SPCU->applyVariableAttributes(NewVar, *VariableDie);
906 SPDIE->addChild(std::move(VariableDie));
913 void DwarfDebug::finalizeModuleInfo() {
914 finishSubprogramDefinitions();
916 finishVariableDefinitions();
918 // Collect info for variables that were optimized out.
919 collectDeadVariables();
921 // Handle anything that needs to be done on a per-unit basis after
922 // all other generation.
923 for (const auto &TheU : getUnits()) {
924 // Emit DW_AT_containing_type attribute to connect types with their
925 // vtable holding type.
926 TheU->constructContainingTypeDIEs();
928 // Add CU specific attributes if we need to add any.
929 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
930 // If we're splitting the dwarf out now that we've got the entire
931 // CU then add the dwo id to it.
932 DwarfCompileUnit *SkCU =
933 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
934 if (useSplitDwarf()) {
935 // Emit a unique identifier for this CU.
936 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
937 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
938 dwarf::DW_FORM_data8, ID);
939 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
940 dwarf::DW_FORM_data8, ID);
942 // We don't keep track of which addresses are used in which CU so this
943 // is a bit pessimistic under LTO.
944 if (!AddrPool.isEmpty())
945 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
946 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
947 DwarfAddrSectionSym);
948 if (!TheU->getRangeLists().empty())
949 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
950 dwarf::DW_AT_GNU_ranges_base,
951 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
954 // If we have code split among multiple sections or non-contiguous
955 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
956 // remain in the .o file, otherwise add a DW_AT_low_pc.
957 // FIXME: We should use ranges allow reordering of code ala
958 // .subsections_via_symbols in mach-o. This would mean turning on
959 // ranges for all subprogram DIEs for mach-o.
960 DwarfCompileUnit &U =
961 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
962 unsigned NumRanges = TheU->getRanges().size();
965 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
966 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
967 DwarfDebugRangeSectionSym);
969 // A DW_AT_low_pc attribute may also be specified in combination with
970 // DW_AT_ranges to specify the default base address for use in
971 // location lists (see Section 2.6.2) and range lists (see Section
973 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
976 RangeSpan &Range = TheU->getRanges().back();
977 attachLowHighPC(U, U.getUnitDie(), Range.getStart(), Range.getEnd());
983 // Compute DIE offsets and sizes.
984 InfoHolder.computeSizeAndOffsets();
986 SkeletonHolder.computeSizeAndOffsets();
989 void DwarfDebug::endSections() {
990 // Filter labels by section.
991 for (const SymbolCU &SCU : ArangeLabels) {
992 if (SCU.Sym->isInSection()) {
993 // Make a note of this symbol and it's section.
994 const MCSection *Section = &SCU.Sym->getSection();
995 if (!Section->getKind().isMetadata())
996 SectionMap[Section].push_back(SCU);
998 // Some symbols (e.g. common/bss on mach-o) can have no section but still
999 // appear in the output. This sucks as we rely on sections to build
1000 // arange spans. We can do it without, but it's icky.
1001 SectionMap[nullptr].push_back(SCU);
1005 // Build a list of sections used.
1006 std::vector<const MCSection *> Sections;
1007 for (const auto &it : SectionMap) {
1008 const MCSection *Section = it.first;
1009 Sections.push_back(Section);
1012 // Sort the sections into order.
1013 // This is only done to ensure consistent output order across different runs.
1014 std::sort(Sections.begin(), Sections.end(), SectionSort);
1016 // Add terminating symbols for each section.
1017 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1018 const MCSection *Section = Sections[ID];
1019 MCSymbol *Sym = nullptr;
1022 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1023 // if we know the section name up-front. For user-created sections, the
1024 // resulting label may not be valid to use as a label. (section names can
1025 // use a greater set of characters on some systems)
1026 Sym = Asm->GetTempSymbol("debug_end", ID);
1027 Asm->OutStreamer.SwitchSection(Section);
1028 Asm->OutStreamer.EmitLabel(Sym);
1031 // Insert a final terminator.
1032 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1036 // Emit all Dwarf sections that should come after the content.
1037 void DwarfDebug::endModule() {
1038 assert(CurFn == nullptr);
1039 assert(CurMI == nullptr);
1044 // End any existing sections.
1045 // TODO: Does this need to happen?
1048 // Finalize the debug info for the module.
1049 finalizeModuleInfo();
1053 // Emit all the DIEs into a debug info section.
1056 // Corresponding abbreviations into a abbrev section.
1057 emitAbbreviations();
1059 // Emit info into a debug aranges section.
1060 if (GenerateARangeSection)
1063 // Emit info into a debug ranges section.
1066 if (useSplitDwarf()) {
1069 emitDebugAbbrevDWO();
1072 // Emit DWO addresses.
1073 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1075 // Emit info into a debug loc section.
1078 // Emit info into the dwarf accelerator table sections.
1079 if (useDwarfAccelTables()) {
1082 emitAccelNamespaces();
1086 // Emit the pubnames and pubtypes sections if requested.
1087 if (HasDwarfPubSections) {
1088 emitDebugPubNames(GenerateGnuPubSections);
1089 emitDebugPubTypes(GenerateGnuPubSections);
1094 AbstractVariables.clear();
1096 // Reset these for the next Module if we have one.
1100 // Find abstract variable, if any, associated with Var.
1101 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
1102 DIVariable &Cleansed) {
1103 LLVMContext &Ctx = DV->getContext();
1104 // More then one inlined variable corresponds to one abstract variable.
1105 // FIXME: This duplication of variables when inlining should probably be
1106 // removed. It's done to allow each DIVariable to describe its location
1107 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
1108 // make it accurate then remove this duplication/cleansing stuff.
1109 Cleansed = cleanseInlinedVariable(DV, Ctx);
1110 auto I = AbstractVariables.find(Cleansed);
1111 if (I != AbstractVariables.end())
1112 return I->second.get();
1116 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
1117 DIVariable Cleansed;
1118 return getExistingAbstractVariable(DV, Cleansed);
1121 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
1122 LexicalScope *Scope) {
1123 auto AbsDbgVariable = make_unique<DbgVariable>(Var, this);
1124 addScopeVariable(Scope, AbsDbgVariable.get());
1125 AbstractVariables[Var] = std::move(AbsDbgVariable);
1128 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
1129 const MDNode *ScopeNode) {
1130 DIVariable Cleansed = DV;
1131 if (getExistingAbstractVariable(DV, Cleansed))
1134 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
1138 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
1139 const MDNode *ScopeNode) {
1140 DIVariable Cleansed = DV;
1141 if (getExistingAbstractVariable(DV, Cleansed))
1144 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
1145 createAbstractVariable(Cleansed, Scope);
1148 // If Var is a current function argument then add it to CurrentFnArguments list.
1149 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1150 if (!LScopes.isCurrentFunctionScope(Scope))
1152 DIVariable DV = Var->getVariable();
1153 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1155 unsigned ArgNo = DV.getArgNumber();
1159 size_t Size = CurrentFnArguments.size();
1161 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1162 // llvm::Function argument size is not good indicator of how many
1163 // arguments does the function have at source level.
1165 CurrentFnArguments.resize(ArgNo * 2);
1166 assert(!CurrentFnArguments[ArgNo - 1]);
1167 CurrentFnArguments[ArgNo - 1] = Var;
1171 // Collect variable information from side table maintained by MMI.
1172 void DwarfDebug::collectVariableInfoFromMMITable(
1173 SmallPtrSetImpl<const MDNode *> &Processed) {
1174 for (const auto &VI : MMI->getVariableDbgInfo()) {
1177 Processed.insert(VI.Var);
1178 DIVariable DV(VI.Var);
1179 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1181 // If variable scope is not found then skip this variable.
1185 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1186 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, this));
1187 DbgVariable *RegVar = ConcreteVariables.back().get();
1188 RegVar->setFrameIndex(VI.Slot);
1189 addScopeVariable(Scope, RegVar);
1193 // Get .debug_loc entry for the instruction range starting at MI.
1194 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1195 const MDNode *Var = MI->getDebugVariable();
1197 assert(MI->getNumOperands() == 3);
1198 if (MI->getOperand(0).isReg()) {
1199 MachineLocation MLoc;
1200 // If the second operand is an immediate, this is a
1201 // register-indirect address.
1202 if (!MI->getOperand(1).isImm())
1203 MLoc.set(MI->getOperand(0).getReg());
1205 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1206 return DebugLocEntry::Value(Var, MLoc);
1208 if (MI->getOperand(0).isImm())
1209 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1210 if (MI->getOperand(0).isFPImm())
1211 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1212 if (MI->getOperand(0).isCImm())
1213 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1215 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1218 /// Determine whether two variable pieces overlap.
1219 static bool piecesOverlap(DIVariable P1, DIVariable P2) {
1220 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1222 unsigned l1 = P1.getPieceOffset();
1223 unsigned l2 = P2.getPieceOffset();
1224 unsigned r1 = l1 + P1.getPieceSize();
1225 unsigned r2 = l2 + P2.getPieceSize();
1226 // True where [l1,r1[ and [r1,r2[ overlap.
1227 return (l1 < r2) && (l2 < r1);
1230 /// Build the location list for all DBG_VALUEs in the function that
1231 /// describe the same variable. If the ranges of several independent
1232 /// pieces of the same variable overlap partially, split them up and
1233 /// combine the ranges. The resulting DebugLocEntries are will have
1234 /// strict monotonically increasing begin addresses and will never
1239 // Ranges History [var, loc, piece ofs size]
1240 // 0 | [x, (reg0, piece 0, 32)]
1241 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1243 // 3 | [clobber reg0]
1244 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1248 // [0-1] [x, (reg0, piece 0, 32)]
1249 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1250 // [3-4] [x, (reg1, piece 32, 32)]
1251 // [4- ] [x, (mem, piece 0, 64)]
1253 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1254 const DbgValueHistoryMap::InstrRanges &Ranges) {
1255 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1257 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1258 const MachineInstr *Begin = I->first;
1259 const MachineInstr *End = I->second;
1260 assert(Begin->isDebugValue() && "Invalid History entry");
1262 // Check if a variable is inaccessible in this range.
1263 if (Begin->getNumOperands() > 1 &&
1264 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1269 // If this piece overlaps with any open ranges, truncate them.
1270 DIVariable DIVar = Begin->getDebugVariable();
1271 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1272 [&](DebugLocEntry::Value R) {
1273 return piecesOverlap(DIVar, R.getVariable());
1275 OpenRanges.erase(Last, OpenRanges.end());
1277 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1278 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1280 const MCSymbol *EndLabel;
1282 EndLabel = getLabelAfterInsn(End);
1283 else if (std::next(I) == Ranges.end())
1284 EndLabel = FunctionEndSym;
1286 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1287 assert(EndLabel && "Forgot label after instruction ending a range!");
1289 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1291 auto Value = getDebugLocValue(Begin);
1292 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1293 bool couldMerge = false;
1295 // If this is a piece, it may belong to the current DebugLocEntry.
1296 if (DIVar.isVariablePiece()) {
1297 // Add this value to the list of open ranges.
1298 OpenRanges.push_back(Value);
1300 // Attempt to add the piece to the last entry.
1301 if (!DebugLoc.empty())
1302 if (DebugLoc.back().MergeValues(Loc))
1307 // Need to add a new DebugLocEntry. Add all values from still
1308 // valid non-overlapping pieces.
1309 if (OpenRanges.size())
1310 Loc.addValues(OpenRanges);
1312 DebugLoc.push_back(std::move(Loc));
1315 // Attempt to coalesce the ranges of two otherwise identical
1317 auto CurEntry = DebugLoc.rbegin();
1318 auto PrevEntry = std::next(CurEntry);
1319 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1320 DebugLoc.pop_back();
1322 DEBUG(dbgs() << "Values:\n";
1323 for (auto Value : CurEntry->getValues())
1324 Value.getVariable()->dump();
1325 dbgs() << "-----\n");
1330 // Find variables for each lexical scope.
1332 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1333 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1334 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1336 // Grab the variable info that was squirreled away in the MMI side-table.
1337 collectVariableInfoFromMMITable(Processed);
1339 for (const auto &I : DbgValues) {
1340 DIVariable DV(I.first);
1341 if (Processed.count(DV))
1344 // Instruction ranges, specifying where DV is accessible.
1345 const auto &Ranges = I.second;
1349 LexicalScope *Scope = nullptr;
1350 if (MDNode *IA = DV.getInlinedAt()) {
1351 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1352 Scope = LScopes.findInlinedScope(DebugLoc::get(
1353 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1355 Scope = LScopes.findLexicalScope(DV.getContext());
1356 // If variable scope is not found then skip this variable.
1360 Processed.insert(getEntireVariable(DV));
1361 const MachineInstr *MInsn = Ranges.front().first;
1362 assert(MInsn->isDebugValue() && "History must begin with debug value");
1363 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1364 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1365 DbgVariable *RegVar = ConcreteVariables.back().get();
1366 addScopeVariable(Scope, RegVar);
1368 // Check if the first DBG_VALUE is valid for the rest of the function.
1369 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1372 // Handle multiple DBG_VALUE instructions describing one variable.
1373 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1375 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1376 DebugLocList &LocList = DotDebugLocEntries.back();
1379 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1381 // Build the location list for this variable.
1382 buildLocationList(LocList.List, Ranges);
1385 // Collect info for variables that were optimized out.
1386 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1387 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1388 DIVariable DV(Variables.getElement(i));
1389 assert(DV.isVariable());
1390 if (!Processed.insert(DV))
1392 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1393 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1394 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, this));
1395 addScopeVariable(Scope, ConcreteVariables.back().get());
1400 // Return Label preceding the instruction.
1401 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1402 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1403 assert(Label && "Didn't insert label before instruction");
1407 // Return Label immediately following the instruction.
1408 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1409 return LabelsAfterInsn.lookup(MI);
1412 // Process beginning of an instruction.
1413 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1414 assert(CurMI == nullptr);
1416 // Check if source location changes, but ignore DBG_VALUE locations.
1417 if (!MI->isDebugValue()) {
1418 DebugLoc DL = MI->getDebugLoc();
1419 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1422 if (DL == PrologEndLoc) {
1423 Flags |= DWARF2_FLAG_PROLOGUE_END;
1424 PrologEndLoc = DebugLoc();
1426 if (PrologEndLoc.isUnknown())
1427 Flags |= DWARF2_FLAG_IS_STMT;
1429 if (!DL.isUnknown()) {
1430 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1431 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1433 recordSourceLine(0, 0, nullptr, 0);
1437 // Insert labels where requested.
1438 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1439 LabelsBeforeInsn.find(MI);
1442 if (I == LabelsBeforeInsn.end())
1445 // Label already assigned.
1450 PrevLabel = MMI->getContext().CreateTempSymbol();
1451 Asm->OutStreamer.EmitLabel(PrevLabel);
1453 I->second = PrevLabel;
1456 // Process end of an instruction.
1457 void DwarfDebug::endInstruction() {
1458 assert(CurMI != nullptr);
1459 // Don't create a new label after DBG_VALUE instructions.
1460 // They don't generate code.
1461 if (!CurMI->isDebugValue())
1462 PrevLabel = nullptr;
1464 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1465 LabelsAfterInsn.find(CurMI);
1469 if (I == LabelsAfterInsn.end())
1472 // Label already assigned.
1476 // We need a label after this instruction.
1478 PrevLabel = MMI->getContext().CreateTempSymbol();
1479 Asm->OutStreamer.EmitLabel(PrevLabel);
1481 I->second = PrevLabel;
1484 // Each LexicalScope has first instruction and last instruction to mark
1485 // beginning and end of a scope respectively. Create an inverse map that list
1486 // scopes starts (and ends) with an instruction. One instruction may start (or
1487 // end) multiple scopes. Ignore scopes that are not reachable.
1488 void DwarfDebug::identifyScopeMarkers() {
1489 SmallVector<LexicalScope *, 4> WorkList;
1490 WorkList.push_back(LScopes.getCurrentFunctionScope());
1491 while (!WorkList.empty()) {
1492 LexicalScope *S = WorkList.pop_back_val();
1494 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1495 if (!Children.empty())
1496 WorkList.append(Children.begin(), Children.end());
1498 if (S->isAbstractScope())
1501 for (const InsnRange &R : S->getRanges()) {
1502 assert(R.first && "InsnRange does not have first instruction!");
1503 assert(R.second && "InsnRange does not have second instruction!");
1504 requestLabelBeforeInsn(R.first);
1505 requestLabelAfterInsn(R.second);
1510 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1511 // First known non-DBG_VALUE and non-frame setup location marks
1512 // the beginning of the function body.
1513 for (const auto &MBB : *MF)
1514 for (const auto &MI : MBB)
1515 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1516 !MI.getDebugLoc().isUnknown())
1517 return MI.getDebugLoc();
1521 // Gather pre-function debug information. Assumes being called immediately
1522 // after the function entry point has been emitted.
1523 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1526 // If there's no debug info for the function we're not going to do anything.
1527 if (!MMI->hasDebugInfo())
1530 auto DI = FunctionDIs.find(MF->getFunction());
1531 if (DI == FunctionDIs.end())
1534 // Grab the lexical scopes for the function, if we don't have any of those
1535 // then we're not going to be able to do anything.
1536 LScopes.initialize(*MF);
1537 if (LScopes.empty())
1540 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1542 // Make sure that each lexical scope will have a begin/end label.
1543 identifyScopeMarkers();
1545 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1546 // belongs to so that we add to the correct per-cu line table in the
1548 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1549 // FnScope->getScopeNode() and DI->second should represent the same function,
1550 // though they may not be the same MDNode due to inline functions merged in
1551 // LTO where the debug info metadata still differs (either due to distinct
1552 // written differences - two versions of a linkonce_odr function
1553 // written/copied into two separate files, or some sub-optimal metadata that
1554 // isn't structurally identical (see: file path/name info from clang, which
1555 // includes the directory of the cpp file being built, even when the file name
1556 // is absolute (such as an <> lookup header)))
1557 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1558 assert(TheCU && "Unable to find compile unit!");
1559 if (Asm->OutStreamer.hasRawTextSupport())
1560 // Use a single line table if we are generating assembly.
1561 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1563 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1565 // Emit a label for the function so that we have a beginning address.
1566 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1567 // Assumes in correct section after the entry point.
1568 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1570 // Calculate history for local variables.
1571 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1574 // Request labels for the full history.
1575 for (const auto &I : DbgValues) {
1576 const auto &Ranges = I.second;
1580 // The first mention of a function argument gets the FunctionBeginSym
1581 // label, so arguments are visible when breaking at function entry.
1582 DIVariable DV(Ranges.front().first->getDebugVariable());
1583 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1584 getDISubprogram(DV.getContext()).describes(MF->getFunction())) {
1585 if (!DV.isVariablePiece())
1586 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1588 // Mark all non-overlapping initial pieces.
1589 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1590 DIVariable Piece = I->first->getDebugVariable();
1591 if (std::all_of(Ranges.begin(), I,
1592 [&](DbgValueHistoryMap::InstrRange Pred){
1593 return !piecesOverlap(Piece, Pred.first->getDebugVariable());
1595 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1602 for (const auto &Range : Ranges) {
1603 requestLabelBeforeInsn(Range.first);
1605 requestLabelAfterInsn(Range.second);
1609 PrevInstLoc = DebugLoc();
1610 PrevLabel = FunctionBeginSym;
1612 // Record beginning of function.
1613 PrologEndLoc = findPrologueEndLoc(MF);
1614 if (!PrologEndLoc.isUnknown()) {
1615 DebugLoc FnStartDL =
1616 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1618 FnStartDL.getLine(), FnStartDL.getCol(),
1619 FnStartDL.getScope(MF->getFunction()->getContext()),
1620 // We'd like to list the prologue as "not statements" but GDB behaves
1621 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1622 DWARF2_FLAG_IS_STMT);
1626 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1627 if (addCurrentFnArgument(Var, LS))
1629 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1630 DIVariable DV = Var->getVariable();
1631 // Variables with positive arg numbers are parameters.
1632 if (unsigned ArgNum = DV.getArgNumber()) {
1633 // Keep all parameters in order at the start of the variable list to ensure
1634 // function types are correct (no out-of-order parameters)
1636 // This could be improved by only doing it for optimized builds (unoptimized
1637 // builds have the right order to begin with), searching from the back (this
1638 // would catch the unoptimized case quickly), or doing a binary search
1639 // rather than linear search.
1640 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1641 while (I != Vars.end()) {
1642 unsigned CurNum = (*I)->getVariable().getArgNumber();
1643 // A local (non-parameter) variable has been found, insert immediately
1647 // A later indexed parameter has been found, insert immediately before it.
1648 if (CurNum > ArgNum)
1652 Vars.insert(I, Var);
1656 Vars.push_back(Var);
1659 // Gather and emit post-function debug information.
1660 void DwarfDebug::endFunction(const MachineFunction *MF) {
1661 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1662 // though the beginFunction may not be called at all.
1663 // We should handle both cases.
1667 assert(CurFn == MF);
1668 assert(CurFn != nullptr);
1670 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1671 !FunctionDIs.count(MF->getFunction())) {
1672 // If we don't have a lexical scope for this function then there will
1673 // be a hole in the range information. Keep note of this by setting the
1674 // previously used section to nullptr.
1680 // Define end label for subprogram.
1681 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1682 // Assumes in correct section after the entry point.
1683 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1685 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1686 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1688 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1689 collectVariableInfo(ProcessedVars);
1691 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1692 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1694 // Add the range of this function to the list of ranges for the CU.
1695 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1697 // Under -gmlt, skip building the subprogram if there are no inlined
1698 // subroutines inside it.
1699 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1700 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1701 assert(ScopeVariables.empty());
1702 assert(CurrentFnArguments.empty());
1703 assert(DbgValues.empty());
1704 assert(AbstractVariables.empty());
1705 LabelsBeforeInsn.clear();
1706 LabelsAfterInsn.clear();
1707 PrevLabel = nullptr;
1712 // Construct abstract scopes.
1713 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1714 DISubprogram SP(AScope->getScopeNode());
1715 assert(SP.isSubprogram());
1716 // Collect info for variables that were optimized out.
1717 DIArray Variables = SP.getVariables();
1718 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1719 DIVariable DV(Variables.getElement(i));
1720 assert(DV && DV.isVariable());
1721 if (!ProcessedVars.insert(DV))
1723 ensureAbstractVariableIsCreated(DV, DV.getContext());
1725 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1728 DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
1729 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1730 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1733 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1734 // DbgVariables except those that are also in AbstractVariables (since they
1735 // can be used cross-function)
1736 ScopeVariables.clear();
1737 CurrentFnArguments.clear();
1739 LabelsBeforeInsn.clear();
1740 LabelsAfterInsn.clear();
1741 PrevLabel = nullptr;
1745 // Register a source line with debug info. Returns the unique label that was
1746 // emitted and which provides correspondence to the source line list.
1747 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1752 unsigned Discriminator = 0;
1753 if (DIScope Scope = DIScope(S)) {
1754 assert(Scope.isScope());
1755 Fn = Scope.getFilename();
1756 Dir = Scope.getDirectory();
1757 if (Scope.isLexicalBlockFile())
1758 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1760 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1761 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1762 .getOrCreateSourceID(Fn, Dir);
1764 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1768 //===----------------------------------------------------------------------===//
1770 //===----------------------------------------------------------------------===//
1772 // Emit initial Dwarf sections with a label at the start of each one.
1773 void DwarfDebug::emitSectionLabels() {
1774 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1776 // Dwarf sections base addresses.
1777 DwarfInfoSectionSym =
1778 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1779 if (useSplitDwarf()) {
1780 DwarfInfoDWOSectionSym =
1781 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1782 DwarfTypesDWOSectionSym =
1783 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1785 DwarfAbbrevSectionSym =
1786 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1787 if (useSplitDwarf())
1788 DwarfAbbrevDWOSectionSym = emitSectionSym(
1789 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1790 if (GenerateARangeSection)
1791 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1793 DwarfLineSectionSym =
1794 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1795 if (GenerateGnuPubSections) {
1796 DwarfGnuPubNamesSectionSym =
1797 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1798 DwarfGnuPubTypesSectionSym =
1799 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1800 } else if (HasDwarfPubSections) {
1801 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1802 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1805 DwarfStrSectionSym =
1806 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1807 if (useSplitDwarf()) {
1808 DwarfStrDWOSectionSym =
1809 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1810 DwarfAddrSectionSym =
1811 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1812 DwarfDebugLocSectionSym =
1813 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1815 DwarfDebugLocSectionSym =
1816 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1817 DwarfDebugRangeSectionSym =
1818 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1821 // Recursively emits a debug information entry.
1822 void DwarfDebug::emitDIE(DIE &Die) {
1823 // Get the abbreviation for this DIE.
1824 const DIEAbbrev &Abbrev = Die.getAbbrev();
1826 // Emit the code (index) for the abbreviation.
1827 if (Asm->isVerbose())
1828 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1829 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1830 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1831 dwarf::TagString(Abbrev.getTag()));
1832 Asm->EmitULEB128(Abbrev.getNumber());
1834 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1835 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1837 // Emit the DIE attribute values.
1838 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1839 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1840 dwarf::Form Form = AbbrevData[i].getForm();
1841 assert(Form && "Too many attributes for DIE (check abbreviation)");
1843 if (Asm->isVerbose()) {
1844 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1845 if (Attr == dwarf::DW_AT_accessibility)
1846 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1847 cast<DIEInteger>(Values[i])->getValue()));
1850 // Emit an attribute using the defined form.
1851 Values[i]->EmitValue(Asm, Form);
1854 // Emit the DIE children if any.
1855 if (Abbrev.hasChildren()) {
1856 for (auto &Child : Die.getChildren())
1859 Asm->OutStreamer.AddComment("End Of Children Mark");
1864 // Emit the debug info section.
1865 void DwarfDebug::emitDebugInfo() {
1866 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1868 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1871 // Emit the abbreviation section.
1872 void DwarfDebug::emitAbbreviations() {
1873 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1875 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1878 // Emit the last address of the section and the end of the line matrix.
1879 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1880 // Define last address of section.
1881 Asm->OutStreamer.AddComment("Extended Op");
1884 Asm->OutStreamer.AddComment("Op size");
1885 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1886 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1887 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1889 Asm->OutStreamer.AddComment("Section end label");
1891 Asm->OutStreamer.EmitSymbolValue(
1892 Asm->GetTempSymbol("section_end", SectionEnd),
1893 Asm->getDataLayout().getPointerSize());
1895 // Mark end of matrix.
1896 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1902 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1903 StringRef TableName, StringRef SymName) {
1904 Accel.FinalizeTable(Asm, TableName);
1905 Asm->OutStreamer.SwitchSection(Section);
1906 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1907 Asm->OutStreamer.EmitLabel(SectionBegin);
1909 // Emit the full data.
1910 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1913 // Emit visible names into a hashed accelerator table section.
1914 void DwarfDebug::emitAccelNames() {
1915 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1916 "Names", "names_begin");
1919 // Emit objective C classes and categories into a hashed accelerator table
1921 void DwarfDebug::emitAccelObjC() {
1922 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1923 "ObjC", "objc_begin");
1926 // Emit namespace dies into a hashed accelerator table.
1927 void DwarfDebug::emitAccelNamespaces() {
1928 emitAccel(AccelNamespace,
1929 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1930 "namespac", "namespac_begin");
1933 // Emit type dies into a hashed accelerator table.
1934 void DwarfDebug::emitAccelTypes() {
1935 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1936 "types", "types_begin");
1939 // Public name handling.
1940 // The format for the various pubnames:
1942 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1943 // for the DIE that is named.
1945 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1946 // into the CU and the index value is computed according to the type of value
1947 // for the DIE that is named.
1949 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1950 // it's the offset within the debug_info/debug_types dwo section, however, the
1951 // reference in the pubname header doesn't change.
1953 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1954 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1956 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1958 // We could have a specification DIE that has our most of our knowledge,
1959 // look for that now.
1960 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1962 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1963 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1964 Linkage = dwarf::GIEL_EXTERNAL;
1965 } else if (Die->findAttribute(dwarf::DW_AT_external))
1966 Linkage = dwarf::GIEL_EXTERNAL;
1968 switch (Die->getTag()) {
1969 case dwarf::DW_TAG_class_type:
1970 case dwarf::DW_TAG_structure_type:
1971 case dwarf::DW_TAG_union_type:
1972 case dwarf::DW_TAG_enumeration_type:
1973 return dwarf::PubIndexEntryDescriptor(
1974 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1975 ? dwarf::GIEL_STATIC
1976 : dwarf::GIEL_EXTERNAL);
1977 case dwarf::DW_TAG_typedef:
1978 case dwarf::DW_TAG_base_type:
1979 case dwarf::DW_TAG_subrange_type:
1980 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1981 case dwarf::DW_TAG_namespace:
1982 return dwarf::GIEK_TYPE;
1983 case dwarf::DW_TAG_subprogram:
1984 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1985 case dwarf::DW_TAG_constant:
1986 case dwarf::DW_TAG_variable:
1987 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1988 case dwarf::DW_TAG_enumerator:
1989 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1990 dwarf::GIEL_STATIC);
1992 return dwarf::GIEK_NONE;
1996 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1998 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1999 const MCSection *PSec =
2000 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2001 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2003 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2006 void DwarfDebug::emitDebugPubSection(
2007 bool GnuStyle, const MCSection *PSec, StringRef Name,
2008 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2009 for (const auto &NU : CUMap) {
2010 DwarfCompileUnit *TheU = NU.second;
2012 const auto &Globals = (TheU->*Accessor)();
2014 if (Globals.empty())
2017 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2019 unsigned ID = TheU->getUniqueID();
2021 // Start the dwarf pubnames section.
2022 Asm->OutStreamer.SwitchSection(PSec);
2025 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2026 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2027 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2028 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2030 Asm->OutStreamer.EmitLabel(BeginLabel);
2032 Asm->OutStreamer.AddComment("DWARF Version");
2033 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2035 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2036 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2038 Asm->OutStreamer.AddComment("Compilation Unit Length");
2039 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2041 // Emit the pubnames for this compilation unit.
2042 for (const auto &GI : Globals) {
2043 const char *Name = GI.getKeyData();
2044 const DIE *Entity = GI.second;
2046 Asm->OutStreamer.AddComment("DIE offset");
2047 Asm->EmitInt32(Entity->getOffset());
2050 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2051 Asm->OutStreamer.AddComment(
2052 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2053 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2054 Asm->EmitInt8(Desc.toBits());
2057 Asm->OutStreamer.AddComment("External Name");
2058 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2061 Asm->OutStreamer.AddComment("End Mark");
2063 Asm->OutStreamer.EmitLabel(EndLabel);
2067 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2068 const MCSection *PSec =
2069 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2070 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2072 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2075 // Emit visible names into a debug str section.
2076 void DwarfDebug::emitDebugStr() {
2077 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2078 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2081 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
2082 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
2083 const DITypeIdentifierMap &Map,
2084 ArrayRef<DebugLocEntry::Value> Values) {
2085 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
2086 return P.isVariablePiece();
2087 }) && "all values are expected to be pieces");
2088 assert(std::is_sorted(Values.begin(), Values.end()) &&
2089 "pieces are expected to be sorted");
2091 unsigned Offset = 0;
2092 for (auto Piece : Values) {
2093 DIVariable Var = Piece.getVariable();
2094 unsigned PieceOffset = Var.getPieceOffset();
2095 unsigned PieceSize = Var.getPieceSize();
2096 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
2097 if (Offset < PieceOffset) {
2098 // The DWARF spec seriously mandates pieces with no locations for gaps.
2099 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
2100 Offset += PieceOffset-Offset;
2103 Offset += PieceSize;
2105 const unsigned SizeOfByte = 8;
2106 assert(!Var.isIndirect() && "indirect address for piece");
2108 unsigned VarSize = Var.getSizeInBits(Map);
2109 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
2110 && "piece is larger than or outside of variable");
2111 assert(PieceSize*SizeOfByte != VarSize
2112 && "piece covers entire variable");
2114 if (Piece.isLocation() && Piece.getLoc().isReg())
2115 Asm->EmitDwarfRegOpPiece(Streamer,
2117 PieceSize*SizeOfByte);
2119 emitDebugLocValue(Streamer, Piece);
2120 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
2126 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2127 const DebugLocEntry &Entry) {
2128 const DebugLocEntry::Value Value = Entry.getValues()[0];
2129 if (Value.isVariablePiece())
2130 // Emit all pieces that belong to the same variable and range.
2131 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
2133 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
2134 emitDebugLocValue(Streamer, Value);
2137 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
2138 const DebugLocEntry::Value &Value) {
2139 DIVariable DV = Value.getVariable();
2141 if (Value.isInt()) {
2142 DIBasicType BTy(resolve(DV.getType()));
2143 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2144 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2145 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2146 Streamer.EmitSLEB128(Value.getInt());
2148 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2149 Streamer.EmitULEB128(Value.getInt());
2151 } else if (Value.isLocation()) {
2152 MachineLocation Loc = Value.getLoc();
2153 if (!DV.hasComplexAddress())
2155 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2157 // Complex address entry.
2158 unsigned N = DV.getNumAddrElements();
2160 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2161 if (Loc.getOffset()) {
2163 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2164 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2165 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2166 Streamer.EmitSLEB128(DV.getAddrElement(1));
2168 // If first address element is OpPlus then emit
2169 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2170 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2171 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2175 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2178 // Emit remaining complex address elements.
2179 for (; i < N; ++i) {
2180 uint64_t Element = DV.getAddrElement(i);
2181 if (Element == DIBuilder::OpPlus) {
2182 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2183 Streamer.EmitULEB128(DV.getAddrElement(++i));
2184 } else if (Element == DIBuilder::OpDeref) {
2186 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2187 } else if (Element == DIBuilder::OpPiece) {
2189 // handled in emitDebugLocEntry.
2191 llvm_unreachable("unknown Opcode found in complex address");
2195 // else ... ignore constant fp. There is not any good way to
2196 // to represent them here in dwarf.
2200 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2201 Asm->OutStreamer.AddComment("Loc expr size");
2202 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2203 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2204 Asm->EmitLabelDifference(end, begin, 2);
2205 Asm->OutStreamer.EmitLabel(begin);
2207 APByteStreamer Streamer(*Asm);
2208 emitDebugLocEntry(Streamer, Entry);
2210 Asm->OutStreamer.EmitLabel(end);
2213 // Emit locations into the debug loc section.
2214 void DwarfDebug::emitDebugLoc() {
2215 // Start the dwarf loc section.
2216 Asm->OutStreamer.SwitchSection(
2217 Asm->getObjFileLowering().getDwarfLocSection());
2218 unsigned char Size = Asm->getDataLayout().getPointerSize();
2219 for (const auto &DebugLoc : DotDebugLocEntries) {
2220 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2221 const DwarfCompileUnit *CU = DebugLoc.CU;
2222 assert(!CU->getRanges().empty());
2223 for (const auto &Entry : DebugLoc.List) {
2224 // Set up the range. This range is relative to the entry point of the
2225 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2226 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2227 if (CU->getRanges().size() == 1) {
2228 // Grab the begin symbol from the first range as our base.
2229 const MCSymbol *Base = CU->getRanges()[0].getStart();
2230 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2231 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2233 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2234 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2237 emitDebugLocEntryLocation(Entry);
2239 Asm->OutStreamer.EmitIntValue(0, Size);
2240 Asm->OutStreamer.EmitIntValue(0, Size);
2244 void DwarfDebug::emitDebugLocDWO() {
2245 Asm->OutStreamer.SwitchSection(
2246 Asm->getObjFileLowering().getDwarfLocDWOSection());
2247 for (const auto &DebugLoc : DotDebugLocEntries) {
2248 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2249 for (const auto &Entry : DebugLoc.List) {
2250 // Just always use start_length for now - at least that's one address
2251 // rather than two. We could get fancier and try to, say, reuse an
2252 // address we know we've emitted elsewhere (the start of the function?
2253 // The start of the CU or CU subrange that encloses this range?)
2254 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2255 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2256 Asm->EmitULEB128(idx);
2257 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2259 emitDebugLocEntryLocation(Entry);
2261 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2266 const MCSymbol *Start, *End;
2269 // Emit a debug aranges section, containing a CU lookup for any
2270 // address we can tie back to a CU.
2271 void DwarfDebug::emitDebugARanges() {
2272 // Start the dwarf aranges section.
2273 Asm->OutStreamer.SwitchSection(
2274 Asm->getObjFileLowering().getDwarfARangesSection());
2276 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2280 // Build a list of sections used.
2281 std::vector<const MCSection *> Sections;
2282 for (const auto &it : SectionMap) {
2283 const MCSection *Section = it.first;
2284 Sections.push_back(Section);
2287 // Sort the sections into order.
2288 // This is only done to ensure consistent output order across different runs.
2289 std::sort(Sections.begin(), Sections.end(), SectionSort);
2291 // Build a set of address spans, sorted by CU.
2292 for (const MCSection *Section : Sections) {
2293 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2294 if (List.size() < 2)
2297 // Sort the symbols by offset within the section.
2298 std::sort(List.begin(), List.end(),
2299 [&](const SymbolCU &A, const SymbolCU &B) {
2300 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2301 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2303 // Symbols with no order assigned should be placed at the end.
2304 // (e.g. section end labels)
2312 // If we have no section (e.g. common), just write out
2313 // individual spans for each symbol.
2315 for (const SymbolCU &Cur : List) {
2317 Span.Start = Cur.Sym;
2320 Spans[Cur.CU].push_back(Span);
2323 // Build spans between each label.
2324 const MCSymbol *StartSym = List[0].Sym;
2325 for (size_t n = 1, e = List.size(); n < e; n++) {
2326 const SymbolCU &Prev = List[n - 1];
2327 const SymbolCU &Cur = List[n];
2329 // Try and build the longest span we can within the same CU.
2330 if (Cur.CU != Prev.CU) {
2332 Span.Start = StartSym;
2334 Spans[Prev.CU].push_back(Span);
2341 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2343 // Build a list of CUs used.
2344 std::vector<DwarfCompileUnit *> CUs;
2345 for (const auto &it : Spans) {
2346 DwarfCompileUnit *CU = it.first;
2350 // Sort the CU list (again, to ensure consistent output order).
2351 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2352 return A->getUniqueID() < B->getUniqueID();
2355 // Emit an arange table for each CU we used.
2356 for (DwarfCompileUnit *CU : CUs) {
2357 std::vector<ArangeSpan> &List = Spans[CU];
2359 // Emit size of content not including length itself.
2360 unsigned ContentSize =
2361 sizeof(int16_t) + // DWARF ARange version number
2362 sizeof(int32_t) + // Offset of CU in the .debug_info section
2363 sizeof(int8_t) + // Pointer Size (in bytes)
2364 sizeof(int8_t); // Segment Size (in bytes)
2366 unsigned TupleSize = PtrSize * 2;
2368 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2370 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2372 ContentSize += Padding;
2373 ContentSize += (List.size() + 1) * TupleSize;
2375 // For each compile unit, write the list of spans it covers.
2376 Asm->OutStreamer.AddComment("Length of ARange Set");
2377 Asm->EmitInt32(ContentSize);
2378 Asm->OutStreamer.AddComment("DWARF Arange version number");
2379 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2380 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2381 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2382 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2383 Asm->EmitInt8(PtrSize);
2384 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2387 Asm->OutStreamer.EmitFill(Padding, 0xff);
2389 for (const ArangeSpan &Span : List) {
2390 Asm->EmitLabelReference(Span.Start, PtrSize);
2392 // Calculate the size as being from the span start to it's end.
2394 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2396 // For symbols without an end marker (e.g. common), we
2397 // write a single arange entry containing just that one symbol.
2398 uint64_t Size = SymSize[Span.Start];
2402 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2406 Asm->OutStreamer.AddComment("ARange terminator");
2407 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2408 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2412 // Emit visible names into a debug ranges section.
2413 void DwarfDebug::emitDebugRanges() {
2414 // Start the dwarf ranges section.
2415 Asm->OutStreamer.SwitchSection(
2416 Asm->getObjFileLowering().getDwarfRangesSection());
2418 // Size for our labels.
2419 unsigned char Size = Asm->getDataLayout().getPointerSize();
2421 // Grab the specific ranges for the compile units in the module.
2422 for (const auto &I : CUMap) {
2423 DwarfCompileUnit *TheCU = I.second;
2425 // Iterate over the misc ranges for the compile units in the module.
2426 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2427 // Emit our symbol so we can find the beginning of the range.
2428 Asm->OutStreamer.EmitLabel(List.getSym());
2430 for (const RangeSpan &Range : List.getRanges()) {
2431 const MCSymbol *Begin = Range.getStart();
2432 const MCSymbol *End = Range.getEnd();
2433 assert(Begin && "Range without a begin symbol?");
2434 assert(End && "Range without an end symbol?");
2435 if (TheCU->getRanges().size() == 1) {
2436 // Grab the begin symbol from the first range as our base.
2437 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2438 Asm->EmitLabelDifference(Begin, Base, Size);
2439 Asm->EmitLabelDifference(End, Base, Size);
2441 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2442 Asm->OutStreamer.EmitSymbolValue(End, Size);
2446 // And terminate the list with two 0 values.
2447 Asm->OutStreamer.EmitIntValue(0, Size);
2448 Asm->OutStreamer.EmitIntValue(0, Size);
2451 // Now emit a range for the CU itself.
2452 if (TheCU->getRanges().size() > 1) {
2453 Asm->OutStreamer.EmitLabel(
2454 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2455 for (const RangeSpan &Range : TheCU->getRanges()) {
2456 const MCSymbol *Begin = Range.getStart();
2457 const MCSymbol *End = Range.getEnd();
2458 assert(Begin && "Range without a begin symbol?");
2459 assert(End && "Range without an end symbol?");
2460 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2461 Asm->OutStreamer.EmitSymbolValue(End, Size);
2463 // And terminate the list with two 0 values.
2464 Asm->OutStreamer.EmitIntValue(0, Size);
2465 Asm->OutStreamer.EmitIntValue(0, Size);
2470 // DWARF5 Experimental Separate Dwarf emitters.
2472 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2473 std::unique_ptr<DwarfUnit> NewU) {
2474 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2475 U.getCUNode().getSplitDebugFilename());
2477 if (!CompilationDir.empty())
2478 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2480 addGnuPubAttributes(*NewU, Die);
2482 SkeletonHolder.addUnit(std::move(NewU));
2485 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2486 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2487 // DW_AT_addr_base, DW_AT_ranges_base.
2488 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2490 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2491 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2492 DwarfCompileUnit &NewCU = *OwnedUnit;
2493 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2494 DwarfInfoSectionSym);
2496 NewCU.initStmtList(DwarfLineSectionSym);
2498 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2503 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2504 // compile units that would normally be in debug_info.
2505 void DwarfDebug::emitDebugInfoDWO() {
2506 assert(useSplitDwarf() && "No split dwarf debug info?");
2507 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2508 // emit relocations into the dwo file.
2509 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2512 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2513 // abbreviations for the .debug_info.dwo section.
2514 void DwarfDebug::emitDebugAbbrevDWO() {
2515 assert(useSplitDwarf() && "No split dwarf?");
2516 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2519 void DwarfDebug::emitDebugLineDWO() {
2520 assert(useSplitDwarf() && "No split dwarf?");
2521 Asm->OutStreamer.SwitchSection(
2522 Asm->getObjFileLowering().getDwarfLineDWOSection());
2523 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2526 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2527 // string section and is identical in format to traditional .debug_str
2529 void DwarfDebug::emitDebugStrDWO() {
2530 assert(useSplitDwarf() && "No split dwarf?");
2531 const MCSection *OffSec =
2532 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2533 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2537 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2538 if (!useSplitDwarf())
2541 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2542 return &SplitTypeUnitFileTable;
2545 static uint64_t makeTypeSignature(StringRef Identifier) {
2547 Hash.update(Identifier);
2548 // ... take the least significant 8 bytes and return those. Our MD5
2549 // implementation always returns its results in little endian, swap bytes
2551 MD5::MD5Result Result;
2553 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2556 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2557 StringRef Identifier, DIE &RefDie,
2558 DICompositeType CTy) {
2559 // Fast path if we're building some type units and one has already used the
2560 // address pool we know we're going to throw away all this work anyway, so
2561 // don't bother building dependent types.
2562 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2565 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2567 CU.addDIETypeSignature(RefDie, *TU);
2571 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2572 AddrPool.resetUsedFlag();
2574 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2575 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2576 this, &InfoHolder, getDwoLineTable(CU));
2577 DwarfTypeUnit &NewTU = *OwnedUnit;
2578 DIE &UnitDie = NewTU.getUnitDie();
2580 TypeUnitsUnderConstruction.push_back(
2581 std::make_pair(std::move(OwnedUnit), CTy));
2583 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2586 uint64_t Signature = makeTypeSignature(Identifier);
2587 NewTU.setTypeSignature(Signature);
2589 if (useSplitDwarf())
2590 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2591 DwarfTypesDWOSectionSym);
2593 CU.applyStmtList(UnitDie);
2595 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2598 NewTU.setType(NewTU.createTypeDIE(CTy));
2601 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2602 TypeUnitsUnderConstruction.clear();
2604 // Types referencing entries in the address table cannot be placed in type
2606 if (AddrPool.hasBeenUsed()) {
2608 // Remove all the types built while building this type.
2609 // This is pessimistic as some of these types might not be dependent on
2610 // the type that used an address.
2611 for (const auto &TU : TypeUnitsToAdd)
2612 DwarfTypeUnits.erase(TU.second);
2614 // Construct this type in the CU directly.
2615 // This is inefficient because all the dependent types will be rebuilt
2616 // from scratch, including building them in type units, discovering that
2617 // they depend on addresses, throwing them out and rebuilding them.
2618 CU.constructTypeDIE(RefDie, CTy);
2622 // If the type wasn't dependent on fission addresses, finish adding the type
2623 // and all its dependent types.
2624 for (auto &TU : TypeUnitsToAdd)
2625 InfoHolder.addUnit(std::move(TU.first));
2627 CU.addDIETypeSignature(RefDie, NewTU);
2630 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2631 const MCSymbol *Begin, const MCSymbol *End) {
2632 assert(Begin && "Begin label should not be null!");
2633 assert(End && "End label should not be null!");
2634 assert(Begin->isDefined() && "Invalid starting label");
2635 assert(End->isDefined() && "Invalid end label");
2637 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2638 if (DwarfVersion < 4)
2639 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2641 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2644 // Accelerator table mutators - add each name along with its companion
2645 // DIE to the proper table while ensuring that the name that we're going
2646 // to reference is in the string table. We do this since the names we
2647 // add may not only be identical to the names in the DIE.
2648 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2649 if (!useDwarfAccelTables())
2651 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2655 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2656 if (!useDwarfAccelTables())
2658 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2662 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2663 if (!useDwarfAccelTables())
2665 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2669 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2670 if (!useDwarfAccelTables())
2672 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),