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 "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Dwarf.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"
53 #define DEBUG_TYPE "dwarfdebug"
56 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
57 cl::desc("Disable debug info printing"));
59 static cl::opt<bool> UnknownLocations(
60 "use-unknown-locations", cl::Hidden,
61 cl::desc("Make an absence of debug location information explicit."),
65 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
66 cl::desc("Generate GNU-style pubnames and pubtypes"),
69 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
71 cl::desc("Generate dwarf aranges"),
75 enum DefaultOnOff { Default, Enable, Disable };
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 static cl::opt<DefaultOnOff>
87 SplitDwarf("split-dwarf", cl::Hidden,
88 cl::desc("Output DWARF5 split debug info."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 static cl::opt<DefaultOnOff>
95 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
96 cl::desc("Generate DWARF pubnames and pubtypes sections"),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 static cl::opt<unsigned>
103 DwarfVersionNumber("dwarf-version", cl::Hidden,
104 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
106 static const char *const DWARFGroupName = "DWARF Emission";
107 static const char *const DbgTimerName = "DWARF Debug Writer";
109 //===----------------------------------------------------------------------===//
113 /// resolve - Look in the DwarfDebug map for the MDNode that
114 /// corresponds to the reference.
115 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
116 return DD->resolve(Ref);
119 bool DbgVariable::isBlockByrefVariable() const {
120 assert(Var.isVariable() && "Invalid complex DbgVariable!");
121 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
125 DIType DbgVariable::getType() const {
126 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
127 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
128 // addresses instead.
129 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
130 /* Byref variables, in Blocks, are declared by the programmer as
131 "SomeType VarName;", but the compiler creates a
132 __Block_byref_x_VarName struct, and gives the variable VarName
133 either the struct, or a pointer to the struct, as its type. This
134 is necessary for various behind-the-scenes things the compiler
135 needs to do with by-reference variables in blocks.
137 However, as far as the original *programmer* is concerned, the
138 variable should still have type 'SomeType', as originally declared.
140 The following function dives into the __Block_byref_x_VarName
141 struct to find the original type of the variable. This will be
142 passed back to the code generating the type for the Debug
143 Information Entry for the variable 'VarName'. 'VarName' will then
144 have the original type 'SomeType' in its debug information.
146 The original type 'SomeType' will be the type of the field named
147 'VarName' inside the __Block_byref_x_VarName struct.
149 NOTE: In order for this to not completely fail on the debugger
150 side, the Debug Information Entry for the variable VarName needs to
151 have a DW_AT_location that tells the debugger how to unwind through
152 the pointers and __Block_byref_x_VarName struct to find the actual
153 value of the variable. The function addBlockByrefType does this. */
155 uint16_t tag = Ty.getTag();
157 if (tag == dwarf::DW_TAG_pointer_type)
158 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
160 DIArray Elements = DICompositeType(subType).getTypeArray();
161 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
162 DIDerivedType DT(Elements.getElement(i));
163 if (getName() == DT.getName())
164 return (resolve(DT.getTypeDerivedFrom()));
170 } // end llvm namespace
172 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
173 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
174 InfoHolder(A, "info_string", DIEValueAllocator),
175 UsedNonDefaultText(false),
176 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
178 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
179 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
180 DwarfAddrSectionSym = 0;
181 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
182 FunctionBeginSym = FunctionEndSym = 0;
186 // Turn on accelerator tables for Darwin by default, pubnames by
187 // default for non-Darwin, and handle split dwarf.
188 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
190 if (DwarfAccelTables == Default)
191 HasDwarfAccelTables = IsDarwin;
193 HasDwarfAccelTables = DwarfAccelTables == Enable;
195 if (SplitDwarf == Default)
196 HasSplitDwarf = false;
198 HasSplitDwarf = SplitDwarf == Enable;
200 if (DwarfPubSections == Default)
201 HasDwarfPubSections = !IsDarwin;
203 HasDwarfPubSections = DwarfPubSections == Enable;
205 DwarfVersion = DwarfVersionNumber
207 : MMI->getModule()->getDwarfVersion();
210 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
215 // Switch to the specified MCSection and emit an assembler
216 // temporary label to it if SymbolStem is specified.
217 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
218 const char *SymbolStem = 0) {
219 Asm->OutStreamer.SwitchSection(Section);
223 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
224 Asm->OutStreamer.EmitLabel(TmpSym);
228 DwarfFile::~DwarfFile() {
229 for (DwarfUnit *DU : CUs)
233 MCSymbol *DwarfFile::getStringPoolSym() {
234 return Asm->GetTempSymbol(StringPref);
237 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
238 std::pair<MCSymbol *, unsigned> &Entry =
239 StringPool.GetOrCreateValue(Str).getValue();
243 Entry.second = NextStringPoolNumber++;
244 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
247 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
248 std::pair<MCSymbol *, unsigned> &Entry =
249 StringPool.GetOrCreateValue(Str).getValue();
253 Entry.second = NextStringPoolNumber++;
254 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
259 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
260 std::make_pair(Sym, AddressPoolEntry(AddressPool.size(), TLS)));
261 return P.first->second.Number;
264 // Define a unique number for the abbreviation.
266 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
267 // Check the set for priors.
268 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
270 // If it's newly added.
271 if (InSet == &Abbrev) {
272 // Add to abbreviation list.
273 Abbreviations.push_back(&Abbrev);
275 // Assign the vector position + 1 as its number.
276 Abbrev.setNumber(Abbreviations.size());
278 // Assign existing abbreviation number.
279 Abbrev.setNumber(InSet->getNumber());
283 static bool isObjCClass(StringRef Name) {
284 return Name.startswith("+") || Name.startswith("-");
287 static bool hasObjCCategory(StringRef Name) {
288 if (!isObjCClass(Name))
291 return Name.find(") ") != StringRef::npos;
294 static void getObjCClassCategory(StringRef In, StringRef &Class,
295 StringRef &Category) {
296 if (!hasObjCCategory(In)) {
297 Class = In.slice(In.find('[') + 1, In.find(' '));
302 Class = In.slice(In.find('[') + 1, In.find('('));
303 Category = In.slice(In.find('[') + 1, In.find(' '));
307 static StringRef getObjCMethodName(StringRef In) {
308 return In.slice(In.find(' ') + 1, In.find(']'));
311 // Helper for sorting sections into a stable output order.
312 static bool SectionSort(const MCSection *A, const MCSection *B) {
313 std::string LA = (A ? A->getLabelBeginName() : "");
314 std::string LB = (B ? B->getLabelBeginName() : "");
318 // Add the various names to the Dwarf accelerator table names.
319 // TODO: Determine whether or not we should add names for programs
320 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
321 // is only slightly different than the lookup of non-standard ObjC names.
322 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
323 if (!SP.isDefinition())
325 TheU->addAccelName(SP.getName(), Die);
327 // If the linkage name is different than the name, go ahead and output
328 // that as well into the name table.
329 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
330 TheU->addAccelName(SP.getLinkageName(), Die);
332 // If this is an Objective-C selector name add it to the ObjC accelerator
334 if (isObjCClass(SP.getName())) {
335 StringRef Class, Category;
336 getObjCClassCategory(SP.getName(), Class, Category);
337 TheU->addAccelObjC(Class, Die);
339 TheU->addAccelObjC(Category, Die);
340 // Also add the base method name to the name table.
341 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
345 /// isSubprogramContext - Return true if Context is either a subprogram
346 /// or another context nested inside a subprogram.
347 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
350 DIDescriptor D(Context);
351 if (D.isSubprogram())
354 return isSubprogramContext(resolve(DIType(Context).getContext()));
358 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
359 // and DW_AT_high_pc attributes. If there are global variables in this
360 // scope then create and insert DIEs for these variables.
361 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
363 DIE *SPDie = SPCU->getDIE(SP);
365 assert(SPDie && "Unable to find subprogram DIE!");
367 // If we're updating an abstract DIE, then we will be adding the children and
368 // object pointer later on. But what we don't want to do is process the
369 // concrete DIE twice.
370 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
371 // Pick up abstract subprogram DIE.
373 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
374 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
376 DISubprogram SPDecl = SP.getFunctionDeclaration();
377 if (!SPDecl.isSubprogram()) {
378 // There is not any need to generate specification DIE for a function
379 // defined at compile unit level. If a function is defined inside another
380 // function then gdb prefers the definition at top level and but does not
381 // expect specification DIE in parent function. So avoid creating
382 // specification DIE for a function defined inside a function.
383 DIScope SPContext = resolve(SP.getContext());
384 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
385 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
386 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
389 DICompositeType SPTy = SP.getType();
390 DIArray Args = SPTy.getTypeArray();
391 uint16_t SPTag = SPTy.getTag();
392 if (SPTag == dwarf::DW_TAG_subroutine_type)
393 SPCU->constructSubprogramArguments(*SPDie, Args);
394 DIE *SPDeclDie = SPDie;
395 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
396 *SPCU->getUnitDie());
397 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
402 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
404 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
405 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
406 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
408 // Add name to the name table, we do this here because we're guaranteed
409 // to have concrete versions of our DW_TAG_subprogram nodes.
410 addSubprogramNames(SPCU, SP, SPDie);
415 /// Check whether we should create a DIE for the given Scope, return true
416 /// if we don't create a DIE (the corresponding DIE is null).
417 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
418 if (Scope->isAbstractScope())
421 // We don't create a DIE if there is no Range.
422 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
426 if (Ranges.size() > 1)
429 // We don't create a DIE if we have a single Range and the end label
431 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
432 MCSymbol *End = getLabelAfterInsn(RI->second);
436 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
437 dwarf::Attribute A, const MCSymbol *L,
438 const MCSymbol *Sec) {
439 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
440 U->addSectionLabel(D, A, L);
442 U->addSectionDelta(D, A, L, Sec);
445 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
446 const SmallVectorImpl<InsnRange> &Range) {
447 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
448 // emitting it appropriately.
449 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
451 // Under fission, ranges are specified by constant offsets relative to the
452 // CU's DW_AT_GNU_ranges_base.
454 TheCU->addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
455 DwarfDebugRangeSectionSym);
457 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
458 DwarfDebugRangeSectionSym);
460 RangeSpanList List(RangeSym);
461 for (const InsnRange &R : Range) {
462 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
463 List.addRange(std::move(Span));
466 // Add the range list to the set of ranges to be emitted.
467 TheCU->addRangeList(std::move(List));
470 // Construct new DW_TAG_lexical_block for this scope and attach
471 // DW_AT_low_pc/DW_AT_high_pc labels.
472 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
473 LexicalScope *Scope) {
474 if (isLexicalScopeDIENull(Scope))
477 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
478 if (Scope->isAbstractScope())
481 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
483 // If we have multiple ranges, emit them into the range section.
484 if (ScopeRanges.size() > 1) {
485 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
489 // Construct the address range for this DIE.
490 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
491 MCSymbol *Start = getLabelBeforeInsn(RI->first);
492 MCSymbol *End = getLabelAfterInsn(RI->second);
493 assert(End && "End label should not be null!");
495 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
496 assert(End->isDefined() && "Invalid end label for an inlined scope!");
498 attachLowHighPC(TheCU, ScopeDIE, Start, End);
503 // This scope represents inlined body of a function. Construct DIE to
504 // represent this concrete inlined copy of the function.
505 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
506 LexicalScope *Scope) {
507 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
508 assert(!ScopeRanges.empty() &&
509 "LexicalScope does not have instruction markers!");
511 if (!Scope->getScopeNode())
513 DIScope DS(Scope->getScopeNode());
514 DISubprogram InlinedSP = getDISubprogram(DS);
515 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
517 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
521 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
522 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
524 // If we have multiple ranges, emit them into the range section.
525 if (ScopeRanges.size() > 1)
526 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
528 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
529 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
530 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
532 if (StartLabel == 0 || EndLabel == 0)
533 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
535 assert(StartLabel->isDefined() &&
536 "Invalid starting label for an inlined scope!");
537 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
539 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
542 InlinedSubprogramDIEs.insert(OriginDIE);
544 // Add the call site information to the DIE.
545 DILocation DL(Scope->getInlinedAt());
547 ScopeDIE, dwarf::DW_AT_call_file, None,
548 TheCU->getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
549 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
551 // Add name to the name table, we do this here because we're guaranteed
552 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
553 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
558 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
560 SmallVectorImpl<DIE *> &Children) {
561 DIE *ObjectPointer = NULL;
563 // Collect arguments for current function.
564 if (LScopes.isCurrentFunctionScope(Scope)) {
565 for (DbgVariable *ArgDV : CurrentFnArguments)
568 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
569 Children.push_back(Arg);
570 if (ArgDV->isObjectPointer())
574 // If this is a variadic function, add an unspecified parameter.
575 DISubprogram SP(Scope->getScopeNode());
576 DIArray FnArgs = SP.getType().getTypeArray();
577 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
578 .isUnspecifiedParameter()) {
579 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
580 Children.push_back(Ellipsis);
584 // Collect lexical scope children first.
585 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
586 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
587 Scope->isAbstractScope())) {
588 Children.push_back(Variable);
589 if (DV->isObjectPointer())
590 ObjectPointer = Variable;
592 for (LexicalScope *LS : Scope->getChildren())
593 if (DIE *Nested = constructScopeDIE(TheCU, LS))
594 Children.push_back(Nested);
595 return ObjectPointer;
598 // Construct a DIE for this scope.
599 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
600 LexicalScope *Scope) {
601 if (!Scope || !Scope->getScopeNode())
604 DIScope DS(Scope->getScopeNode());
606 SmallVector<DIE *, 8> Children;
607 DIE *ObjectPointer = NULL;
608 bool ChildrenCreated = false;
610 // We try to create the scope DIE first, then the children DIEs. This will
611 // avoid creating un-used children then removing them later when we find out
612 // the scope DIE is null.
613 DIE *ScopeDIE = NULL;
614 if (Scope->getInlinedAt())
615 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
616 else if (DS.isSubprogram()) {
617 ProcessedSPNodes.insert(DS);
618 if (Scope->isAbstractScope()) {
619 ScopeDIE = TheCU->getDIE(DS);
620 // Note down abstract DIE.
622 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
624 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
626 // Early exit when we know the scope DIE is going to be null.
627 if (isLexicalScopeDIENull(Scope))
630 // We create children here when we know the scope DIE is not going to be
631 // null and the children will be added to the scope DIE.
632 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
633 ChildrenCreated = true;
635 // There is no need to emit empty lexical block DIE.
636 std::pair<ImportedEntityMap::const_iterator,
637 ImportedEntityMap::const_iterator> Range =
639 ScopesWithImportedEntities.begin(),
640 ScopesWithImportedEntities.end(),
641 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
643 if (Children.empty() && Range.first == Range.second)
645 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
646 assert(ScopeDIE && "Scope DIE should not be null.");
647 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
649 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
653 assert(Children.empty() &&
654 "We create children only when the scope DIE is not null.");
657 if (!ChildrenCreated)
658 // We create children when the scope DIE is not null.
659 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
662 for (DIE *I : Children)
663 ScopeDIE->addChild(I);
665 if (DS.isSubprogram() && ObjectPointer != NULL)
666 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
671 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
672 if (!GenerateGnuPubSections)
675 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
678 // Create new DwarfCompileUnit for the given metadata node with tag
679 // DW_TAG_compile_unit.
680 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
681 StringRef FN = DIUnit.getFilename();
682 CompilationDir = DIUnit.getDirectory();
684 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
685 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
686 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
687 InfoHolder.addUnit(NewCU);
689 // LTO with assembly output shares a single line table amongst multiple CUs.
690 // To avoid the compilation directory being ambiguous, let the line table
691 // explicitly describe the directory of all files, never relying on the
692 // compilation directory.
693 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
694 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
695 NewCU->getUniqueID(), CompilationDir);
697 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
698 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
699 DIUnit.getLanguage());
700 NewCU->addString(Die, dwarf::DW_AT_name, FN);
702 if (!useSplitDwarf()) {
703 NewCU->initStmtList(DwarfLineSectionSym);
705 // If we're using split dwarf the compilation dir is going to be in the
706 // skeleton CU and so we don't need to duplicate it here.
707 if (!CompilationDir.empty())
708 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
710 addGnuPubAttributes(NewCU, Die);
713 if (DIUnit.isOptimized())
714 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
716 StringRef Flags = DIUnit.getFlags();
718 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
720 if (unsigned RVer = DIUnit.getRunTimeVersion())
721 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
722 dwarf::DW_FORM_data1, RVer);
727 if (useSplitDwarf()) {
728 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
729 DwarfInfoDWOSectionSym);
730 NewCU->setSkeleton(constructSkeletonCU(NewCU));
732 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
733 DwarfInfoSectionSym);
735 CUMap.insert(std::make_pair(DIUnit, NewCU));
736 CUDieMap.insert(std::make_pair(Die, NewCU));
740 // Construct subprogram DIE.
741 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
743 // FIXME: We should only call this routine once, however, during LTO if a
744 // program is defined in multiple CUs we could end up calling it out of
745 // beginModule as we walk the CUs.
747 DwarfCompileUnit *&CURef = SPMap[N];
753 if (!SP.isDefinition())
754 // This is a method declaration which will be handled while constructing
758 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
760 // Expose as a global name.
761 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
764 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
766 DIImportedEntity Module(N);
767 assert(Module.Verify());
768 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
769 constructImportedEntityDIE(TheCU, Module, D);
772 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
773 const MDNode *N, DIE *Context) {
774 DIImportedEntity Module(N);
775 assert(Module.Verify());
776 return constructImportedEntityDIE(TheCU, Module, Context);
779 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
780 const DIImportedEntity &Module,
782 assert(Module.Verify() &&
783 "Use one of the MDNode * overloads to handle invalid metadata");
784 assert(Context && "Should always have a context for an imported_module");
785 DIE *IMDie = TheCU->createAndAddDIE(Module.getTag(), *Context, Module);
787 DIDescriptor Entity = resolve(Module.getEntity());
788 if (Entity.isNameSpace())
789 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
790 else if (Entity.isSubprogram())
791 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
792 else if (Entity.isType())
793 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
795 EntityDie = TheCU->getDIE(Entity);
796 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
797 Module.getContext().getFilename(),
798 Module.getContext().getDirectory());
799 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
800 StringRef Name = Module.getName();
802 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
805 // Emit all Dwarf sections that should come prior to the content. Create
806 // global DIEs and emit initial debug info sections. This is invoked by
807 // the target AsmPrinter.
808 void DwarfDebug::beginModule() {
809 if (DisableDebugInfoPrinting)
812 const Module *M = MMI->getModule();
814 // If module has named metadata anchors then use them, otherwise scan the
815 // module using debug info finder to collect debug info.
816 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
819 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
821 // Emit initial sections so we can reference labels later.
824 SingleCU = CU_Nodes->getNumOperands() == 1;
826 for (MDNode *N : CU_Nodes->operands()) {
827 DICompileUnit CUNode(N);
828 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
829 DIArray ImportedEntities = CUNode.getImportedEntities();
830 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
831 ScopesWithImportedEntities.push_back(std::make_pair(
832 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
833 ImportedEntities.getElement(i)));
834 std::sort(ScopesWithImportedEntities.begin(),
835 ScopesWithImportedEntities.end(), less_first());
836 DIArray GVs = CUNode.getGlobalVariables();
837 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
838 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
839 DIArray SPs = CUNode.getSubprograms();
840 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
841 constructSubprogramDIE(CU, SPs.getElement(i));
842 DIArray EnumTypes = CUNode.getEnumTypes();
843 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
844 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
845 DIArray RetainedTypes = CUNode.getRetainedTypes();
846 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
847 DIType Ty(RetainedTypes.getElement(i));
848 // The retained types array by design contains pointers to
849 // MDNodes rather than DIRefs. Unique them here.
850 DIType UniqueTy(resolve(Ty.getRef()));
851 CU->getOrCreateTypeDIE(UniqueTy);
853 // Emit imported_modules last so that the relevant context is already
855 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
856 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
859 // Tell MMI that we have debug info.
860 MMI->setDebugInfoAvailability(true);
862 // Prime section data.
863 SectionMap[Asm->getObjFileLowering().getTextSection()];
866 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
867 void DwarfDebug::computeInlinedDIEs() {
868 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
869 for (DIE *ISP : InlinedSubprogramDIEs)
870 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
872 for (const auto &AI : AbstractSPDies) {
873 DIE *ISP = AI.second;
874 if (InlinedSubprogramDIEs.count(ISP))
876 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
880 // Collect info for variables that were optimized out.
881 void DwarfDebug::collectDeadVariables() {
882 const Module *M = MMI->getModule();
884 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
885 for (MDNode *N : CU_Nodes->operands()) {
886 DICompileUnit TheCU(N);
887 DIArray Subprograms = TheCU.getSubprograms();
888 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
889 DISubprogram SP(Subprograms.getElement(i));
890 if (ProcessedSPNodes.count(SP) != 0)
892 if (!SP.isSubprogram())
894 if (!SP.isDefinition())
896 DIArray Variables = SP.getVariables();
897 if (Variables.getNumElements() == 0)
900 // Construct subprogram DIE and add variables DIEs.
901 DwarfCompileUnit *SPCU =
902 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
903 assert(SPCU && "Unable to find Compile Unit!");
904 // FIXME: See the comment in constructSubprogramDIE about duplicate
906 constructSubprogramDIE(SPCU, SP);
907 DIE *SPDIE = SPCU->getDIE(SP);
908 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
909 DIVariable DV(Variables.getElement(vi));
910 if (!DV.isVariable())
912 DbgVariable NewVar(DV, NULL, this);
913 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
914 SPDIE->addChild(VariableDIE);
921 void DwarfDebug::finalizeModuleInfo() {
922 // Collect info for variables that were optimized out.
923 collectDeadVariables();
925 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
926 computeInlinedDIEs();
928 // Handle anything that needs to be done on a per-unit basis after
929 // all other generation.
930 for (DwarfUnit *TheU : getUnits()) {
931 // Emit DW_AT_containing_type attribute to connect types with their
932 // vtable holding type.
933 TheU->constructContainingTypeDIEs();
935 // Add CU specific attributes if we need to add any.
936 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
937 // If we're splitting the dwarf out now that we've got the entire
938 // CU then add the dwo id to it.
939 DwarfCompileUnit *SkCU =
940 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
941 if (useSplitDwarf()) {
942 // Emit a unique identifier for this CU.
943 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
944 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
945 dwarf::DW_FORM_data8, ID);
946 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
947 dwarf::DW_FORM_data8, ID);
949 // We don't keep track of which addresses are used in which CU so this
950 // is a bit pessimistic under LTO.
951 if (!InfoHolder.getAddrPool()->empty())
952 addSectionLabel(Asm, SkCU, SkCU->getUnitDie(),
953 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
954 DwarfAddrSectionSym);
955 if (!TheU->getRangeLists().empty())
956 addSectionLabel(Asm, SkCU, SkCU->getUnitDie(),
957 dwarf::DW_AT_GNU_ranges_base,
958 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
961 // If we have code split among multiple sections or non-contiguous
962 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
963 // remain in the .o file, otherwise add a DW_AT_low_pc.
964 // FIXME: We should use ranges allow reordering of code ala
965 // .subsections_via_symbols in mach-o. This would mean turning on
966 // ranges for all subprogram DIEs for mach-o.
967 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
968 unsigned NumRanges = TheU->getRanges().size();
971 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
972 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
973 DwarfDebugRangeSectionSym);
975 // A DW_AT_low_pc attribute may also be specified in combination with
976 // DW_AT_ranges to specify the default base address for use in
977 // location lists (see Section 2.6.2) and range lists (see Section
979 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
982 RangeSpan &Range = TheU->getRanges().back();
983 U->addLocalLabelAddress(U->getUnitDie(), dwarf::DW_AT_low_pc,
985 U->addLabelDelta(U->getUnitDie(), dwarf::DW_AT_high_pc,
986 Range.getEnd(), Range.getStart());
992 // Compute DIE offsets and sizes.
993 InfoHolder.computeSizeAndOffsets();
995 SkeletonHolder.computeSizeAndOffsets();
998 void DwarfDebug::endSections() {
999 // Filter labels by section.
1000 for (const SymbolCU &SCU : ArangeLabels) {
1001 if (SCU.Sym->isInSection()) {
1002 // Make a note of this symbol and it's section.
1003 const MCSection *Section = &SCU.Sym->getSection();
1004 if (!Section->getKind().isMetadata())
1005 SectionMap[Section].push_back(SCU);
1007 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1008 // appear in the output. This sucks as we rely on sections to build
1009 // arange spans. We can do it without, but it's icky.
1010 SectionMap[NULL].push_back(SCU);
1014 // Build a list of sections used.
1015 std::vector<const MCSection *> Sections;
1016 for (const auto &it : SectionMap) {
1017 const MCSection *Section = it.first;
1018 Sections.push_back(Section);
1021 // Sort the sections into order.
1022 // This is only done to ensure consistent output order across different runs.
1023 std::sort(Sections.begin(), Sections.end(), SectionSort);
1025 // Add terminating symbols for each section.
1026 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1027 const MCSection *Section = Sections[ID];
1028 MCSymbol *Sym = NULL;
1031 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1032 // if we know the section name up-front. For user-created sections, the
1033 // resulting label may not be valid to use as a label. (section names can
1034 // use a greater set of characters on some systems)
1035 Sym = Asm->GetTempSymbol("debug_end", ID);
1036 Asm->OutStreamer.SwitchSection(Section);
1037 Asm->OutStreamer.EmitLabel(Sym);
1040 // Insert a final terminator.
1041 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1045 // Emit all Dwarf sections that should come after the content.
1046 void DwarfDebug::endModule() {
1053 // End any existing sections.
1054 // TODO: Does this need to happen?
1057 // Finalize the debug info for the module.
1058 finalizeModuleInfo();
1062 // Emit all the DIEs into a debug info section.
1065 // Corresponding abbreviations into a abbrev section.
1066 emitAbbreviations();
1068 // Emit info into a debug aranges section.
1069 if (GenerateARangeSection)
1072 // Emit info into a debug ranges section.
1075 if (useSplitDwarf()) {
1078 emitDebugAbbrevDWO();
1080 // Emit DWO addresses.
1081 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1084 // Emit info into a debug loc section.
1087 // Emit info into the dwarf accelerator table sections.
1088 if (useDwarfAccelTables()) {
1091 emitAccelNamespaces();
1095 // Emit the pubnames and pubtypes sections if requested.
1096 if (HasDwarfPubSections) {
1097 emitDebugPubNames(GenerateGnuPubSections);
1098 emitDebugPubTypes(GenerateGnuPubSections);
1104 // Reset these for the next Module if we have one.
1108 // Find abstract variable, if any, associated with Var.
1109 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1110 DebugLoc ScopeLoc) {
1111 LLVMContext &Ctx = DV->getContext();
1112 // More then one inlined variable corresponds to one abstract variable.
1113 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1114 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1116 return AbsDbgVariable;
1118 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1122 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1123 addScopeVariable(Scope, AbsDbgVariable);
1124 AbstractVariables[Var] = AbsDbgVariable;
1125 return AbsDbgVariable;
1128 // If Var is a current function argument then add it to CurrentFnArguments list.
1129 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1130 if (!LScopes.isCurrentFunctionScope(Scope))
1132 DIVariable DV = Var->getVariable();
1133 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1135 unsigned ArgNo = DV.getArgNumber();
1139 size_t Size = CurrentFnArguments.size();
1141 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1142 // llvm::Function argument size is not good indicator of how many
1143 // arguments does the function have at source level.
1145 CurrentFnArguments.resize(ArgNo * 2);
1146 CurrentFnArguments[ArgNo - 1] = Var;
1150 // Collect variable information from side table maintained by MMI.
1151 void DwarfDebug::collectVariableInfoFromMMITable(
1152 SmallPtrSet<const MDNode *, 16> &Processed) {
1153 for (const auto &VI : MMI->getVariableDbgInfo()) {
1156 Processed.insert(VI.Var);
1157 DIVariable DV(VI.Var);
1158 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1160 // If variable scope is not found then skip this variable.
1164 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1165 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1166 RegVar->setFrameIndex(VI.Slot);
1167 if (!addCurrentFnArgument(RegVar, Scope))
1168 addScopeVariable(Scope, RegVar);
1170 AbsDbgVariable->setFrameIndex(VI.Slot);
1174 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1176 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1177 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1178 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1179 MI->getOperand(0).getReg() &&
1180 (MI->getOperand(1).isImm() ||
1181 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1184 // Get .debug_loc entry for the instruction range starting at MI.
1185 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1186 const MCSymbol *FLabel,
1187 const MCSymbol *SLabel,
1188 const MachineInstr *MI,
1189 DwarfCompileUnit *Unit) {
1190 const MDNode *Var = MI->getDebugVariable();
1192 assert(MI->getNumOperands() == 3);
1193 if (MI->getOperand(0).isReg()) {
1194 MachineLocation MLoc;
1195 // If the second operand is an immediate, this is a
1196 // register-indirect address.
1197 if (!MI->getOperand(1).isImm())
1198 MLoc.set(MI->getOperand(0).getReg());
1200 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1201 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1203 if (MI->getOperand(0).isImm())
1204 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1205 if (MI->getOperand(0).isFPImm())
1206 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1208 if (MI->getOperand(0).isCImm())
1209 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1212 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1215 // Find variables for each lexical scope.
1217 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1219 // Grab the variable info that was squirreled away in the MMI side-table.
1220 collectVariableInfoFromMMITable(Processed);
1222 for (const MDNode *Var : UserVariables) {
1223 if (Processed.count(Var))
1226 // History contains relevant DBG_VALUE instructions for Var and instructions
1228 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1229 if (History.empty())
1231 const MachineInstr *MInsn = History.front();
1234 LexicalScope *Scope = NULL;
1235 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1236 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1237 Scope = LScopes.getCurrentFunctionScope();
1238 else if (MDNode *IA = DV.getInlinedAt())
1239 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1241 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1242 // If variable scope is not found then skip this variable.
1246 Processed.insert(DV);
1247 assert(MInsn->isDebugValue() && "History must begin with debug value");
1248 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1249 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1250 if (!addCurrentFnArgument(RegVar, Scope))
1251 addScopeVariable(Scope, RegVar);
1253 AbsVar->setMInsn(MInsn);
1255 // Simplify ranges that are fully coalesced.
1256 if (History.size() <= 1 ||
1257 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1258 RegVar->setMInsn(MInsn);
1262 // Handle multiple DBG_VALUE instructions describing one variable.
1263 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1265 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1266 DebugLocList &LocList = DotDebugLocEntries.back();
1268 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1269 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1270 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1271 HI = History.begin(),
1274 const MachineInstr *Begin = *HI;
1275 assert(Begin->isDebugValue() && "Invalid History entry");
1277 // Check if DBG_VALUE is truncating a range.
1278 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1279 !Begin->getOperand(0).getReg())
1282 // Compute the range for a register location.
1283 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1284 const MCSymbol *SLabel = 0;
1287 // If Begin is the last instruction in History then its value is valid
1288 // until the end of the function.
1289 SLabel = FunctionEndSym;
1291 const MachineInstr *End = HI[1];
1292 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1293 << "\t" << *Begin << "\t" << *End << "\n");
1294 if (End->isDebugValue())
1295 SLabel = getLabelBeforeInsn(End);
1297 // End is a normal instruction clobbering the range.
1298 SLabel = getLabelAfterInsn(End);
1299 assert(SLabel && "Forgot label after clobber instruction");
1304 // The value is valid until the next DBG_VALUE or clobber.
1305 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1306 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1307 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1308 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1309 DebugLoc.push_back(std::move(Loc));
1313 // Collect info for variables that were optimized out.
1314 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1315 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1316 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1317 DIVariable DV(Variables.getElement(i));
1318 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1320 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1321 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1325 // Return Label preceding the instruction.
1326 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1327 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1328 assert(Label && "Didn't insert label before instruction");
1332 // Return Label immediately following the instruction.
1333 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1334 return LabelsAfterInsn.lookup(MI);
1337 // Process beginning of an instruction.
1338 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1341 // Check if source location changes, but ignore DBG_VALUE locations.
1342 if (!MI->isDebugValue()) {
1343 DebugLoc DL = MI->getDebugLoc();
1344 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1347 if (DL == PrologEndLoc) {
1348 Flags |= DWARF2_FLAG_PROLOGUE_END;
1349 PrologEndLoc = DebugLoc();
1351 if (PrologEndLoc.isUnknown())
1352 Flags |= DWARF2_FLAG_IS_STMT;
1354 if (!DL.isUnknown()) {
1355 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1356 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1358 recordSourceLine(0, 0, 0, 0);
1362 // Insert labels where requested.
1363 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1364 LabelsBeforeInsn.find(MI);
1367 if (I == LabelsBeforeInsn.end())
1370 // Label already assigned.
1375 PrevLabel = MMI->getContext().CreateTempSymbol();
1376 Asm->OutStreamer.EmitLabel(PrevLabel);
1378 I->second = PrevLabel;
1381 // Process end of an instruction.
1382 void DwarfDebug::endInstruction() {
1384 // Don't create a new label after DBG_VALUE instructions.
1385 // They don't generate code.
1386 if (!CurMI->isDebugValue())
1389 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1390 LabelsAfterInsn.find(CurMI);
1394 if (I == LabelsAfterInsn.end())
1397 // Label already assigned.
1401 // We need a label after this instruction.
1403 PrevLabel = MMI->getContext().CreateTempSymbol();
1404 Asm->OutStreamer.EmitLabel(PrevLabel);
1406 I->second = PrevLabel;
1409 // Each LexicalScope has first instruction and last instruction to mark
1410 // beginning and end of a scope respectively. Create an inverse map that list
1411 // scopes starts (and ends) with an instruction. One instruction may start (or
1412 // end) multiple scopes. Ignore scopes that are not reachable.
1413 void DwarfDebug::identifyScopeMarkers() {
1414 SmallVector<LexicalScope *, 4> WorkList;
1415 WorkList.push_back(LScopes.getCurrentFunctionScope());
1416 while (!WorkList.empty()) {
1417 LexicalScope *S = WorkList.pop_back_val();
1419 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1420 if (!Children.empty())
1421 WorkList.append(Children.begin(), Children.end());
1423 if (S->isAbstractScope())
1426 for (const InsnRange &R : S->getRanges()) {
1427 assert(R.first && "InsnRange does not have first instruction!");
1428 assert(R.second && "InsnRange does not have second instruction!");
1429 requestLabelBeforeInsn(R.first);
1430 requestLabelAfterInsn(R.second);
1435 // Gather pre-function debug information. Assumes being called immediately
1436 // after the function entry point has been emitted.
1437 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1440 // If there's no debug info for the function we're not going to do anything.
1441 if (!MMI->hasDebugInfo())
1444 // Grab the lexical scopes for the function, if we don't have any of those
1445 // then we're not going to be able to do anything.
1446 LScopes.initialize(*MF);
1447 if (LScopes.empty())
1450 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1452 // Make sure that each lexical scope will have a begin/end label.
1453 identifyScopeMarkers();
1455 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1456 // belongs to so that we add to the correct per-cu line table in the
1458 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1459 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1460 assert(TheCU && "Unable to find compile unit!");
1461 if (Asm->OutStreamer.hasRawTextSupport())
1462 // Use a single line table if we are generating assembly.
1463 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1465 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1467 // Emit a label for the function so that we have a beginning address.
1468 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1469 // Assumes in correct section after the entry point.
1470 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1472 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1473 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1474 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1476 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1478 bool AtBlockEntry = true;
1479 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1481 const MachineInstr *MI = II;
1483 if (MI->isDebugValue()) {
1484 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1486 // Keep track of user variables.
1487 const MDNode *Var = MI->getDebugVariable();
1489 // Variable is in a register, we need to check for clobbers.
1490 if (isDbgValueInDefinedReg(MI))
1491 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1493 // Check the history of this variable.
1494 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1495 if (History.empty()) {
1496 UserVariables.push_back(Var);
1497 // The first mention of a function argument gets the FunctionBeginSym
1498 // label, so arguments are visible when breaking at function entry.
1500 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1501 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1502 LabelsBeforeInsn[MI] = FunctionBeginSym;
1504 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1505 const MachineInstr *Prev = History.back();
1506 if (Prev->isDebugValue()) {
1507 // Coalesce identical entries at the end of History.
1508 if (History.size() >= 2 &&
1509 Prev->isIdenticalTo(History[History.size() - 2])) {
1510 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1511 << "\t" << *Prev << "\t"
1512 << *History[History.size() - 2] << "\n");
1516 // Terminate old register assignments that don't reach MI;
1517 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1518 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1519 isDbgValueInDefinedReg(Prev)) {
1520 // Previous register assignment needs to terminate at the end of
1522 MachineBasicBlock::const_iterator LastMI =
1523 PrevMBB->getLastNonDebugInstr();
1524 if (LastMI == PrevMBB->end()) {
1525 // Drop DBG_VALUE for empty range.
1526 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1527 << "\t" << *Prev << "\n");
1529 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1530 // Terminate after LastMI.
1531 History.push_back(LastMI);
1535 History.push_back(MI);
1537 // Not a DBG_VALUE instruction.
1538 if (!MI->isPosition())
1539 AtBlockEntry = false;
1541 // First known non-DBG_VALUE and non-frame setup location marks
1542 // the beginning of the function body.
1543 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1544 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1545 PrologEndLoc = MI->getDebugLoc();
1547 // Check if the instruction clobbers any registers with debug vars.
1548 for (const MachineOperand &MO : MI->operands()) {
1549 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1551 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1554 const MDNode *Var = LiveUserVar[Reg];
1557 // Reg is now clobbered.
1558 LiveUserVar[Reg] = 0;
1560 // Was MD last defined by a DBG_VALUE referring to Reg?
1561 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1562 if (HistI == DbgValues.end())
1564 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1565 if (History.empty())
1567 const MachineInstr *Prev = History.back();
1568 // Sanity-check: Register assignments are terminated at the end of
1570 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1572 // Is the variable still in Reg?
1573 if (!isDbgValueInDefinedReg(Prev) ||
1574 Prev->getOperand(0).getReg() != Reg)
1576 // Var is clobbered. Make sure the next instruction gets a label.
1577 History.push_back(MI);
1584 for (auto &I : DbgValues) {
1585 SmallVectorImpl<const MachineInstr *> &History = I.second;
1586 if (History.empty())
1589 // Make sure the final register assignments are terminated.
1590 const MachineInstr *Prev = History.back();
1591 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1592 const MachineBasicBlock *PrevMBB = Prev->getParent();
1593 MachineBasicBlock::const_iterator LastMI =
1594 PrevMBB->getLastNonDebugInstr();
1595 if (LastMI == PrevMBB->end())
1596 // Drop DBG_VALUE for empty range.
1598 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1599 // Terminate after LastMI.
1600 History.push_back(LastMI);
1603 // Request labels for the full history.
1604 for (const MachineInstr *MI : History) {
1605 if (MI->isDebugValue())
1606 requestLabelBeforeInsn(MI);
1608 requestLabelAfterInsn(MI);
1612 PrevInstLoc = DebugLoc();
1613 PrevLabel = FunctionBeginSym;
1615 // Record beginning of function.
1616 if (!PrologEndLoc.isUnknown()) {
1617 DebugLoc FnStartDL =
1618 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1620 FnStartDL.getLine(), FnStartDL.getCol(),
1621 FnStartDL.getScope(MF->getFunction()->getContext()),
1622 // We'd like to list the prologue as "not statements" but GDB behaves
1623 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1624 DWARF2_FLAG_IS_STMT);
1628 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
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);
1670 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1671 // If we don't have a lexical scope for this function then there will
1672 // be a hole in the range information. Keep note of this by setting the
1673 // previously used section to nullptr.
1674 PrevSection = 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());
1693 assert(TheCU && "Unable to find compile unit!");
1695 // Construct abstract scopes.
1696 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1697 DISubprogram SP(AScope->getScopeNode());
1698 if (SP.isSubprogram()) {
1699 // Collect info for variables that were optimized out.
1700 DIArray Variables = SP.getVariables();
1701 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1702 DIVariable DV(Variables.getElement(i));
1703 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1705 // Check that DbgVariable for DV wasn't created earlier, when
1706 // findAbstractVariable() was called for inlined instance of DV.
1707 LLVMContext &Ctx = DV->getContext();
1708 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1709 if (AbstractVariables.lookup(CleanDV))
1711 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1712 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1715 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1716 constructScopeDIE(TheCU, AScope);
1719 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1720 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1721 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1723 // Add the range of this function to the list of ranges for the CU.
1724 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1725 TheCU->addRange(std::move(Span));
1726 PrevSection = Asm->getCurrentSection();
1730 for (auto &I : ScopeVariables)
1731 DeleteContainerPointers(I.second);
1732 ScopeVariables.clear();
1733 DeleteContainerPointers(CurrentFnArguments);
1734 UserVariables.clear();
1736 AbstractVariables.clear();
1737 LabelsBeforeInsn.clear();
1738 LabelsAfterInsn.clear();
1743 // Register a source line with debug info. Returns the unique label that was
1744 // emitted and which provides correspondence to the source line list.
1745 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1750 unsigned Discriminator = 0;
1752 DIDescriptor Scope(S);
1754 if (Scope.isCompileUnit()) {
1755 DICompileUnit CU(S);
1756 Fn = CU.getFilename();
1757 Dir = CU.getDirectory();
1758 } else if (Scope.isFile()) {
1760 Fn = F.getFilename();
1761 Dir = F.getDirectory();
1762 } else if (Scope.isSubprogram()) {
1764 Fn = SP.getFilename();
1765 Dir = SP.getDirectory();
1766 } else if (Scope.isLexicalBlockFile()) {
1767 DILexicalBlockFile DBF(S);
1768 Fn = DBF.getFilename();
1769 Dir = DBF.getDirectory();
1770 } else if (Scope.isLexicalBlock()) {
1771 DILexicalBlock DB(S);
1772 Fn = DB.getFilename();
1773 Dir = DB.getDirectory();
1774 Discriminator = DB.getDiscriminator();
1776 llvm_unreachable("Unexpected scope info");
1778 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1779 Src = static_cast<DwarfCompileUnit *>(InfoHolder.getUnits()[CUID])
1780 ->getOrCreateSourceID(Fn, Dir);
1782 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1786 //===----------------------------------------------------------------------===//
1788 //===----------------------------------------------------------------------===//
1790 // Compute the size and offset of a DIE. The offset is relative to start of the
1791 // CU. It returns the offset after laying out the DIE.
1792 unsigned DwarfFile::computeSizeAndOffset(DIE &Die, unsigned Offset) {
1793 // Record the abbreviation.
1794 assignAbbrevNumber(Die.getAbbrev());
1796 // Get the abbreviation for this DIE.
1797 const DIEAbbrev &Abbrev = Die.getAbbrev();
1800 Die.setOffset(Offset);
1802 // Start the size with the size of abbreviation code.
1803 Offset += getULEB128Size(Die.getAbbrevNumber());
1805 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1806 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1808 // Size the DIE attribute values.
1809 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1810 // Size attribute value.
1811 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1813 // Get the children.
1814 const auto &Children = Die.getChildren();
1816 // Size the DIE children if any.
1817 if (!Children.empty()) {
1818 assert(Abbrev.hasChildren() && "Children flag not set");
1820 for (auto &Child : Children)
1821 Offset = computeSizeAndOffset(*Child, Offset);
1823 // End of children marker.
1824 Offset += sizeof(int8_t);
1827 Die.setSize(Offset - Die.getOffset());
1831 // Compute the size and offset for each DIE.
1832 void DwarfFile::computeSizeAndOffsets() {
1833 // Offset from the first CU in the debug info section is 0 initially.
1834 unsigned SecOffset = 0;
1836 // Iterate over each compile unit and set the size and offsets for each
1837 // DIE within each compile unit. All offsets are CU relative.
1838 for (DwarfUnit *TheU : CUs) {
1839 TheU->setDebugInfoOffset(SecOffset);
1841 // CU-relative offset is reset to 0 here.
1842 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1843 TheU->getHeaderSize(); // Unit-specific headers
1845 // EndOffset here is CU-relative, after laying out
1846 // all of the CU DIE.
1847 unsigned EndOffset = computeSizeAndOffset(*TheU->getUnitDie(), Offset);
1848 SecOffset += EndOffset;
1852 // Emit initial Dwarf sections with a label at the start of each one.
1853 void DwarfDebug::emitSectionLabels() {
1854 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1856 // Dwarf sections base addresses.
1857 DwarfInfoSectionSym =
1858 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1859 if (useSplitDwarf())
1860 DwarfInfoDWOSectionSym =
1861 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1862 DwarfAbbrevSectionSym =
1863 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1864 if (useSplitDwarf())
1865 DwarfAbbrevDWOSectionSym = emitSectionSym(
1866 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1867 if (GenerateARangeSection)
1868 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1870 DwarfLineSectionSym =
1871 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1872 if (GenerateGnuPubSections) {
1873 DwarfGnuPubNamesSectionSym =
1874 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1875 DwarfGnuPubTypesSectionSym =
1876 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1877 } else if (HasDwarfPubSections) {
1878 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1879 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1882 DwarfStrSectionSym =
1883 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1884 if (useSplitDwarf()) {
1885 DwarfStrDWOSectionSym =
1886 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1887 DwarfAddrSectionSym =
1888 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1889 DwarfDebugLocSectionSym =
1890 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1892 DwarfDebugLocSectionSym =
1893 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1894 DwarfDebugRangeSectionSym =
1895 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1898 // Recursively emits a debug information entry.
1899 void DwarfDebug::emitDIE(DIE &Die) {
1900 // Get the abbreviation for this DIE.
1901 const DIEAbbrev &Abbrev = Die.getAbbrev();
1903 // Emit the code (index) for the abbreviation.
1904 if (Asm->isVerbose())
1905 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1906 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1907 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1908 dwarf::TagString(Abbrev.getTag()));
1909 Asm->EmitULEB128(Abbrev.getNumber());
1911 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1912 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1914 // Emit the DIE attribute values.
1915 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1916 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1917 dwarf::Form Form = AbbrevData[i].getForm();
1918 assert(Form && "Too many attributes for DIE (check abbreviation)");
1920 if (Asm->isVerbose()) {
1921 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1922 if (Attr == dwarf::DW_AT_accessibility)
1923 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1924 cast<DIEInteger>(Values[i])->getValue()));
1927 // Emit an attribute using the defined form.
1928 Values[i]->EmitValue(Asm, Form);
1931 // Emit the DIE children if any.
1932 if (Abbrev.hasChildren()) {
1933 for (auto &Child : Die.getChildren())
1936 Asm->OutStreamer.AddComment("End Of Children Mark");
1941 // Emit the various dwarf units to the unit section USection with
1942 // the abbreviations going into ASection.
1943 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSymbol *ASectionSym) {
1944 for (DwarfUnit *TheU : CUs) {
1945 DIE *Die = TheU->getUnitDie();
1946 const MCSection *USection = TheU->getSection();
1947 Asm->OutStreamer.SwitchSection(USection);
1949 // Emit the compile units header.
1950 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1952 // Emit size of content not including length itself
1953 Asm->OutStreamer.AddComment("Length of Unit");
1954 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1956 TheU->emitHeader(ASectionSym);
1959 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1963 // Emit the debug info section.
1964 void DwarfDebug::emitDebugInfo() {
1965 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1967 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1970 // Emit the abbreviation section.
1971 void DwarfDebug::emitAbbreviations() {
1972 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1974 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1977 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1978 // Check to see if it is worth the effort.
1979 if (!Abbreviations.empty()) {
1980 // Start the debug abbrev section.
1981 Asm->OutStreamer.SwitchSection(Section);
1983 // For each abbrevation.
1984 for (const DIEAbbrev *Abbrev : Abbreviations) {
1985 // Emit the abbrevations code (base 1 index.)
1986 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1988 // Emit the abbreviations data.
1992 // Mark end of abbreviations.
1993 Asm->EmitULEB128(0, "EOM(3)");
1997 // Emit the last address of the section and the end of the line matrix.
1998 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1999 // Define last address of section.
2000 Asm->OutStreamer.AddComment("Extended Op");
2003 Asm->OutStreamer.AddComment("Op size");
2004 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2005 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2006 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2008 Asm->OutStreamer.AddComment("Section end label");
2010 Asm->OutStreamer.EmitSymbolValue(
2011 Asm->GetTempSymbol("section_end", SectionEnd),
2012 Asm->getDataLayout().getPointerSize());
2014 // Mark end of matrix.
2015 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2021 // Emit visible names into a hashed accelerator table section.
2022 void DwarfDebug::emitAccelNames() {
2024 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2025 for (DwarfUnit *TheU : getUnits()) {
2026 for (const auto &GI : TheU->getAccelNames()) {
2027 StringRef Name = GI.getKey();
2028 for (const DIE *D : GI.second)
2029 AT.AddName(Name, D);
2033 AT.FinalizeTable(Asm, "Names");
2034 Asm->OutStreamer.SwitchSection(
2035 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2036 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2037 Asm->OutStreamer.EmitLabel(SectionBegin);
2039 // Emit the full data.
2040 AT.Emit(Asm, SectionBegin, &InfoHolder);
2043 // Emit objective C classes and categories into a hashed accelerator table
2045 void DwarfDebug::emitAccelObjC() {
2047 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2048 for (DwarfUnit *TheU : getUnits()) {
2049 for (const auto &GI : TheU->getAccelObjC()) {
2050 StringRef Name = GI.getKey();
2051 for (const DIE *D : GI.second)
2052 AT.AddName(Name, D);
2056 AT.FinalizeTable(Asm, "ObjC");
2057 Asm->OutStreamer.SwitchSection(
2058 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2059 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2060 Asm->OutStreamer.EmitLabel(SectionBegin);
2062 // Emit the full data.
2063 AT.Emit(Asm, SectionBegin, &InfoHolder);
2066 // Emit namespace dies into a hashed accelerator table.
2067 void DwarfDebug::emitAccelNamespaces() {
2069 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2070 for (DwarfUnit *TheU : getUnits()) {
2071 for (const auto &GI : TheU->getAccelNamespace()) {
2072 StringRef Name = GI.getKey();
2073 for (const DIE *D : GI.second)
2074 AT.AddName(Name, D);
2078 AT.FinalizeTable(Asm, "namespac");
2079 Asm->OutStreamer.SwitchSection(
2080 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2081 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2082 Asm->OutStreamer.EmitLabel(SectionBegin);
2084 // Emit the full data.
2085 AT.Emit(Asm, SectionBegin, &InfoHolder);
2088 // Emit type dies into a hashed accelerator table.
2089 void DwarfDebug::emitAccelTypes() {
2090 std::vector<DwarfAccelTable::Atom> Atoms;
2092 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2094 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2096 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2097 DwarfAccelTable AT(Atoms);
2098 for (DwarfUnit *TheU : getUnits()) {
2099 for (const auto &GI : TheU->getAccelTypes()) {
2100 StringRef Name = GI.getKey();
2101 for (const auto &DI : GI.second)
2102 AT.AddName(Name, DI.first, DI.second);
2106 AT.FinalizeTable(Asm, "types");
2107 Asm->OutStreamer.SwitchSection(
2108 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2109 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2110 Asm->OutStreamer.EmitLabel(SectionBegin);
2112 // Emit the full data.
2113 AT.Emit(Asm, SectionBegin, &InfoHolder);
2116 // Public name handling.
2117 // The format for the various pubnames:
2119 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2120 // for the DIE that is named.
2122 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2123 // into the CU and the index value is computed according to the type of value
2124 // for the DIE that is named.
2126 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2127 // it's the offset within the debug_info/debug_types dwo section, however, the
2128 // reference in the pubname header doesn't change.
2130 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2131 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2133 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2135 // We could have a specification DIE that has our most of our knowledge,
2136 // look for that now.
2137 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2139 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2140 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2141 Linkage = dwarf::GIEL_EXTERNAL;
2142 } else if (Die->findAttribute(dwarf::DW_AT_external))
2143 Linkage = dwarf::GIEL_EXTERNAL;
2145 switch (Die->getTag()) {
2146 case dwarf::DW_TAG_class_type:
2147 case dwarf::DW_TAG_structure_type:
2148 case dwarf::DW_TAG_union_type:
2149 case dwarf::DW_TAG_enumeration_type:
2150 return dwarf::PubIndexEntryDescriptor(
2151 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2152 ? dwarf::GIEL_STATIC
2153 : dwarf::GIEL_EXTERNAL);
2154 case dwarf::DW_TAG_typedef:
2155 case dwarf::DW_TAG_base_type:
2156 case dwarf::DW_TAG_subrange_type:
2157 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2158 case dwarf::DW_TAG_namespace:
2159 return dwarf::GIEK_TYPE;
2160 case dwarf::DW_TAG_subprogram:
2161 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2162 case dwarf::DW_TAG_constant:
2163 case dwarf::DW_TAG_variable:
2164 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2165 case dwarf::DW_TAG_enumerator:
2166 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2167 dwarf::GIEL_STATIC);
2169 return dwarf::GIEK_NONE;
2173 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2175 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2176 const MCSection *PSec =
2177 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2178 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2180 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2183 void DwarfDebug::emitDebugPubSection(
2184 bool GnuStyle, const MCSection *PSec, StringRef Name,
2185 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2186 for (const auto &NU : CUMap) {
2187 DwarfCompileUnit *TheU = NU.second;
2189 const auto &Globals = (TheU->*Accessor)();
2191 if (Globals.empty())
2194 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2196 unsigned ID = TheU->getUniqueID();
2198 // Start the dwarf pubnames section.
2199 Asm->OutStreamer.SwitchSection(PSec);
2202 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2203 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2204 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2205 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2207 Asm->OutStreamer.EmitLabel(BeginLabel);
2209 Asm->OutStreamer.AddComment("DWARF Version");
2210 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2212 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2213 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2215 Asm->OutStreamer.AddComment("Compilation Unit Length");
2216 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2218 // Emit the pubnames for this compilation unit.
2219 for (const auto &GI : Globals) {
2220 const char *Name = GI.getKeyData();
2221 const DIE *Entity = GI.second;
2223 Asm->OutStreamer.AddComment("DIE offset");
2224 Asm->EmitInt32(Entity->getOffset());
2227 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2228 Asm->OutStreamer.AddComment(
2229 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2230 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2231 Asm->EmitInt8(Desc.toBits());
2234 Asm->OutStreamer.AddComment("External Name");
2235 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2238 Asm->OutStreamer.AddComment("End Mark");
2240 Asm->OutStreamer.EmitLabel(EndLabel);
2244 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2245 const MCSection *PSec =
2246 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2247 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2249 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2252 // Emit strings into a string section.
2253 void DwarfFile::emitStrings(const MCSection *StrSection,
2254 const MCSection *OffsetSection = NULL,
2255 const MCSymbol *StrSecSym = NULL) {
2257 if (StringPool.empty())
2260 // Start the dwarf str section.
2261 Asm->OutStreamer.SwitchSection(StrSection);
2263 // Get all of the string pool entries and put them in an array by their ID so
2264 // we can sort them.
2265 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2267 for (const auto &I : StringPool)
2268 Entries.push_back(std::make_pair(I.second.second, &I));
2270 array_pod_sort(Entries.begin(), Entries.end());
2272 for (const auto &Entry : Entries) {
2273 // Emit a label for reference from debug information entries.
2274 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2276 // Emit the string itself with a terminating null byte.
2277 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2278 Entry.second->getKeyLength() + 1));
2281 // If we've got an offset section go ahead and emit that now as well.
2282 if (OffsetSection) {
2283 Asm->OutStreamer.SwitchSection(OffsetSection);
2284 unsigned offset = 0;
2285 unsigned size = 4; // FIXME: DWARF64 is 8.
2286 for (const auto &Entry : Entries) {
2287 Asm->OutStreamer.EmitIntValue(offset, size);
2288 offset += Entry.second->getKeyLength() + 1;
2293 // Emit addresses into the section given.
2294 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2296 if (AddressPool.empty())
2299 // Start the dwarf addr section.
2300 Asm->OutStreamer.SwitchSection(AddrSection);
2302 // Order the address pool entries by ID
2303 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2305 for (const auto &I : AddressPool)
2306 Entries[I.second.Number] =
2308 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2309 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2311 for (const MCExpr *Entry : Entries)
2312 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2315 // Emit visible names into a debug str section.
2316 void DwarfDebug::emitDebugStr() {
2317 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2318 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2321 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2322 const DebugLocEntry &Entry) {
2323 DIVariable DV(Entry.getVariable());
2324 if (Entry.isInt()) {
2325 DIBasicType BTy(resolve(DV.getType()));
2326 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2327 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2328 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2329 Streamer.EmitSLEB128(Entry.getInt());
2331 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2332 Streamer.EmitULEB128(Entry.getInt());
2334 } else if (Entry.isLocation()) {
2335 MachineLocation Loc = Entry.getLoc();
2336 if (!DV.hasComplexAddress())
2338 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2340 // Complex address entry.
2341 unsigned N = DV.getNumAddrElements();
2343 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2344 if (Loc.getOffset()) {
2346 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2347 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2348 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2349 Streamer.EmitSLEB128(DV.getAddrElement(1));
2351 // If first address element is OpPlus then emit
2352 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2353 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2354 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2358 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2361 // Emit remaining complex address elements.
2362 for (; i < N; ++i) {
2363 uint64_t Element = DV.getAddrElement(i);
2364 if (Element == DIBuilder::OpPlus) {
2365 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2366 Streamer.EmitULEB128(DV.getAddrElement(++i));
2367 } else if (Element == DIBuilder::OpDeref) {
2369 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2371 llvm_unreachable("unknown Opcode found in complex address");
2375 // else ... ignore constant fp. There is not any good way to
2376 // to represent them here in dwarf.
2380 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2381 Asm->OutStreamer.AddComment("Loc expr size");
2382 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2383 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2384 Asm->EmitLabelDifference(end, begin, 2);
2385 Asm->OutStreamer.EmitLabel(begin);
2387 APByteStreamer Streamer(*Asm);
2388 emitDebugLocEntry(Streamer, Entry);
2390 Asm->OutStreamer.EmitLabel(end);
2393 // Emit locations into the debug loc section.
2394 void DwarfDebug::emitDebugLoc() {
2395 // Start the dwarf loc section.
2396 Asm->OutStreamer.SwitchSection(
2397 Asm->getObjFileLowering().getDwarfLocSection());
2398 unsigned char Size = Asm->getDataLayout().getPointerSize();
2399 for (const auto &DebugLoc : DotDebugLocEntries) {
2400 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2401 for (const auto &Entry : DebugLoc.List) {
2402 // Set up the range. This range is relative to the entry point of the
2403 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2404 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2405 const DwarfCompileUnit *CU = Entry.getCU();
2406 if (CU->getRanges().size() == 1) {
2407 // Grab the begin symbol from the first range as our base.
2408 const MCSymbol *Base = CU->getRanges()[0].getStart();
2409 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2410 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2412 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2413 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2416 emitDebugLocEntryLocation(Entry);
2418 Asm->OutStreamer.EmitIntValue(0, Size);
2419 Asm->OutStreamer.EmitIntValue(0, Size);
2423 void DwarfDebug::emitDebugLocDWO() {
2424 Asm->OutStreamer.SwitchSection(
2425 Asm->getObjFileLowering().getDwarfLocDWOSection());
2426 for (const auto &DebugLoc : DotDebugLocEntries) {
2427 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2428 for (const auto &Entry : DebugLoc.List) {
2429 // Just always use start_length for now - at least that's one address
2430 // rather than two. We could get fancier and try to, say, reuse an
2431 // address we know we've emitted elsewhere (the start of the function?
2432 // The start of the CU or CU subrange that encloses this range?)
2433 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2434 unsigned idx = InfoHolder.getAddrPoolIndex(Entry.getBeginSym());
2435 Asm->EmitULEB128(idx);
2436 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2438 emitDebugLocEntryLocation(Entry);
2440 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2445 const MCSymbol *Start, *End;
2448 // Emit a debug aranges section, containing a CU lookup for any
2449 // address we can tie back to a CU.
2450 void DwarfDebug::emitDebugARanges() {
2451 // Start the dwarf aranges section.
2452 Asm->OutStreamer.SwitchSection(
2453 Asm->getObjFileLowering().getDwarfARangesSection());
2455 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2459 // Build a list of sections used.
2460 std::vector<const MCSection *> Sections;
2461 for (const auto &it : SectionMap) {
2462 const MCSection *Section = it.first;
2463 Sections.push_back(Section);
2466 // Sort the sections into order.
2467 // This is only done to ensure consistent output order across different runs.
2468 std::sort(Sections.begin(), Sections.end(), SectionSort);
2470 // Build a set of address spans, sorted by CU.
2471 for (const MCSection *Section : Sections) {
2472 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2473 if (List.size() < 2)
2476 // Sort the symbols by offset within the section.
2477 std::sort(List.begin(), List.end(),
2478 [&](const SymbolCU &A, const SymbolCU &B) {
2479 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2480 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2482 // Symbols with no order assigned should be placed at the end.
2483 // (e.g. section end labels)
2491 // If we have no section (e.g. common), just write out
2492 // individual spans for each symbol.
2493 if (Section == NULL) {
2494 for (const SymbolCU &Cur : List) {
2496 Span.Start = Cur.Sym;
2499 Spans[Cur.CU].push_back(Span);
2502 // Build spans between each label.
2503 const MCSymbol *StartSym = List[0].Sym;
2504 for (size_t n = 1, e = List.size(); n < e; n++) {
2505 const SymbolCU &Prev = List[n - 1];
2506 const SymbolCU &Cur = List[n];
2508 // Try and build the longest span we can within the same CU.
2509 if (Cur.CU != Prev.CU) {
2511 Span.Start = StartSym;
2513 Spans[Prev.CU].push_back(Span);
2520 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2522 // Build a list of CUs used.
2523 std::vector<DwarfCompileUnit *> CUs;
2524 for (const auto &it : Spans) {
2525 DwarfCompileUnit *CU = it.first;
2529 // Sort the CU list (again, to ensure consistent output order).
2530 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2531 return A->getUniqueID() < B->getUniqueID();
2534 // Emit an arange table for each CU we used.
2535 for (DwarfCompileUnit *CU : CUs) {
2536 std::vector<ArangeSpan> &List = Spans[CU];
2538 // Emit size of content not including length itself.
2539 unsigned ContentSize =
2540 sizeof(int16_t) + // DWARF ARange version number
2541 sizeof(int32_t) + // Offset of CU in the .debug_info section
2542 sizeof(int8_t) + // Pointer Size (in bytes)
2543 sizeof(int8_t); // Segment Size (in bytes)
2545 unsigned TupleSize = PtrSize * 2;
2547 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2549 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2551 ContentSize += Padding;
2552 ContentSize += (List.size() + 1) * TupleSize;
2554 // For each compile unit, write the list of spans it covers.
2555 Asm->OutStreamer.AddComment("Length of ARange Set");
2556 Asm->EmitInt32(ContentSize);
2557 Asm->OutStreamer.AddComment("DWARF Arange version number");
2558 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2559 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2560 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2561 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2562 Asm->EmitInt8(PtrSize);
2563 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2566 Asm->OutStreamer.EmitFill(Padding, 0xff);
2568 for (const ArangeSpan &Span : List) {
2569 Asm->EmitLabelReference(Span.Start, PtrSize);
2571 // Calculate the size as being from the span start to it's end.
2573 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2575 // For symbols without an end marker (e.g. common), we
2576 // write a single arange entry containing just that one symbol.
2577 uint64_t Size = SymSize[Span.Start];
2581 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2585 Asm->OutStreamer.AddComment("ARange terminator");
2586 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2587 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2591 // Emit visible names into a debug ranges section.
2592 void DwarfDebug::emitDebugRanges() {
2593 // Start the dwarf ranges section.
2594 Asm->OutStreamer.SwitchSection(
2595 Asm->getObjFileLowering().getDwarfRangesSection());
2597 // Size for our labels.
2598 unsigned char Size = Asm->getDataLayout().getPointerSize();
2600 // Grab the specific ranges for the compile units in the module.
2601 for (const auto &I : CUMap) {
2602 DwarfCompileUnit *TheCU = I.second;
2604 // Emit a symbol so we can find the beginning of our ranges.
2605 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2607 // Iterate over the misc ranges for the compile units in the module.
2608 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2609 // Emit our symbol so we can find the beginning of the range.
2610 Asm->OutStreamer.EmitLabel(List.getSym());
2612 for (const RangeSpan &Range : List.getRanges()) {
2613 const MCSymbol *Begin = Range.getStart();
2614 const MCSymbol *End = Range.getEnd();
2615 assert(Begin && "Range without a begin symbol?");
2616 assert(End && "Range without an end symbol?");
2617 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2618 Asm->OutStreamer.EmitSymbolValue(End, Size);
2621 // And terminate the list with two 0 values.
2622 Asm->OutStreamer.EmitIntValue(0, Size);
2623 Asm->OutStreamer.EmitIntValue(0, Size);
2626 // Now emit a range for the CU itself.
2627 if (TheCU->getRanges().size() > 1) {
2628 Asm->OutStreamer.EmitLabel(
2629 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2630 for (const RangeSpan &Range : TheCU->getRanges()) {
2631 const MCSymbol *Begin = Range.getStart();
2632 const MCSymbol *End = Range.getEnd();
2633 assert(Begin && "Range without a begin symbol?");
2634 assert(End && "Range without an end symbol?");
2635 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2636 Asm->OutStreamer.EmitSymbolValue(End, Size);
2638 // And terminate the list with two 0 values.
2639 Asm->OutStreamer.EmitIntValue(0, Size);
2640 Asm->OutStreamer.EmitIntValue(0, Size);
2645 // DWARF5 Experimental Separate Dwarf emitters.
2647 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2649 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2650 U->getCUNode().getSplitDebugFilename());
2652 if (!CompilationDir.empty())
2653 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2655 addGnuPubAttributes(NewU, Die);
2657 SkeletonHolder.addUnit(NewU);
2660 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2661 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2662 // DW_AT_addr_base, DW_AT_ranges_base.
2663 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2665 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2666 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2667 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2668 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2669 DwarfInfoSectionSym);
2671 NewCU->initStmtList(DwarfLineSectionSym);
2673 initSkeletonUnit(CU, Die, NewCU);
2678 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2680 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2681 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2682 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2684 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2685 DwarfTypeUnit *NewTU =
2686 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2687 NewTU->setTypeSignature(TU->getTypeSignature());
2688 NewTU->setType(NULL);
2690 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2692 initSkeletonUnit(TU, Die, NewTU);
2696 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2697 // compile units that would normally be in debug_info.
2698 void DwarfDebug::emitDebugInfoDWO() {
2699 assert(useSplitDwarf() && "No split dwarf debug info?");
2700 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2701 // emit relocations into the dwo file.
2702 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2705 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2706 // abbreviations for the .debug_info.dwo section.
2707 void DwarfDebug::emitDebugAbbrevDWO() {
2708 assert(useSplitDwarf() && "No split dwarf?");
2709 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2712 void DwarfDebug::emitDebugLineDWO() {
2713 assert(useSplitDwarf() && "No split dwarf?");
2714 Asm->OutStreamer.SwitchSection(
2715 Asm->getObjFileLowering().getDwarfLineDWOSection());
2716 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2719 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2720 // string section and is identical in format to traditional .debug_str
2722 void DwarfDebug::emitDebugStrDWO() {
2723 assert(useSplitDwarf() && "No split dwarf?");
2724 const MCSection *OffSec =
2725 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2726 const MCSymbol *StrSym = DwarfStrSectionSym;
2727 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2731 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2732 if (!useSplitDwarf())
2735 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2736 return &SplitTypeUnitFileTable;
2739 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2740 StringRef Identifier, DIE *RefDie,
2741 DICompositeType CTy) {
2742 // Flag the type unit reference as a declaration so that if it contains
2743 // members (implicit special members, static data member definitions, member
2744 // declarations for definitions in this CU, etc) consumers don't get confused
2745 // and think this is a full definition.
2746 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2748 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2750 CU.addDIETypeSignature(RefDie, *TU);
2754 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2755 DwarfTypeUnit *NewTU =
2756 new DwarfTypeUnit(InfoHolder.getUnits().size(), UnitDie, CU, Asm, this,
2757 &InfoHolder, getDwoLineTable(CU));
2759 InfoHolder.addUnit(NewTU);
2761 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2765 Hash.update(Identifier);
2766 // ... take the least significant 8 bytes and return those. Our MD5
2767 // implementation always returns its results in little endian, swap bytes
2769 MD5::MD5Result Result;
2771 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2772 NewTU->setTypeSignature(Signature);
2773 if (useSplitDwarf())
2774 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2776 CU.applyStmtList(*UnitDie);
2778 NewTU->setType(NewTU->createTypeDIE(CTy));
2782 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2783 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2785 CU.addDIETypeSignature(RefDie, *NewTU);
2788 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2789 MCSymbol *Begin, MCSymbol *End) {
2790 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2791 if (DwarfVersion < 4)
2792 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2794 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);