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(AsmPrinter *AP, const char *Pref, BumpPtrAllocator &DA)
229 : Asm(AP), StringPool(DA), NextStringPoolNumber(0), StringPref(Pref) {}
230 DwarfFile::~DwarfFile() {
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 void DwarfFile::addUnit(std::unique_ptr<DwarfUnit> U) {
284 CUs.push_back(std::move(U));
287 static bool isObjCClass(StringRef Name) {
288 return Name.startswith("+") || Name.startswith("-");
291 static bool hasObjCCategory(StringRef Name) {
292 if (!isObjCClass(Name))
295 return Name.find(") ") != StringRef::npos;
298 static void getObjCClassCategory(StringRef In, StringRef &Class,
299 StringRef &Category) {
300 if (!hasObjCCategory(In)) {
301 Class = In.slice(In.find('[') + 1, In.find(' '));
306 Class = In.slice(In.find('[') + 1, In.find('('));
307 Category = In.slice(In.find('[') + 1, In.find(' '));
311 static StringRef getObjCMethodName(StringRef In) {
312 return In.slice(In.find(' ') + 1, In.find(']'));
315 // Helper for sorting sections into a stable output order.
316 static bool SectionSort(const MCSection *A, const MCSection *B) {
317 std::string LA = (A ? A->getLabelBeginName() : "");
318 std::string LB = (B ? B->getLabelBeginName() : "");
322 // Add the various names to the Dwarf accelerator table names.
323 // TODO: Determine whether or not we should add names for programs
324 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
325 // is only slightly different than the lookup of non-standard ObjC names.
326 static void addSubprogramNames(DwarfUnit &TheU, DISubprogram SP, DIE *Die) {
327 if (!SP.isDefinition())
329 TheU.addAccelName(SP.getName(), Die);
331 // If the linkage name is different than the name, go ahead and output
332 // that as well into the name table.
333 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
334 TheU.addAccelName(SP.getLinkageName(), Die);
336 // If this is an Objective-C selector name add it to the ObjC accelerator
338 if (isObjCClass(SP.getName())) {
339 StringRef Class, Category;
340 getObjCClassCategory(SP.getName(), Class, Category);
341 TheU.addAccelObjC(Class, Die);
343 TheU.addAccelObjC(Category, Die);
344 // Also add the base method name to the name table.
345 TheU.addAccelName(getObjCMethodName(SP.getName()), Die);
349 /// isSubprogramContext - Return true if Context is either a subprogram
350 /// or another context nested inside a subprogram.
351 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
354 DIDescriptor D(Context);
355 if (D.isSubprogram())
358 return isSubprogramContext(resolve(DIType(Context).getContext()));
362 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
363 // and DW_AT_high_pc attributes. If there are global variables in this
364 // scope then create and insert DIEs for these variables.
365 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
367 DIE *SPDie = SPCU.getDIE(SP);
369 assert(SPDie && "Unable to find subprogram DIE!");
371 // If we're updating an abstract DIE, then we will be adding the children and
372 // object pointer later on. But what we don't want to do is process the
373 // concrete DIE twice.
374 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
375 // Pick up abstract subprogram DIE.
377 SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
378 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
380 DISubprogram SPDecl = SP.getFunctionDeclaration();
381 if (!SPDecl.isSubprogram()) {
382 // There is not any need to generate specification DIE for a function
383 // defined at compile unit level. If a function is defined inside another
384 // function then gdb prefers the definition at top level and but does not
385 // expect specification DIE in parent function. So avoid creating
386 // specification DIE for a function defined inside a function.
387 DIScope SPContext = resolve(SP.getContext());
388 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
389 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
390 SPCU.addFlag(SPDie, dwarf::DW_AT_declaration);
393 DICompositeType SPTy = SP.getType();
394 DIArray Args = SPTy.getTypeArray();
395 uint16_t SPTag = SPTy.getTag();
396 if (SPTag == dwarf::DW_TAG_subroutine_type)
397 SPCU.constructSubprogramArguments(*SPDie, Args);
398 DIE *SPDeclDie = SPDie;
399 SPDie = SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram,
401 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
406 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
408 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
409 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
410 SPCU.addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
412 // Add name to the name table, we do this here because we're guaranteed
413 // to have concrete versions of our DW_TAG_subprogram nodes.
414 addSubprogramNames(SPCU, SP, SPDie);
419 /// Check whether we should create a DIE for the given Scope, return true
420 /// if we don't create a DIE (the corresponding DIE is null).
421 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
422 if (Scope->isAbstractScope())
425 // We don't create a DIE if there is no Range.
426 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
430 if (Ranges.size() > 1)
433 // We don't create a DIE if we have a single Range and the end label
435 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
436 MCSymbol *End = getLabelAfterInsn(RI->second);
440 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE *D,
441 dwarf::Attribute A, const MCSymbol *L,
442 const MCSymbol *Sec) {
443 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
444 U.addSectionLabel(D, A, L);
446 U.addSectionDelta(D, A, L, Sec);
449 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE *ScopeDIE,
450 const SmallVectorImpl<InsnRange> &Range) {
451 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
452 // emitting it appropriately.
453 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
455 // Under fission, ranges are specified by constant offsets relative to the
456 // CU's DW_AT_GNU_ranges_base.
458 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
459 DwarfDebugRangeSectionSym);
461 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
462 DwarfDebugRangeSectionSym);
464 RangeSpanList List(RangeSym);
465 for (const InsnRange &R : Range) {
466 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
467 List.addRange(std::move(Span));
470 // Add the range list to the set of ranges to be emitted.
471 TheCU.addRangeList(std::move(List));
474 // Construct new DW_TAG_lexical_block for this scope and attach
475 // DW_AT_low_pc/DW_AT_high_pc labels.
476 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
477 LexicalScope *Scope) {
478 if (isLexicalScopeDIENull(Scope))
481 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
482 if (Scope->isAbstractScope())
485 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
487 // If we have multiple ranges, emit them into the range section.
488 if (ScopeRanges.size() > 1) {
489 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
493 // Construct the address range for this DIE.
494 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
495 MCSymbol *Start = getLabelBeforeInsn(RI->first);
496 MCSymbol *End = getLabelAfterInsn(RI->second);
497 assert(End && "End label should not be null!");
499 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
500 assert(End->isDefined() && "Invalid end label for an inlined scope!");
502 attachLowHighPC(TheCU, ScopeDIE, Start, End);
507 // This scope represents inlined body of a function. Construct DIE to
508 // represent this concrete inlined copy of the function.
509 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
510 LexicalScope *Scope) {
511 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
512 assert(!ScopeRanges.empty() &&
513 "LexicalScope does not have instruction markers!");
515 if (!Scope->getScopeNode())
517 DIScope DS(Scope->getScopeNode());
518 DISubprogram InlinedSP = getDISubprogram(DS);
519 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
521 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
525 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
526 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
528 // If we have multiple ranges, emit them into the range section.
529 if (ScopeRanges.size() > 1)
530 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
532 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
533 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
534 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
536 if (StartLabel == 0 || EndLabel == 0)
537 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
539 assert(StartLabel->isDefined() &&
540 "Invalid starting label for an inlined scope!");
541 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
543 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
546 InlinedSubprogramDIEs.insert(OriginDIE);
548 // Add the call site information to the DIE.
549 DILocation DL(Scope->getInlinedAt());
551 ScopeDIE, dwarf::DW_AT_call_file, None,
552 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
553 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
555 // Add name to the name table, we do this here because we're guaranteed
556 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
557 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
562 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit &TheCU,
564 SmallVectorImpl<DIE *> &Children) {
565 DIE *ObjectPointer = NULL;
567 // Collect arguments for current function.
568 if (LScopes.isCurrentFunctionScope(Scope)) {
569 for (DbgVariable *ArgDV : CurrentFnArguments)
572 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
573 Children.push_back(Arg);
574 if (ArgDV->isObjectPointer())
578 // If this is a variadic function, add an unspecified parameter.
579 DISubprogram SP(Scope->getScopeNode());
580 DIArray FnArgs = SP.getType().getTypeArray();
581 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
582 .isUnspecifiedParameter()) {
583 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
584 Children.push_back(Ellipsis);
588 // Collect lexical scope children first.
589 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
590 if (DIE *Variable = TheCU.constructVariableDIE(*DV,
591 Scope->isAbstractScope())) {
592 Children.push_back(Variable);
593 if (DV->isObjectPointer())
594 ObjectPointer = Variable;
596 for (LexicalScope *LS : Scope->getChildren())
597 if (DIE *Nested = constructScopeDIE(TheCU, LS))
598 Children.push_back(Nested);
599 return ObjectPointer;
602 // Construct a DIE for this scope.
603 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
604 LexicalScope *Scope) {
605 if (!Scope || !Scope->getScopeNode())
608 DIScope DS(Scope->getScopeNode());
610 SmallVector<DIE *, 8> Children;
611 DIE *ObjectPointer = NULL;
612 bool ChildrenCreated = false;
614 // We try to create the scope DIE first, then the children DIEs. This will
615 // avoid creating un-used children then removing them later when we find out
616 // the scope DIE is null.
617 DIE *ScopeDIE = NULL;
618 if (Scope->getInlinedAt())
619 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
620 else if (DS.isSubprogram()) {
621 ProcessedSPNodes.insert(DS);
622 if (Scope->isAbstractScope()) {
623 ScopeDIE = TheCU.getDIE(DS);
624 // Note down abstract DIE.
626 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
628 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
630 // Early exit when we know the scope DIE is going to be null.
631 if (isLexicalScopeDIENull(Scope))
634 // We create children here when we know the scope DIE is not going to be
635 // null and the children will be added to the scope DIE.
636 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
637 ChildrenCreated = true;
639 // There is no need to emit empty lexical block DIE.
640 std::pair<ImportedEntityMap::const_iterator,
641 ImportedEntityMap::const_iterator> Range =
643 ScopesWithImportedEntities.begin(),
644 ScopesWithImportedEntities.end(),
645 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
647 if (Children.empty() && Range.first == Range.second)
649 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
650 assert(ScopeDIE && "Scope DIE should not be null.");
651 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
653 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
657 assert(Children.empty() &&
658 "We create children only when the scope DIE is not null.");
661 if (!ChildrenCreated)
662 // We create children when the scope DIE is not null.
663 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
666 for (DIE *I : Children)
667 ScopeDIE->addChild(I);
669 if (DS.isSubprogram() && ObjectPointer != NULL)
670 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
675 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE *D) const {
676 if (!GenerateGnuPubSections)
679 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
682 // Create new DwarfCompileUnit for the given metadata node with tag
683 // DW_TAG_compile_unit.
684 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
685 StringRef FN = DIUnit.getFilename();
686 CompilationDir = DIUnit.getDirectory();
688 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
689 auto OwnedUnit = make_unique<DwarfCompileUnit>(
690 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
691 DwarfCompileUnit &NewCU = *OwnedUnit;
692 InfoHolder.addUnit(std::move(OwnedUnit));
695 // LTO with assembly output shares a single line table amongst multiple CUs.
696 // To avoid the compilation directory being ambiguous, let the line table
697 // explicitly describe the directory of all files, never relying on the
698 // compilation directory.
699 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
700 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
701 NewCU.getUniqueID(), CompilationDir);
703 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
704 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
705 DIUnit.getLanguage());
706 NewCU.addString(Die, dwarf::DW_AT_name, FN);
708 if (!useSplitDwarf()) {
709 NewCU.initStmtList(DwarfLineSectionSym);
711 // If we're using split dwarf the compilation dir is going to be in the
712 // skeleton CU and so we don't need to duplicate it here.
713 if (!CompilationDir.empty())
714 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
716 addGnuPubAttributes(NewCU, Die);
719 if (DIUnit.isOptimized())
720 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
722 StringRef Flags = DIUnit.getFlags();
724 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
726 if (unsigned RVer = DIUnit.getRunTimeVersion())
727 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
728 dwarf::DW_FORM_data1, RVer);
733 if (useSplitDwarf()) {
734 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
735 DwarfInfoDWOSectionSym);
736 NewCU.setSkeleton(constructSkeletonCU(NewCU));
738 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
739 DwarfInfoSectionSym);
741 CUMap.insert(std::make_pair(DIUnit, &NewCU));
742 CUDieMap.insert(std::make_pair(Die, &NewCU));
746 // Construct subprogram DIE.
747 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
749 // FIXME: We should only call this routine once, however, during LTO if a
750 // program is defined in multiple CUs we could end up calling it out of
751 // beginModule as we walk the CUs.
753 DwarfCompileUnit *&CURef = SPMap[N];
759 if (!SP.isDefinition())
760 // This is a method declaration which will be handled while constructing
764 DIE *SubprogramDie = TheCU.getOrCreateSubprogramDIE(SP);
766 // Expose as a global name.
767 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
770 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
772 DIImportedEntity Module(N);
773 assert(Module.Verify());
774 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
775 constructImportedEntityDIE(TheCU, Module, D);
778 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
779 const MDNode *N, DIE *Context) {
780 DIImportedEntity Module(N);
781 assert(Module.Verify());
782 return constructImportedEntityDIE(TheCU, Module, Context);
785 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
786 const DIImportedEntity &Module,
788 assert(Module.Verify() &&
789 "Use one of the MDNode * overloads to handle invalid metadata");
790 assert(Context && "Should always have a context for an imported_module");
791 DIE *IMDie = TheCU.createAndAddDIE(Module.getTag(), *Context, Module);
793 DIDescriptor Entity = resolve(Module.getEntity());
794 if (Entity.isNameSpace())
795 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
796 else if (Entity.isSubprogram())
797 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
798 else if (Entity.isType())
799 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
801 EntityDie = TheCU.getDIE(Entity);
802 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
803 Module.getContext().getFilename(),
804 Module.getContext().getDirectory());
805 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
806 StringRef Name = Module.getName();
808 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
811 // Emit all Dwarf sections that should come prior to the content. Create
812 // global DIEs and emit initial debug info sections. This is invoked by
813 // the target AsmPrinter.
814 void DwarfDebug::beginModule() {
815 if (DisableDebugInfoPrinting)
818 const Module *M = MMI->getModule();
820 // If module has named metadata anchors then use them, otherwise scan the
821 // module using debug info finder to collect debug info.
822 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
825 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
827 // Emit initial sections so we can reference labels later.
830 SingleCU = CU_Nodes->getNumOperands() == 1;
832 for (MDNode *N : CU_Nodes->operands()) {
833 DICompileUnit CUNode(N);
834 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
835 DIArray ImportedEntities = CUNode.getImportedEntities();
836 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
837 ScopesWithImportedEntities.push_back(std::make_pair(
838 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
839 ImportedEntities.getElement(i)));
840 std::sort(ScopesWithImportedEntities.begin(),
841 ScopesWithImportedEntities.end(), less_first());
842 DIArray GVs = CUNode.getGlobalVariables();
843 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
844 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
845 DIArray SPs = CUNode.getSubprograms();
846 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
847 constructSubprogramDIE(CU, SPs.getElement(i));
848 DIArray EnumTypes = CUNode.getEnumTypes();
849 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
850 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
851 DIArray RetainedTypes = CUNode.getRetainedTypes();
852 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
853 DIType Ty(RetainedTypes.getElement(i));
854 // The retained types array by design contains pointers to
855 // MDNodes rather than DIRefs. Unique them here.
856 DIType UniqueTy(resolve(Ty.getRef()));
857 CU.getOrCreateTypeDIE(UniqueTy);
859 // Emit imported_modules last so that the relevant context is already
861 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
862 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
865 // Tell MMI that we have debug info.
866 MMI->setDebugInfoAvailability(true);
868 // Prime section data.
869 SectionMap[Asm->getObjFileLowering().getTextSection()];
872 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
873 void DwarfDebug::computeInlinedDIEs() {
874 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
875 for (DIE *ISP : InlinedSubprogramDIEs)
876 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
878 for (const auto &AI : AbstractSPDies) {
879 DIE *ISP = AI.second;
880 if (InlinedSubprogramDIEs.count(ISP))
882 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
886 // Collect info for variables that were optimized out.
887 void DwarfDebug::collectDeadVariables() {
888 const Module *M = MMI->getModule();
890 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
891 for (MDNode *N : CU_Nodes->operands()) {
892 DICompileUnit TheCU(N);
893 DIArray Subprograms = TheCU.getSubprograms();
894 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
895 DISubprogram SP(Subprograms.getElement(i));
896 if (ProcessedSPNodes.count(SP) != 0)
898 if (!SP.isSubprogram())
900 if (!SP.isDefinition())
902 DIArray Variables = SP.getVariables();
903 if (Variables.getNumElements() == 0)
906 // Construct subprogram DIE and add variables DIEs.
907 DwarfCompileUnit *SPCU =
908 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
909 assert(SPCU && "Unable to find Compile Unit!");
910 // FIXME: See the comment in constructSubprogramDIE about duplicate
912 constructSubprogramDIE(*SPCU, SP);
913 DIE *SPDIE = SPCU->getDIE(SP);
914 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
915 DIVariable DV(Variables.getElement(vi));
916 if (!DV.isVariable())
918 DbgVariable NewVar(DV, NULL, this);
919 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
920 SPDIE->addChild(VariableDIE);
927 void DwarfDebug::finalizeModuleInfo() {
928 // Collect info for variables that were optimized out.
929 collectDeadVariables();
931 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
932 computeInlinedDIEs();
934 // Handle anything that needs to be done on a per-unit basis after
935 // all other generation.
936 for (const auto &TheU : getUnits()) {
937 // Emit DW_AT_containing_type attribute to connect types with their
938 // vtable holding type.
939 TheU->constructContainingTypeDIEs();
941 // Add CU specific attributes if we need to add any.
942 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
943 // If we're splitting the dwarf out now that we've got the entire
944 // CU then add the dwo id to it.
945 DwarfCompileUnit *SkCU =
946 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
947 if (useSplitDwarf()) {
948 // Emit a unique identifier for this CU.
949 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
950 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
951 dwarf::DW_FORM_data8, ID);
952 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
953 dwarf::DW_FORM_data8, ID);
955 // We don't keep track of which addresses are used in which CU so this
956 // is a bit pessimistic under LTO.
957 if (!InfoHolder.getAddrPool()->empty())
958 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
959 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
960 DwarfAddrSectionSym);
961 if (!TheU->getRangeLists().empty())
962 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
963 dwarf::DW_AT_GNU_ranges_base,
964 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
967 // If we have code split among multiple sections or non-contiguous
968 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
969 // remain in the .o file, otherwise add a DW_AT_low_pc.
970 // FIXME: We should use ranges allow reordering of code ala
971 // .subsections_via_symbols in mach-o. This would mean turning on
972 // ranges for all subprogram DIEs for mach-o.
973 DwarfCompileUnit &U =
974 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
975 unsigned NumRanges = TheU->getRanges().size();
978 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
979 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
980 DwarfDebugRangeSectionSym);
982 // A DW_AT_low_pc attribute may also be specified in combination with
983 // DW_AT_ranges to specify the default base address for use in
984 // location lists (see Section 2.6.2) and range lists (see Section
986 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
989 RangeSpan &Range = TheU->getRanges().back();
990 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
992 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
999 // Compute DIE offsets and sizes.
1000 InfoHolder.computeSizeAndOffsets();
1001 if (useSplitDwarf())
1002 SkeletonHolder.computeSizeAndOffsets();
1005 void DwarfDebug::endSections() {
1006 // Filter labels by section.
1007 for (const SymbolCU &SCU : ArangeLabels) {
1008 if (SCU.Sym->isInSection()) {
1009 // Make a note of this symbol and it's section.
1010 const MCSection *Section = &SCU.Sym->getSection();
1011 if (!Section->getKind().isMetadata())
1012 SectionMap[Section].push_back(SCU);
1014 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1015 // appear in the output. This sucks as we rely on sections to build
1016 // arange spans. We can do it without, but it's icky.
1017 SectionMap[NULL].push_back(SCU);
1021 // Build a list of sections used.
1022 std::vector<const MCSection *> Sections;
1023 for (const auto &it : SectionMap) {
1024 const MCSection *Section = it.first;
1025 Sections.push_back(Section);
1028 // Sort the sections into order.
1029 // This is only done to ensure consistent output order across different runs.
1030 std::sort(Sections.begin(), Sections.end(), SectionSort);
1032 // Add terminating symbols for each section.
1033 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1034 const MCSection *Section = Sections[ID];
1035 MCSymbol *Sym = NULL;
1038 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1039 // if we know the section name up-front. For user-created sections, the
1040 // resulting label may not be valid to use as a label. (section names can
1041 // use a greater set of characters on some systems)
1042 Sym = Asm->GetTempSymbol("debug_end", ID);
1043 Asm->OutStreamer.SwitchSection(Section);
1044 Asm->OutStreamer.EmitLabel(Sym);
1047 // Insert a final terminator.
1048 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1052 // Emit all Dwarf sections that should come after the content.
1053 void DwarfDebug::endModule() {
1060 // End any existing sections.
1061 // TODO: Does this need to happen?
1064 // Finalize the debug info for the module.
1065 finalizeModuleInfo();
1069 // Emit all the DIEs into a debug info section.
1072 // Corresponding abbreviations into a abbrev section.
1073 emitAbbreviations();
1075 // Emit info into a debug aranges section.
1076 if (GenerateARangeSection)
1079 // Emit info into a debug ranges section.
1082 if (useSplitDwarf()) {
1085 emitDebugAbbrevDWO();
1087 // Emit DWO addresses.
1088 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1091 // Emit info into a debug loc section.
1094 // Emit info into the dwarf accelerator table sections.
1095 if (useDwarfAccelTables()) {
1098 emitAccelNamespaces();
1102 // Emit the pubnames and pubtypes sections if requested.
1103 if (HasDwarfPubSections) {
1104 emitDebugPubNames(GenerateGnuPubSections);
1105 emitDebugPubTypes(GenerateGnuPubSections);
1111 // Reset these for the next Module if we have one.
1115 // Find abstract variable, if any, associated with Var.
1116 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1117 DebugLoc ScopeLoc) {
1118 LLVMContext &Ctx = DV->getContext();
1119 // More then one inlined variable corresponds to one abstract variable.
1120 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1121 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1123 return AbsDbgVariable;
1125 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1129 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1130 addScopeVariable(Scope, AbsDbgVariable);
1131 AbstractVariables[Var] = AbsDbgVariable;
1132 return AbsDbgVariable;
1135 // If Var is a current function argument then add it to CurrentFnArguments list.
1136 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1137 if (!LScopes.isCurrentFunctionScope(Scope))
1139 DIVariable DV = Var->getVariable();
1140 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1142 unsigned ArgNo = DV.getArgNumber();
1146 size_t Size = CurrentFnArguments.size();
1148 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1149 // llvm::Function argument size is not good indicator of how many
1150 // arguments does the function have at source level.
1152 CurrentFnArguments.resize(ArgNo * 2);
1153 CurrentFnArguments[ArgNo - 1] = Var;
1157 // Collect variable information from side table maintained by MMI.
1158 void DwarfDebug::collectVariableInfoFromMMITable(
1159 SmallPtrSet<const MDNode *, 16> &Processed) {
1160 for (const auto &VI : MMI->getVariableDbgInfo()) {
1163 Processed.insert(VI.Var);
1164 DIVariable DV(VI.Var);
1165 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1167 // If variable scope is not found then skip this variable.
1171 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1172 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1173 RegVar->setFrameIndex(VI.Slot);
1174 if (!addCurrentFnArgument(RegVar, Scope))
1175 addScopeVariable(Scope, RegVar);
1177 AbsDbgVariable->setFrameIndex(VI.Slot);
1181 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1183 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1184 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1185 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1186 MI->getOperand(0).getReg() &&
1187 (MI->getOperand(1).isImm() ||
1188 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1191 // Get .debug_loc entry for the instruction range starting at MI.
1192 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1193 const MCSymbol *FLabel,
1194 const MCSymbol *SLabel,
1195 const MachineInstr *MI,
1196 DwarfCompileUnit *Unit) {
1197 const MDNode *Var = MI->getDebugVariable();
1199 assert(MI->getNumOperands() == 3);
1200 if (MI->getOperand(0).isReg()) {
1201 MachineLocation MLoc;
1202 // If the second operand is an immediate, this is a
1203 // register-indirect address.
1204 if (!MI->getOperand(1).isImm())
1205 MLoc.set(MI->getOperand(0).getReg());
1207 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1208 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1210 if (MI->getOperand(0).isImm())
1211 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1212 if (MI->getOperand(0).isFPImm())
1213 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1215 if (MI->getOperand(0).isCImm())
1216 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1219 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1222 // Find variables for each lexical scope.
1224 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1226 // Grab the variable info that was squirreled away in the MMI side-table.
1227 collectVariableInfoFromMMITable(Processed);
1229 for (const MDNode *Var : UserVariables) {
1230 if (Processed.count(Var))
1233 // History contains relevant DBG_VALUE instructions for Var and instructions
1235 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1236 if (History.empty())
1238 const MachineInstr *MInsn = History.front();
1241 LexicalScope *Scope = NULL;
1242 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1243 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1244 Scope = LScopes.getCurrentFunctionScope();
1245 else if (MDNode *IA = DV.getInlinedAt())
1246 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1248 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1249 // If variable scope is not found then skip this variable.
1253 Processed.insert(DV);
1254 assert(MInsn->isDebugValue() && "History must begin with debug value");
1255 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1256 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1257 if (!addCurrentFnArgument(RegVar, Scope))
1258 addScopeVariable(Scope, RegVar);
1260 AbsVar->setMInsn(MInsn);
1262 // Simplify ranges that are fully coalesced.
1263 if (History.size() <= 1 ||
1264 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1265 RegVar->setMInsn(MInsn);
1269 // Handle multiple DBG_VALUE instructions describing one variable.
1270 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1272 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1273 DebugLocList &LocList = DotDebugLocEntries.back();
1275 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1276 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1277 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1278 HI = History.begin(),
1281 const MachineInstr *Begin = *HI;
1282 assert(Begin->isDebugValue() && "Invalid History entry");
1284 // Check if DBG_VALUE is truncating a range.
1285 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1286 !Begin->getOperand(0).getReg())
1289 // Compute the range for a register location.
1290 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1291 const MCSymbol *SLabel = 0;
1294 // If Begin is the last instruction in History then its value is valid
1295 // until the end of the function.
1296 SLabel = FunctionEndSym;
1298 const MachineInstr *End = HI[1];
1299 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1300 << "\t" << *Begin << "\t" << *End << "\n");
1301 if (End->isDebugValue())
1302 SLabel = getLabelBeforeInsn(End);
1304 // End is a normal instruction clobbering the range.
1305 SLabel = getLabelAfterInsn(End);
1306 assert(SLabel && "Forgot label after clobber instruction");
1311 // The value is valid until the next DBG_VALUE or clobber.
1312 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1313 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1314 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1315 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1316 DebugLoc.push_back(std::move(Loc));
1320 // Collect info for variables that were optimized out.
1321 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1322 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1323 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1324 DIVariable DV(Variables.getElement(i));
1325 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1327 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1328 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1332 // Return Label preceding the instruction.
1333 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1334 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1335 assert(Label && "Didn't insert label before instruction");
1339 // Return Label immediately following the instruction.
1340 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1341 return LabelsAfterInsn.lookup(MI);
1344 // Process beginning of an instruction.
1345 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1348 // Check if source location changes, but ignore DBG_VALUE locations.
1349 if (!MI->isDebugValue()) {
1350 DebugLoc DL = MI->getDebugLoc();
1351 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1354 if (DL == PrologEndLoc) {
1355 Flags |= DWARF2_FLAG_PROLOGUE_END;
1356 PrologEndLoc = DebugLoc();
1358 if (PrologEndLoc.isUnknown())
1359 Flags |= DWARF2_FLAG_IS_STMT;
1361 if (!DL.isUnknown()) {
1362 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1363 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1365 recordSourceLine(0, 0, 0, 0);
1369 // Insert labels where requested.
1370 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1371 LabelsBeforeInsn.find(MI);
1374 if (I == LabelsBeforeInsn.end())
1377 // Label already assigned.
1382 PrevLabel = MMI->getContext().CreateTempSymbol();
1383 Asm->OutStreamer.EmitLabel(PrevLabel);
1385 I->second = PrevLabel;
1388 // Process end of an instruction.
1389 void DwarfDebug::endInstruction() {
1391 // Don't create a new label after DBG_VALUE instructions.
1392 // They don't generate code.
1393 if (!CurMI->isDebugValue())
1396 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1397 LabelsAfterInsn.find(CurMI);
1401 if (I == LabelsAfterInsn.end())
1404 // Label already assigned.
1408 // We need a label after this instruction.
1410 PrevLabel = MMI->getContext().CreateTempSymbol();
1411 Asm->OutStreamer.EmitLabel(PrevLabel);
1413 I->second = PrevLabel;
1416 // Each LexicalScope has first instruction and last instruction to mark
1417 // beginning and end of a scope respectively. Create an inverse map that list
1418 // scopes starts (and ends) with an instruction. One instruction may start (or
1419 // end) multiple scopes. Ignore scopes that are not reachable.
1420 void DwarfDebug::identifyScopeMarkers() {
1421 SmallVector<LexicalScope *, 4> WorkList;
1422 WorkList.push_back(LScopes.getCurrentFunctionScope());
1423 while (!WorkList.empty()) {
1424 LexicalScope *S = WorkList.pop_back_val();
1426 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1427 if (!Children.empty())
1428 WorkList.append(Children.begin(), Children.end());
1430 if (S->isAbstractScope())
1433 for (const InsnRange &R : S->getRanges()) {
1434 assert(R.first && "InsnRange does not have first instruction!");
1435 assert(R.second && "InsnRange does not have second instruction!");
1436 requestLabelBeforeInsn(R.first);
1437 requestLabelAfterInsn(R.second);
1442 // Gather pre-function debug information. Assumes being called immediately
1443 // after the function entry point has been emitted.
1444 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1447 // If there's no debug info for the function we're not going to do anything.
1448 if (!MMI->hasDebugInfo())
1451 // Grab the lexical scopes for the function, if we don't have any of those
1452 // then we're not going to be able to do anything.
1453 LScopes.initialize(*MF);
1454 if (LScopes.empty())
1457 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1459 // Make sure that each lexical scope will have a begin/end label.
1460 identifyScopeMarkers();
1462 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1463 // belongs to so that we add to the correct per-cu line table in the
1465 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1466 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1467 assert(TheCU && "Unable to find compile unit!");
1468 if (Asm->OutStreamer.hasRawTextSupport())
1469 // Use a single line table if we are generating assembly.
1470 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1472 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1474 // Emit a label for the function so that we have a beginning address.
1475 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1476 // Assumes in correct section after the entry point.
1477 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1479 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1480 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1481 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1483 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1485 bool AtBlockEntry = true;
1486 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1488 const MachineInstr *MI = II;
1490 if (MI->isDebugValue()) {
1491 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1493 // Keep track of user variables.
1494 const MDNode *Var = MI->getDebugVariable();
1496 // Variable is in a register, we need to check for clobbers.
1497 if (isDbgValueInDefinedReg(MI))
1498 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1500 // Check the history of this variable.
1501 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1502 if (History.empty()) {
1503 UserVariables.push_back(Var);
1504 // The first mention of a function argument gets the FunctionBeginSym
1505 // label, so arguments are visible when breaking at function entry.
1507 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1508 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1509 LabelsBeforeInsn[MI] = FunctionBeginSym;
1511 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1512 const MachineInstr *Prev = History.back();
1513 if (Prev->isDebugValue()) {
1514 // Coalesce identical entries at the end of History.
1515 if (History.size() >= 2 &&
1516 Prev->isIdenticalTo(History[History.size() - 2])) {
1517 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1518 << "\t" << *Prev << "\t"
1519 << *History[History.size() - 2] << "\n");
1523 // Terminate old register assignments that don't reach MI;
1524 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1525 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1526 isDbgValueInDefinedReg(Prev)) {
1527 // Previous register assignment needs to terminate at the end of
1529 MachineBasicBlock::const_iterator LastMI =
1530 PrevMBB->getLastNonDebugInstr();
1531 if (LastMI == PrevMBB->end()) {
1532 // Drop DBG_VALUE for empty range.
1533 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1534 << "\t" << *Prev << "\n");
1536 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1537 // Terminate after LastMI.
1538 History.push_back(LastMI);
1542 History.push_back(MI);
1544 // Not a DBG_VALUE instruction.
1545 if (!MI->isPosition())
1546 AtBlockEntry = false;
1548 // First known non-DBG_VALUE and non-frame setup location marks
1549 // the beginning of the function body.
1550 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1551 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1552 PrologEndLoc = MI->getDebugLoc();
1554 // Check if the instruction clobbers any registers with debug vars.
1555 for (const MachineOperand &MO : MI->operands()) {
1556 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1558 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1561 const MDNode *Var = LiveUserVar[Reg];
1564 // Reg is now clobbered.
1565 LiveUserVar[Reg] = 0;
1567 // Was MD last defined by a DBG_VALUE referring to Reg?
1568 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1569 if (HistI == DbgValues.end())
1571 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1572 if (History.empty())
1574 const MachineInstr *Prev = History.back();
1575 // Sanity-check: Register assignments are terminated at the end of
1577 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1579 // Is the variable still in Reg?
1580 if (!isDbgValueInDefinedReg(Prev) ||
1581 Prev->getOperand(0).getReg() != Reg)
1583 // Var is clobbered. Make sure the next instruction gets a label.
1584 History.push_back(MI);
1591 for (auto &I : DbgValues) {
1592 SmallVectorImpl<const MachineInstr *> &History = I.second;
1593 if (History.empty())
1596 // Make sure the final register assignments are terminated.
1597 const MachineInstr *Prev = History.back();
1598 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1599 const MachineBasicBlock *PrevMBB = Prev->getParent();
1600 MachineBasicBlock::const_iterator LastMI =
1601 PrevMBB->getLastNonDebugInstr();
1602 if (LastMI == PrevMBB->end())
1603 // Drop DBG_VALUE for empty range.
1605 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1606 // Terminate after LastMI.
1607 History.push_back(LastMI);
1610 // Request labels for the full history.
1611 for (const MachineInstr *MI : History) {
1612 if (MI->isDebugValue())
1613 requestLabelBeforeInsn(MI);
1615 requestLabelAfterInsn(MI);
1619 PrevInstLoc = DebugLoc();
1620 PrevLabel = FunctionBeginSym;
1622 // Record beginning of function.
1623 if (!PrologEndLoc.isUnknown()) {
1624 DebugLoc FnStartDL =
1625 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1627 FnStartDL.getLine(), FnStartDL.getCol(),
1628 FnStartDL.getScope(MF->getFunction()->getContext()),
1629 // We'd like to list the prologue as "not statements" but GDB behaves
1630 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1631 DWARF2_FLAG_IS_STMT);
1635 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1636 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1637 DIVariable DV = Var->getVariable();
1638 // Variables with positive arg numbers are parameters.
1639 if (unsigned ArgNum = DV.getArgNumber()) {
1640 // Keep all parameters in order at the start of the variable list to ensure
1641 // function types are correct (no out-of-order parameters)
1643 // This could be improved by only doing it for optimized builds (unoptimized
1644 // builds have the right order to begin with), searching from the back (this
1645 // would catch the unoptimized case quickly), or doing a binary search
1646 // rather than linear search.
1647 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1648 while (I != Vars.end()) {
1649 unsigned CurNum = (*I)->getVariable().getArgNumber();
1650 // A local (non-parameter) variable has been found, insert immediately
1654 // A later indexed parameter has been found, insert immediately before it.
1655 if (CurNum > ArgNum)
1659 Vars.insert(I, Var);
1663 Vars.push_back(Var);
1666 // Gather and emit post-function debug information.
1667 void DwarfDebug::endFunction(const MachineFunction *MF) {
1668 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1669 // though the beginFunction may not be called at all.
1670 // We should handle both cases.
1674 assert(CurFn == MF);
1677 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1678 // If we don't have a lexical scope for this function then there will
1679 // be a hole in the range information. Keep note of this by setting the
1680 // previously used section to nullptr.
1681 PrevSection = nullptr;
1687 // Define end label for subprogram.
1688 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1689 // Assumes in correct section after the entry point.
1690 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1692 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1693 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1695 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1696 collectVariableInfo(ProcessedVars);
1698 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1699 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1701 // Construct abstract scopes.
1702 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1703 DISubprogram SP(AScope->getScopeNode());
1704 if (SP.isSubprogram()) {
1705 // Collect info for variables that were optimized out.
1706 DIArray Variables = SP.getVariables();
1707 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1708 DIVariable DV(Variables.getElement(i));
1709 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1711 // Check that DbgVariable for DV wasn't created earlier, when
1712 // findAbstractVariable() was called for inlined instance of DV.
1713 LLVMContext &Ctx = DV->getContext();
1714 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1715 if (AbstractVariables.lookup(CleanDV))
1717 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1718 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1721 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1722 constructScopeDIE(TheCU, AScope);
1725 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1726 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1727 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1729 // Add the range of this function to the list of ranges for the CU.
1730 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1731 TheCU.addRange(std::move(Span));
1732 PrevSection = Asm->getCurrentSection();
1736 for (auto &I : ScopeVariables)
1737 DeleteContainerPointers(I.second);
1738 ScopeVariables.clear();
1739 DeleteContainerPointers(CurrentFnArguments);
1740 UserVariables.clear();
1742 AbstractVariables.clear();
1743 LabelsBeforeInsn.clear();
1744 LabelsAfterInsn.clear();
1749 // Register a source line with debug info. Returns the unique label that was
1750 // emitted and which provides correspondence to the source line list.
1751 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1756 unsigned Discriminator = 0;
1758 DIDescriptor Scope(S);
1760 if (Scope.isCompileUnit()) {
1761 DICompileUnit CU(S);
1762 Fn = CU.getFilename();
1763 Dir = CU.getDirectory();
1764 } else if (Scope.isFile()) {
1766 Fn = F.getFilename();
1767 Dir = F.getDirectory();
1768 } else if (Scope.isSubprogram()) {
1770 Fn = SP.getFilename();
1771 Dir = SP.getDirectory();
1772 } else if (Scope.isLexicalBlockFile()) {
1773 DILexicalBlockFile DBF(S);
1774 Fn = DBF.getFilename();
1775 Dir = DBF.getDirectory();
1776 } else if (Scope.isLexicalBlock()) {
1777 DILexicalBlock DB(S);
1778 Fn = DB.getFilename();
1779 Dir = DB.getDirectory();
1780 Discriminator = DB.getDiscriminator();
1782 llvm_unreachable("Unexpected scope info");
1784 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1785 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1786 .getOrCreateSourceID(Fn, Dir);
1788 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1792 //===----------------------------------------------------------------------===//
1794 //===----------------------------------------------------------------------===//
1796 // Compute the size and offset of a DIE. The offset is relative to start of the
1797 // CU. It returns the offset after laying out the DIE.
1798 unsigned DwarfFile::computeSizeAndOffset(DIE &Die, unsigned Offset) {
1799 // Record the abbreviation.
1800 assignAbbrevNumber(Die.getAbbrev());
1802 // Get the abbreviation for this DIE.
1803 const DIEAbbrev &Abbrev = Die.getAbbrev();
1806 Die.setOffset(Offset);
1808 // Start the size with the size of abbreviation code.
1809 Offset += getULEB128Size(Die.getAbbrevNumber());
1811 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1812 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1814 // Size the DIE attribute values.
1815 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1816 // Size attribute value.
1817 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1819 // Get the children.
1820 const auto &Children = Die.getChildren();
1822 // Size the DIE children if any.
1823 if (!Children.empty()) {
1824 assert(Abbrev.hasChildren() && "Children flag not set");
1826 for (auto &Child : Children)
1827 Offset = computeSizeAndOffset(*Child, Offset);
1829 // End of children marker.
1830 Offset += sizeof(int8_t);
1833 Die.setSize(Offset - Die.getOffset());
1837 // Compute the size and offset for each DIE.
1838 void DwarfFile::computeSizeAndOffsets() {
1839 // Offset from the first CU in the debug info section is 0 initially.
1840 unsigned SecOffset = 0;
1842 // Iterate over each compile unit and set the size and offsets for each
1843 // DIE within each compile unit. All offsets are CU relative.
1844 for (const auto &TheU : CUs) {
1845 TheU->setDebugInfoOffset(SecOffset);
1847 // CU-relative offset is reset to 0 here.
1848 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1849 TheU->getHeaderSize(); // Unit-specific headers
1851 // EndOffset here is CU-relative, after laying out
1852 // all of the CU DIE.
1853 unsigned EndOffset = computeSizeAndOffset(*TheU->getUnitDie(), Offset);
1854 SecOffset += EndOffset;
1858 // Emit initial Dwarf sections with a label at the start of each one.
1859 void DwarfDebug::emitSectionLabels() {
1860 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1862 // Dwarf sections base addresses.
1863 DwarfInfoSectionSym =
1864 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1865 if (useSplitDwarf())
1866 DwarfInfoDWOSectionSym =
1867 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1868 DwarfAbbrevSectionSym =
1869 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1870 if (useSplitDwarf())
1871 DwarfAbbrevDWOSectionSym = emitSectionSym(
1872 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1873 if (GenerateARangeSection)
1874 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1876 DwarfLineSectionSym =
1877 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1878 if (GenerateGnuPubSections) {
1879 DwarfGnuPubNamesSectionSym =
1880 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1881 DwarfGnuPubTypesSectionSym =
1882 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1883 } else if (HasDwarfPubSections) {
1884 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1885 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1888 DwarfStrSectionSym =
1889 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1890 if (useSplitDwarf()) {
1891 DwarfStrDWOSectionSym =
1892 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1893 DwarfAddrSectionSym =
1894 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1895 DwarfDebugLocSectionSym =
1896 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1898 DwarfDebugLocSectionSym =
1899 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1900 DwarfDebugRangeSectionSym =
1901 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1904 // Recursively emits a debug information entry.
1905 void DwarfDebug::emitDIE(DIE &Die) {
1906 // Get the abbreviation for this DIE.
1907 const DIEAbbrev &Abbrev = Die.getAbbrev();
1909 // Emit the code (index) for the abbreviation.
1910 if (Asm->isVerbose())
1911 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1912 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1913 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1914 dwarf::TagString(Abbrev.getTag()));
1915 Asm->EmitULEB128(Abbrev.getNumber());
1917 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1918 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1920 // Emit the DIE attribute values.
1921 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1922 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1923 dwarf::Form Form = AbbrevData[i].getForm();
1924 assert(Form && "Too many attributes for DIE (check abbreviation)");
1926 if (Asm->isVerbose()) {
1927 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1928 if (Attr == dwarf::DW_AT_accessibility)
1929 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1930 cast<DIEInteger>(Values[i])->getValue()));
1933 // Emit an attribute using the defined form.
1934 Values[i]->EmitValue(Asm, Form);
1937 // Emit the DIE children if any.
1938 if (Abbrev.hasChildren()) {
1939 for (auto &Child : Die.getChildren())
1942 Asm->OutStreamer.AddComment("End Of Children Mark");
1947 // Emit the various dwarf units to the unit section USection with
1948 // the abbreviations going into ASection.
1949 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSymbol *ASectionSym) {
1950 for (const auto &TheU : CUs) {
1951 DIE *Die = TheU->getUnitDie();
1952 const MCSection *USection = TheU->getSection();
1953 Asm->OutStreamer.SwitchSection(USection);
1955 // Emit the compile units header.
1956 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1958 // Emit size of content not including length itself
1959 Asm->OutStreamer.AddComment("Length of Unit");
1960 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1962 TheU->emitHeader(ASectionSym);
1965 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1969 // Emit the debug info section.
1970 void DwarfDebug::emitDebugInfo() {
1971 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1973 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1976 // Emit the abbreviation section.
1977 void DwarfDebug::emitAbbreviations() {
1978 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1980 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1983 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1984 // Check to see if it is worth the effort.
1985 if (!Abbreviations.empty()) {
1986 // Start the debug abbrev section.
1987 Asm->OutStreamer.SwitchSection(Section);
1989 // For each abbrevation.
1990 for (const DIEAbbrev *Abbrev : Abbreviations) {
1991 // Emit the abbrevations code (base 1 index.)
1992 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1994 // Emit the abbreviations data.
1998 // Mark end of abbreviations.
1999 Asm->EmitULEB128(0, "EOM(3)");
2003 // Emit the last address of the section and the end of the line matrix.
2004 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2005 // Define last address of section.
2006 Asm->OutStreamer.AddComment("Extended Op");
2009 Asm->OutStreamer.AddComment("Op size");
2010 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2011 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2012 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2014 Asm->OutStreamer.AddComment("Section end label");
2016 Asm->OutStreamer.EmitSymbolValue(
2017 Asm->GetTempSymbol("section_end", SectionEnd),
2018 Asm->getDataLayout().getPointerSize());
2020 // Mark end of matrix.
2021 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2027 // Emit visible names into a hashed accelerator table section.
2028 void DwarfDebug::emitAccelNames() {
2030 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2031 for (const auto &TheU : getUnits()) {
2032 for (const auto &GI : TheU->getAccelNames()) {
2033 StringRef Name = GI.getKey();
2034 for (const DIE *D : GI.second)
2035 AT.AddName(Name, D);
2039 AT.FinalizeTable(Asm, "Names");
2040 Asm->OutStreamer.SwitchSection(
2041 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2042 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2043 Asm->OutStreamer.EmitLabel(SectionBegin);
2045 // Emit the full data.
2046 AT.Emit(Asm, SectionBegin, &InfoHolder);
2049 // Emit objective C classes and categories into a hashed accelerator table
2051 void DwarfDebug::emitAccelObjC() {
2053 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2054 for (const auto &TheU : getUnits()) {
2055 for (const auto &GI : TheU->getAccelObjC()) {
2056 StringRef Name = GI.getKey();
2057 for (const DIE *D : GI.second)
2058 AT.AddName(Name, D);
2062 AT.FinalizeTable(Asm, "ObjC");
2063 Asm->OutStreamer.SwitchSection(
2064 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2065 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2066 Asm->OutStreamer.EmitLabel(SectionBegin);
2068 // Emit the full data.
2069 AT.Emit(Asm, SectionBegin, &InfoHolder);
2072 // Emit namespace dies into a hashed accelerator table.
2073 void DwarfDebug::emitAccelNamespaces() {
2075 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2076 for (const auto &TheU : getUnits()) {
2077 for (const auto &GI : TheU->getAccelNamespace()) {
2078 StringRef Name = GI.getKey();
2079 for (const DIE *D : GI.second)
2080 AT.AddName(Name, D);
2084 AT.FinalizeTable(Asm, "namespac");
2085 Asm->OutStreamer.SwitchSection(
2086 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2087 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2088 Asm->OutStreamer.EmitLabel(SectionBegin);
2090 // Emit the full data.
2091 AT.Emit(Asm, SectionBegin, &InfoHolder);
2094 // Emit type dies into a hashed accelerator table.
2095 void DwarfDebug::emitAccelTypes() {
2096 std::vector<DwarfAccelTable::Atom> Atoms;
2098 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2100 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2102 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2103 DwarfAccelTable AT(Atoms);
2104 for (const auto &TheU : getUnits()) {
2105 for (const auto &GI : TheU->getAccelTypes()) {
2106 StringRef Name = GI.getKey();
2107 for (const auto &DI : GI.second)
2108 AT.AddName(Name, DI.first, DI.second);
2112 AT.FinalizeTable(Asm, "types");
2113 Asm->OutStreamer.SwitchSection(
2114 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2115 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2116 Asm->OutStreamer.EmitLabel(SectionBegin);
2118 // Emit the full data.
2119 AT.Emit(Asm, SectionBegin, &InfoHolder);
2122 // Public name handling.
2123 // The format for the various pubnames:
2125 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2126 // for the DIE that is named.
2128 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2129 // into the CU and the index value is computed according to the type of value
2130 // for the DIE that is named.
2132 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2133 // it's the offset within the debug_info/debug_types dwo section, however, the
2134 // reference in the pubname header doesn't change.
2136 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2137 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2139 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2141 // We could have a specification DIE that has our most of our knowledge,
2142 // look for that now.
2143 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2145 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2146 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2147 Linkage = dwarf::GIEL_EXTERNAL;
2148 } else if (Die->findAttribute(dwarf::DW_AT_external))
2149 Linkage = dwarf::GIEL_EXTERNAL;
2151 switch (Die->getTag()) {
2152 case dwarf::DW_TAG_class_type:
2153 case dwarf::DW_TAG_structure_type:
2154 case dwarf::DW_TAG_union_type:
2155 case dwarf::DW_TAG_enumeration_type:
2156 return dwarf::PubIndexEntryDescriptor(
2157 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2158 ? dwarf::GIEL_STATIC
2159 : dwarf::GIEL_EXTERNAL);
2160 case dwarf::DW_TAG_typedef:
2161 case dwarf::DW_TAG_base_type:
2162 case dwarf::DW_TAG_subrange_type:
2163 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2164 case dwarf::DW_TAG_namespace:
2165 return dwarf::GIEK_TYPE;
2166 case dwarf::DW_TAG_subprogram:
2167 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2168 case dwarf::DW_TAG_constant:
2169 case dwarf::DW_TAG_variable:
2170 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2171 case dwarf::DW_TAG_enumerator:
2172 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2173 dwarf::GIEL_STATIC);
2175 return dwarf::GIEK_NONE;
2179 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2181 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2182 const MCSection *PSec =
2183 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2184 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2186 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2189 void DwarfDebug::emitDebugPubSection(
2190 bool GnuStyle, const MCSection *PSec, StringRef Name,
2191 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2192 for (const auto &NU : CUMap) {
2193 DwarfCompileUnit *TheU = NU.second;
2195 const auto &Globals = (TheU->*Accessor)();
2197 if (Globals.empty())
2200 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2202 unsigned ID = TheU->getUniqueID();
2204 // Start the dwarf pubnames section.
2205 Asm->OutStreamer.SwitchSection(PSec);
2208 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2209 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2210 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2211 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2213 Asm->OutStreamer.EmitLabel(BeginLabel);
2215 Asm->OutStreamer.AddComment("DWARF Version");
2216 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2218 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2219 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2221 Asm->OutStreamer.AddComment("Compilation Unit Length");
2222 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2224 // Emit the pubnames for this compilation unit.
2225 for (const auto &GI : Globals) {
2226 const char *Name = GI.getKeyData();
2227 const DIE *Entity = GI.second;
2229 Asm->OutStreamer.AddComment("DIE offset");
2230 Asm->EmitInt32(Entity->getOffset());
2233 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2234 Asm->OutStreamer.AddComment(
2235 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2236 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2237 Asm->EmitInt8(Desc.toBits());
2240 Asm->OutStreamer.AddComment("External Name");
2241 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2244 Asm->OutStreamer.AddComment("End Mark");
2246 Asm->OutStreamer.EmitLabel(EndLabel);
2250 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2251 const MCSection *PSec =
2252 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2253 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2255 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2258 // Emit strings into a string section.
2259 void DwarfFile::emitStrings(const MCSection *StrSection,
2260 const MCSection *OffsetSection = NULL,
2261 const MCSymbol *StrSecSym = NULL) {
2263 if (StringPool.empty())
2266 // Start the dwarf str section.
2267 Asm->OutStreamer.SwitchSection(StrSection);
2269 // Get all of the string pool entries and put them in an array by their ID so
2270 // we can sort them.
2271 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2273 for (const auto &I : StringPool)
2274 Entries.push_back(std::make_pair(I.second.second, &I));
2276 array_pod_sort(Entries.begin(), Entries.end());
2278 for (const auto &Entry : Entries) {
2279 // Emit a label for reference from debug information entries.
2280 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2282 // Emit the string itself with a terminating null byte.
2283 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2284 Entry.second->getKeyLength() + 1));
2287 // If we've got an offset section go ahead and emit that now as well.
2288 if (OffsetSection) {
2289 Asm->OutStreamer.SwitchSection(OffsetSection);
2290 unsigned offset = 0;
2291 unsigned size = 4; // FIXME: DWARF64 is 8.
2292 for (const auto &Entry : Entries) {
2293 Asm->OutStreamer.EmitIntValue(offset, size);
2294 offset += Entry.second->getKeyLength() + 1;
2299 // Emit addresses into the section given.
2300 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2302 if (AddressPool.empty())
2305 // Start the dwarf addr section.
2306 Asm->OutStreamer.SwitchSection(AddrSection);
2308 // Order the address pool entries by ID
2309 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2311 for (const auto &I : AddressPool)
2312 Entries[I.second.Number] =
2314 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2315 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2317 for (const MCExpr *Entry : Entries)
2318 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2321 // Emit visible names into a debug str section.
2322 void DwarfDebug::emitDebugStr() {
2323 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2324 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2327 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2328 const DebugLocEntry &Entry) {
2329 DIVariable DV(Entry.getVariable());
2330 if (Entry.isInt()) {
2331 DIBasicType BTy(resolve(DV.getType()));
2332 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2333 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2334 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2335 Streamer.EmitSLEB128(Entry.getInt());
2337 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2338 Streamer.EmitULEB128(Entry.getInt());
2340 } else if (Entry.isLocation()) {
2341 MachineLocation Loc = Entry.getLoc();
2342 if (!DV.hasComplexAddress())
2344 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2346 // Complex address entry.
2347 unsigned N = DV.getNumAddrElements();
2349 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2350 if (Loc.getOffset()) {
2352 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2353 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2354 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2355 Streamer.EmitSLEB128(DV.getAddrElement(1));
2357 // If first address element is OpPlus then emit
2358 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2359 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2360 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2364 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2367 // Emit remaining complex address elements.
2368 for (; i < N; ++i) {
2369 uint64_t Element = DV.getAddrElement(i);
2370 if (Element == DIBuilder::OpPlus) {
2371 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2372 Streamer.EmitULEB128(DV.getAddrElement(++i));
2373 } else if (Element == DIBuilder::OpDeref) {
2375 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2377 llvm_unreachable("unknown Opcode found in complex address");
2381 // else ... ignore constant fp. There is not any good way to
2382 // to represent them here in dwarf.
2386 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2387 Asm->OutStreamer.AddComment("Loc expr size");
2388 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2389 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2390 Asm->EmitLabelDifference(end, begin, 2);
2391 Asm->OutStreamer.EmitLabel(begin);
2393 APByteStreamer Streamer(*Asm);
2394 emitDebugLocEntry(Streamer, Entry);
2396 Asm->OutStreamer.EmitLabel(end);
2399 // Emit locations into the debug loc section.
2400 void DwarfDebug::emitDebugLoc() {
2401 // Start the dwarf loc section.
2402 Asm->OutStreamer.SwitchSection(
2403 Asm->getObjFileLowering().getDwarfLocSection());
2404 unsigned char Size = Asm->getDataLayout().getPointerSize();
2405 for (const auto &DebugLoc : DotDebugLocEntries) {
2406 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2407 for (const auto &Entry : DebugLoc.List) {
2408 // Set up the range. This range is relative to the entry point of the
2409 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2410 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2411 const DwarfCompileUnit *CU = Entry.getCU();
2412 if (CU->getRanges().size() == 1) {
2413 // Grab the begin symbol from the first range as our base.
2414 const MCSymbol *Base = CU->getRanges()[0].getStart();
2415 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2416 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2418 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2419 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2422 emitDebugLocEntryLocation(Entry);
2424 Asm->OutStreamer.EmitIntValue(0, Size);
2425 Asm->OutStreamer.EmitIntValue(0, Size);
2429 void DwarfDebug::emitDebugLocDWO() {
2430 Asm->OutStreamer.SwitchSection(
2431 Asm->getObjFileLowering().getDwarfLocDWOSection());
2432 for (const auto &DebugLoc : DotDebugLocEntries) {
2433 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2434 for (const auto &Entry : DebugLoc.List) {
2435 // Just always use start_length for now - at least that's one address
2436 // rather than two. We could get fancier and try to, say, reuse an
2437 // address we know we've emitted elsewhere (the start of the function?
2438 // The start of the CU or CU subrange that encloses this range?)
2439 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2440 unsigned idx = InfoHolder.getAddrPoolIndex(Entry.getBeginSym());
2441 Asm->EmitULEB128(idx);
2442 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2444 emitDebugLocEntryLocation(Entry);
2446 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2451 const MCSymbol *Start, *End;
2454 // Emit a debug aranges section, containing a CU lookup for any
2455 // address we can tie back to a CU.
2456 void DwarfDebug::emitDebugARanges() {
2457 // Start the dwarf aranges section.
2458 Asm->OutStreamer.SwitchSection(
2459 Asm->getObjFileLowering().getDwarfARangesSection());
2461 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2465 // Build a list of sections used.
2466 std::vector<const MCSection *> Sections;
2467 for (const auto &it : SectionMap) {
2468 const MCSection *Section = it.first;
2469 Sections.push_back(Section);
2472 // Sort the sections into order.
2473 // This is only done to ensure consistent output order across different runs.
2474 std::sort(Sections.begin(), Sections.end(), SectionSort);
2476 // Build a set of address spans, sorted by CU.
2477 for (const MCSection *Section : Sections) {
2478 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2479 if (List.size() < 2)
2482 // Sort the symbols by offset within the section.
2483 std::sort(List.begin(), List.end(),
2484 [&](const SymbolCU &A, const SymbolCU &B) {
2485 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2486 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2488 // Symbols with no order assigned should be placed at the end.
2489 // (e.g. section end labels)
2497 // If we have no section (e.g. common), just write out
2498 // individual spans for each symbol.
2499 if (Section == NULL) {
2500 for (const SymbolCU &Cur : List) {
2502 Span.Start = Cur.Sym;
2505 Spans[Cur.CU].push_back(Span);
2508 // Build spans between each label.
2509 const MCSymbol *StartSym = List[0].Sym;
2510 for (size_t n = 1, e = List.size(); n < e; n++) {
2511 const SymbolCU &Prev = List[n - 1];
2512 const SymbolCU &Cur = List[n];
2514 // Try and build the longest span we can within the same CU.
2515 if (Cur.CU != Prev.CU) {
2517 Span.Start = StartSym;
2519 Spans[Prev.CU].push_back(Span);
2526 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2528 // Build a list of CUs used.
2529 std::vector<DwarfCompileUnit *> CUs;
2530 for (const auto &it : Spans) {
2531 DwarfCompileUnit *CU = it.first;
2535 // Sort the CU list (again, to ensure consistent output order).
2536 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2537 return A->getUniqueID() < B->getUniqueID();
2540 // Emit an arange table for each CU we used.
2541 for (DwarfCompileUnit *CU : CUs) {
2542 std::vector<ArangeSpan> &List = Spans[CU];
2544 // Emit size of content not including length itself.
2545 unsigned ContentSize =
2546 sizeof(int16_t) + // DWARF ARange version number
2547 sizeof(int32_t) + // Offset of CU in the .debug_info section
2548 sizeof(int8_t) + // Pointer Size (in bytes)
2549 sizeof(int8_t); // Segment Size (in bytes)
2551 unsigned TupleSize = PtrSize * 2;
2553 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2555 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2557 ContentSize += Padding;
2558 ContentSize += (List.size() + 1) * TupleSize;
2560 // For each compile unit, write the list of spans it covers.
2561 Asm->OutStreamer.AddComment("Length of ARange Set");
2562 Asm->EmitInt32(ContentSize);
2563 Asm->OutStreamer.AddComment("DWARF Arange version number");
2564 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2565 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2566 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2567 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2568 Asm->EmitInt8(PtrSize);
2569 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2572 Asm->OutStreamer.EmitFill(Padding, 0xff);
2574 for (const ArangeSpan &Span : List) {
2575 Asm->EmitLabelReference(Span.Start, PtrSize);
2577 // Calculate the size as being from the span start to it's end.
2579 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2581 // For symbols without an end marker (e.g. common), we
2582 // write a single arange entry containing just that one symbol.
2583 uint64_t Size = SymSize[Span.Start];
2587 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2591 Asm->OutStreamer.AddComment("ARange terminator");
2592 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2593 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2597 // Emit visible names into a debug ranges section.
2598 void DwarfDebug::emitDebugRanges() {
2599 // Start the dwarf ranges section.
2600 Asm->OutStreamer.SwitchSection(
2601 Asm->getObjFileLowering().getDwarfRangesSection());
2603 // Size for our labels.
2604 unsigned char Size = Asm->getDataLayout().getPointerSize();
2606 // Grab the specific ranges for the compile units in the module.
2607 for (const auto &I : CUMap) {
2608 DwarfCompileUnit *TheCU = I.second;
2610 // Emit a symbol so we can find the beginning of our ranges.
2611 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2613 // Iterate over the misc ranges for the compile units in the module.
2614 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2615 // Emit our symbol so we can find the beginning of the range.
2616 Asm->OutStreamer.EmitLabel(List.getSym());
2618 for (const RangeSpan &Range : List.getRanges()) {
2619 const MCSymbol *Begin = Range.getStart();
2620 const MCSymbol *End = Range.getEnd();
2621 assert(Begin && "Range without a begin symbol?");
2622 assert(End && "Range without an end symbol?");
2623 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2624 Asm->OutStreamer.EmitSymbolValue(End, Size);
2627 // And terminate the list with two 0 values.
2628 Asm->OutStreamer.EmitIntValue(0, Size);
2629 Asm->OutStreamer.EmitIntValue(0, Size);
2632 // Now emit a range for the CU itself.
2633 if (TheCU->getRanges().size() > 1) {
2634 Asm->OutStreamer.EmitLabel(
2635 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2636 for (const RangeSpan &Range : TheCU->getRanges()) {
2637 const MCSymbol *Begin = Range.getStart();
2638 const MCSymbol *End = Range.getEnd();
2639 assert(Begin && "Range without a begin symbol?");
2640 assert(End && "Range without an end symbol?");
2641 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2642 Asm->OutStreamer.EmitSymbolValue(End, Size);
2644 // And terminate the list with two 0 values.
2645 Asm->OutStreamer.EmitIntValue(0, Size);
2646 Asm->OutStreamer.EmitIntValue(0, Size);
2651 // DWARF5 Experimental Separate Dwarf emitters.
2653 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE *Die,
2654 std::unique_ptr<DwarfUnit> NewU) {
2655 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2656 U.getCUNode().getSplitDebugFilename());
2658 if (!CompilationDir.empty())
2659 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2661 addGnuPubAttributes(*NewU, Die);
2663 SkeletonHolder.addUnit(std::move(NewU));
2666 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2667 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2668 // DW_AT_addr_base, DW_AT_ranges_base.
2669 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2671 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2672 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2673 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2674 DwarfCompileUnit &NewCU = *OwnedUnit;
2675 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2676 DwarfInfoSectionSym);
2678 NewCU.initStmtList(DwarfLineSectionSym);
2680 initSkeletonUnit(CU, Die, std::move(OwnedUnit));
2685 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2687 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2688 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2689 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2691 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2692 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2693 this, &SkeletonHolder);
2694 DwarfTypeUnit &NewTU = *OwnedUnit;
2695 NewTU.setTypeSignature(TU.getTypeSignature());
2696 NewTU.setType(NULL);
2698 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2700 initSkeletonUnit(TU, Die, std::move(OwnedUnit));
2704 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2705 // compile units that would normally be in debug_info.
2706 void DwarfDebug::emitDebugInfoDWO() {
2707 assert(useSplitDwarf() && "No split dwarf debug info?");
2708 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2709 // emit relocations into the dwo file.
2710 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2713 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2714 // abbreviations for the .debug_info.dwo section.
2715 void DwarfDebug::emitDebugAbbrevDWO() {
2716 assert(useSplitDwarf() && "No split dwarf?");
2717 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2720 void DwarfDebug::emitDebugLineDWO() {
2721 assert(useSplitDwarf() && "No split dwarf?");
2722 Asm->OutStreamer.SwitchSection(
2723 Asm->getObjFileLowering().getDwarfLineDWOSection());
2724 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2727 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2728 // string section and is identical in format to traditional .debug_str
2730 void DwarfDebug::emitDebugStrDWO() {
2731 assert(useSplitDwarf() && "No split dwarf?");
2732 const MCSection *OffSec =
2733 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2734 const MCSymbol *StrSym = DwarfStrSectionSym;
2735 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2739 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2740 if (!useSplitDwarf())
2743 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2744 return &SplitTypeUnitFileTable;
2747 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2748 StringRef Identifier, DIE *RefDie,
2749 DICompositeType CTy) {
2750 // Flag the type unit reference as a declaration so that if it contains
2751 // members (implicit special members, static data member definitions, member
2752 // declarations for definitions in this CU, etc) consumers don't get confused
2753 // and think this is a full definition.
2754 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2756 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2758 CU.addDIETypeSignature(RefDie, *TU);
2762 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2764 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2765 this, &InfoHolder, getDwoLineTable(CU));
2766 DwarfTypeUnit &NewTU = *OwnedUnit;
2768 InfoHolder.addUnit(std::move(OwnedUnit));
2770 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2774 Hash.update(Identifier);
2775 // ... take the least significant 8 bytes and return those. Our MD5
2776 // implementation always returns its results in little endian, swap bytes
2778 MD5::MD5Result Result;
2780 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2781 NewTU.setTypeSignature(Signature);
2782 if (useSplitDwarf())
2783 NewTU.setSkeleton(constructSkeletonTU(NewTU));
2785 CU.applyStmtList(*UnitDie);
2787 NewTU.setType(NewTU.createTypeDIE(CTy));
2791 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2792 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2794 CU.addDIETypeSignature(RefDie, NewTU);
2797 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE *D,
2798 MCSymbol *Begin, MCSymbol *End) {
2799 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2800 if (DwarfVersion < 4)
2801 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2803 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);