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 #define DEBUG_TYPE "dwarfdebug"
15 #include "ByteStreamer.h"
16 #include "DwarfDebug.h"
19 #include "DwarfAccelTable.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/LEB128.h"
44 #include "llvm/Support/MD5.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
63 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
64 cl::desc("Add the CU hash as the dwo_id."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static cl::opt<unsigned>
106 DwarfVersionNumber("dwarf-version", cl::Hidden,
107 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
110 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
111 cl::desc("Generate DW_AT_ranges for compile units"),
114 static const char *const DWARFGroupName = "DWARF Emission";
115 static const char *const DbgTimerName = "DWARF Debug Writer";
117 //===----------------------------------------------------------------------===//
121 /// resolve - Look in the DwarfDebug map for the MDNode that
122 /// corresponds to the reference.
123 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
124 return DD->resolve(Ref);
127 DIType DbgVariable::getType() const {
128 DIType Ty = Var.getType();
129 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
130 // addresses instead.
131 if (Var.isBlockByrefVariable()) {
132 /* Byref variables, in Blocks, are declared by the programmer as
133 "SomeType VarName;", but the compiler creates a
134 __Block_byref_x_VarName struct, and gives the variable VarName
135 either the struct, or a pointer to the struct, as its type. This
136 is necessary for various behind-the-scenes things the compiler
137 needs to do with by-reference variables in blocks.
139 However, as far as the original *programmer* is concerned, the
140 variable should still have type 'SomeType', as originally declared.
142 The following function dives into the __Block_byref_x_VarName
143 struct to find the original type of the variable. This will be
144 passed back to the code generating the type for the Debug
145 Information Entry for the variable 'VarName'. 'VarName' will then
146 have the original type 'SomeType' in its debug information.
148 The original type 'SomeType' will be the type of the field named
149 'VarName' inside the __Block_byref_x_VarName struct.
151 NOTE: In order for this to not completely fail on the debugger
152 side, the Debug Information Entry for the variable VarName needs to
153 have a DW_AT_location that tells the debugger how to unwind through
154 the pointers and __Block_byref_x_VarName struct to find the actual
155 value of the variable. The function addBlockByrefType does this. */
157 uint16_t tag = Ty.getTag();
159 if (tag == dwarf::DW_TAG_pointer_type)
160 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
162 DIArray Elements = DICompositeType(subType).getTypeArray();
163 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
164 DIDerivedType DT(Elements.getElement(i));
165 if (getName() == DT.getName())
166 return (resolve(DT.getTypeDerivedFrom()));
172 } // end llvm namespace
174 /// Return Dwarf Version by checking module flags.
175 static unsigned getDwarfVersionFromModule(const Module *M) {
176 Value *Val = M->getModuleFlag("Dwarf Version");
178 return dwarf::DWARF_VERSION;
179 return cast<ConstantInt>(Val)->getZExtValue();
182 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
183 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
184 PrevLabel(NULL), GlobalRangeCount(0),
185 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
186 UsedNonDefaultText(false),
187 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
189 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
190 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
191 DwarfAddrSectionSym = 0;
192 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
193 FunctionBeginSym = FunctionEndSym = 0;
197 // Turn on accelerator tables for Darwin by default, pubnames by
198 // default for non-Darwin, and handle split dwarf.
199 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
201 if (DwarfAccelTables == Default)
202 HasDwarfAccelTables = IsDarwin;
204 HasDwarfAccelTables = DwarfAccelTables == Enable;
206 if (SplitDwarf == Default)
207 HasSplitDwarf = false;
209 HasSplitDwarf = SplitDwarf == Enable;
211 if (DwarfPubSections == Default)
212 HasDwarfPubSections = !IsDarwin;
214 HasDwarfPubSections = DwarfPubSections == Enable;
216 DwarfVersion = DwarfVersionNumber
218 : getDwarfVersionFromModule(MMI->getModule());
221 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = 0) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 DwarfFile::~DwarfFile() {
240 for (DwarfUnit *DU : CUs)
244 MCSymbol *DwarfFile::getStringPoolSym() {
245 return Asm->GetTempSymbol(StringPref);
248 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
249 std::pair<MCSymbol *, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
254 Entry.second = NextStringPoolNumber++;
255 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
259 std::pair<MCSymbol *, unsigned> &Entry =
260 StringPool.GetOrCreateValue(Str).getValue();
264 Entry.second = NextStringPoolNumber++;
265 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
269 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
270 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
271 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
273 ++NextAddrPoolNumber;
274 return P.first->second.Number;
277 // Define a unique number for the abbreviation.
279 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
280 // Check the set for priors.
281 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
283 // If it's newly added.
284 if (InSet == &Abbrev) {
285 // Add to abbreviation list.
286 Abbreviations.push_back(&Abbrev);
288 // Assign the vector position + 1 as its number.
289 Abbrev.setNumber(Abbreviations.size());
291 // Assign existing abbreviation number.
292 Abbrev.setNumber(InSet->getNumber());
296 static bool isObjCClass(StringRef Name) {
297 return Name.startswith("+") || Name.startswith("-");
300 static bool hasObjCCategory(StringRef Name) {
301 if (!isObjCClass(Name))
304 return Name.find(") ") != StringRef::npos;
307 static void getObjCClassCategory(StringRef In, StringRef &Class,
308 StringRef &Category) {
309 if (!hasObjCCategory(In)) {
310 Class = In.slice(In.find('[') + 1, In.find(' '));
315 Class = In.slice(In.find('[') + 1, In.find('('));
316 Category = In.slice(In.find('[') + 1, In.find(' '));
320 static StringRef getObjCMethodName(StringRef In) {
321 return In.slice(In.find(' ') + 1, In.find(']'));
324 // Helper for sorting sections into a stable output order.
325 static bool SectionSort(const MCSection *A, const MCSection *B) {
326 std::string LA = (A ? A->getLabelBeginName() : "");
327 std::string LB = (B ? B->getLabelBeginName() : "");
331 // Add the various names to the Dwarf accelerator table names.
332 // TODO: Determine whether or not we should add names for programs
333 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
334 // is only slightly different than the lookup of non-standard ObjC names.
335 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
336 if (!SP.isDefinition())
338 TheU->addAccelName(SP.getName(), Die);
340 // If the linkage name is different than the name, go ahead and output
341 // that as well into the name table.
342 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
343 TheU->addAccelName(SP.getLinkageName(), Die);
345 // If this is an Objective-C selector name add it to the ObjC accelerator
347 if (isObjCClass(SP.getName())) {
348 StringRef Class, Category;
349 getObjCClassCategory(SP.getName(), Class, Category);
350 TheU->addAccelObjC(Class, Die);
352 TheU->addAccelObjC(Category, Die);
353 // Also add the base method name to the name table.
354 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
358 /// isSubprogramContext - Return true if Context is either a subprogram
359 /// or another context nested inside a subprogram.
360 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
363 DIDescriptor D(Context);
364 if (D.isSubprogram())
367 return isSubprogramContext(resolve(DIType(Context).getContext()));
371 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
372 // and DW_AT_high_pc attributes. If there are global variables in this
373 // scope then create and insert DIEs for these variables.
374 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
376 DIE *SPDie = SPCU->getDIE(SP);
378 assert(SPDie && "Unable to find subprogram DIE!");
380 // If we're updating an abstract DIE, then we will be adding the children and
381 // object pointer later on. But what we don't want to do is process the
382 // concrete DIE twice.
383 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
384 // Pick up abstract subprogram DIE.
386 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
387 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
389 DISubprogram SPDecl = SP.getFunctionDeclaration();
390 if (!SPDecl.isSubprogram()) {
391 // There is not any need to generate specification DIE for a function
392 // defined at compile unit level. If a function is defined inside another
393 // function then gdb prefers the definition at top level and but does not
394 // expect specification DIE in parent function. So avoid creating
395 // specification DIE for a function defined inside a function.
396 DIScope SPContext = resolve(SP.getContext());
397 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
398 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
399 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
402 DICompositeType SPTy = SP.getType();
403 DIArray Args = SPTy.getTypeArray();
404 uint16_t SPTag = SPTy.getTag();
405 if (SPTag == dwarf::DW_TAG_subroutine_type)
406 SPCU->constructSubprogramArguments(*SPDie, Args);
407 DIE *SPDeclDie = SPDie;
408 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
409 *SPCU->getUnitDie());
410 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
415 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
417 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
418 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
419 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
421 // Add name to the name table, we do this here because we're guaranteed
422 // to have concrete versions of our DW_TAG_subprogram nodes.
423 addSubprogramNames(SPCU, SP, SPDie);
428 /// Check whether we should create a DIE for the given Scope, return true
429 /// if we don't create a DIE (the corresponding DIE is null).
430 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
431 if (Scope->isAbstractScope())
434 // We don't create a DIE if there is no Range.
435 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
439 if (Ranges.size() > 1)
442 // We don't create a DIE if we have a single Range and the end label
444 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
445 MCSymbol *End = getLabelAfterInsn(RI->second);
449 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
450 dwarf::Attribute A, const MCSymbol *L,
451 const MCSymbol *Sec) {
452 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
453 U->addSectionLabel(D, A, L);
455 U->addSectionDelta(D, A, L, Sec);
458 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
459 const SmallVectorImpl<InsnRange> &Range) {
460 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
461 // emitting it appropriately.
462 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
463 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
464 DwarfDebugRangeSectionSym);
466 RangeSpanList List(RangeSym);
467 for (const InsnRange &R : Range) {
468 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
469 List.addRange(std::move(Span));
472 // Add the range list to the set of ranges to be emitted.
473 TheCU->addRangeList(std::move(List));
476 // Construct new DW_TAG_lexical_block for this scope and attach
477 // DW_AT_low_pc/DW_AT_high_pc labels.
478 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
479 LexicalScope *Scope) {
480 if (isLexicalScopeDIENull(Scope))
483 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
484 if (Scope->isAbstractScope())
487 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
489 // If we have multiple ranges, emit them into the range section.
490 if (ScopeRanges.size() > 1) {
491 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
495 // Construct the address range for this DIE.
496 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
497 MCSymbol *Start = getLabelBeforeInsn(RI->first);
498 MCSymbol *End = getLabelAfterInsn(RI->second);
499 assert(End && "End label should not be null!");
501 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
502 assert(End->isDefined() && "Invalid end label for an inlined scope!");
504 attachLowHighPC(TheCU, ScopeDIE, Start, End);
509 // This scope represents inlined body of a function. Construct DIE to
510 // represent this concrete inlined copy of the function.
511 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
512 LexicalScope *Scope) {
513 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
514 assert(!ScopeRanges.empty() &&
515 "LexicalScope does not have instruction markers!");
517 if (!Scope->getScopeNode())
519 DIScope DS(Scope->getScopeNode());
520 DISubprogram InlinedSP = getDISubprogram(DS);
521 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
523 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
527 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
528 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
530 // If we have multiple ranges, emit them into the range section.
531 if (ScopeRanges.size() > 1)
532 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
534 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
535 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
536 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
538 if (StartLabel == 0 || EndLabel == 0)
539 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
541 assert(StartLabel->isDefined() &&
542 "Invalid starting label for an inlined scope!");
543 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
545 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
548 InlinedSubprogramDIEs.insert(OriginDIE);
550 // Add the call site information to the DIE.
551 DILocation DL(Scope->getInlinedAt());
552 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
553 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
554 TheCU->getUniqueID()));
555 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
557 // Add name to the name table, we do this here because we're guaranteed
558 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
559 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
564 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
566 SmallVectorImpl<DIE *> &Children) {
567 DIE *ObjectPointer = NULL;
569 // Collect arguments for current function.
570 if (LScopes.isCurrentFunctionScope(Scope)) {
571 for (DbgVariable *ArgDV : CurrentFnArguments)
574 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
575 Children.push_back(Arg);
576 if (ArgDV->isObjectPointer())
580 // If this is a variadic function, add an unspecified parameter.
581 DISubprogram SP(Scope->getScopeNode());
582 DIArray FnArgs = SP.getType().getTypeArray();
583 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
584 .isUnspecifiedParameter()) {
585 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
586 Children.push_back(Ellipsis);
590 // Collect lexical scope children first.
591 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
592 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
593 Scope->isAbstractScope())) {
594 Children.push_back(Variable);
595 if (DV->isObjectPointer())
596 ObjectPointer = Variable;
598 for (LexicalScope *LS : Scope->getChildren())
599 if (DIE *Nested = constructScopeDIE(TheCU, LS))
600 Children.push_back(Nested);
601 return ObjectPointer;
604 // Construct a DIE for this scope.
605 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
606 LexicalScope *Scope) {
607 if (!Scope || !Scope->getScopeNode())
610 DIScope DS(Scope->getScopeNode());
612 SmallVector<DIE *, 8> Children;
613 DIE *ObjectPointer = NULL;
614 bool ChildrenCreated = false;
616 // We try to create the scope DIE first, then the children DIEs. This will
617 // avoid creating un-used children then removing them later when we find out
618 // the scope DIE is null.
619 DIE *ScopeDIE = NULL;
620 if (Scope->getInlinedAt())
621 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
622 else if (DS.isSubprogram()) {
623 ProcessedSPNodes.insert(DS);
624 if (Scope->isAbstractScope()) {
625 ScopeDIE = TheCU->getDIE(DS);
626 // Note down abstract DIE.
628 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
630 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
632 // Early exit when we know the scope DIE is going to be null.
633 if (isLexicalScopeDIENull(Scope))
636 // We create children here when we know the scope DIE is not going to be
637 // null and the children will be added to the scope DIE.
638 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
639 ChildrenCreated = true;
641 // There is no need to emit empty lexical block DIE.
642 std::pair<ImportedEntityMap::const_iterator,
643 ImportedEntityMap::const_iterator> Range =
645 ScopesWithImportedEntities.begin(),
646 ScopesWithImportedEntities.end(),
647 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
649 if (Children.empty() && Range.first == Range.second)
651 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
652 assert(ScopeDIE && "Scope DIE should not be null.");
653 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
655 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
659 assert(Children.empty() &&
660 "We create children only when the scope DIE is not null.");
663 if (!ChildrenCreated)
664 // We create children when the scope DIE is not null.
665 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
668 for (DIE *I : Children)
669 ScopeDIE->addChild(I);
671 if (DS.isSubprogram() && ObjectPointer != NULL)
672 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
677 // Look up the source id with the given directory and source file names.
678 // If none currently exists, create a new id and insert it in the
679 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
681 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
683 // If we print assembly, we can't separate .file entries according to
684 // compile units. Thus all files will belong to the default compile unit.
686 // FIXME: add a better feature test than hasRawTextSupport. Even better,
687 // extend .file to support this.
688 if (Asm->OutStreamer.hasRawTextSupport())
691 // If FE did not provide a file name, then assume stdin.
692 if (FileName.empty())
693 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
695 // TODO: this might not belong here. See if we can factor this better.
696 if (DirName == CompilationDir)
699 // FileIDCUMap stores the current ID for the given compile unit.
700 unsigned SrcId = FileIDCUMap[CUID] + 1;
702 // We look up the CUID/file/dir by concatenating them with a zero byte.
703 SmallString<128> NamePair;
704 NamePair += utostr(CUID);
707 NamePair += '\0'; // Zero bytes are not allowed in paths.
708 NamePair += FileName;
710 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
711 if (Ent.getValue() != SrcId)
712 return Ent.getValue();
714 FileIDCUMap[CUID] = SrcId;
715 // Print out a .file directive to specify files for .loc directives.
716 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
721 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
722 if (!GenerateGnuPubSections)
725 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
728 // Create new DwarfCompileUnit for the given metadata node with tag
729 // DW_TAG_compile_unit.
730 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
731 StringRef FN = DIUnit.getFilename();
732 CompilationDir = DIUnit.getDirectory();
734 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
735 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
736 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
737 InfoHolder.addUnit(NewCU);
739 FileIDCUMap[NewCU->getUniqueID()] = 0;
741 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
742 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
743 DIUnit.getLanguage());
744 NewCU->addString(Die, dwarf::DW_AT_name, FN);
746 if (!useSplitDwarf()) {
747 NewCU->initStmtList(DwarfLineSectionSym);
749 // If we're using split dwarf the compilation dir is going to be in the
750 // skeleton CU and so we don't need to duplicate it here.
751 if (!CompilationDir.empty())
752 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
754 addGnuPubAttributes(NewCU, Die);
757 if (DIUnit.isOptimized())
758 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
760 StringRef Flags = DIUnit.getFlags();
762 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
764 if (unsigned RVer = DIUnit.getRunTimeVersion())
765 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
766 dwarf::DW_FORM_data1, RVer);
771 if (useSplitDwarf()) {
772 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
773 DwarfInfoDWOSectionSym);
774 NewCU->setSkeleton(constructSkeletonCU(NewCU));
776 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
777 DwarfInfoSectionSym);
779 CUMap.insert(std::make_pair(DIUnit, NewCU));
780 CUDieMap.insert(std::make_pair(Die, NewCU));
784 // Construct subprogram DIE.
785 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
787 // FIXME: We should only call this routine once, however, during LTO if a
788 // program is defined in multiple CUs we could end up calling it out of
789 // beginModule as we walk the CUs.
791 DwarfCompileUnit *&CURef = SPMap[N];
797 if (!SP.isDefinition())
798 // This is a method declaration which will be handled while constructing
802 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
804 // Expose as a global name.
805 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
808 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
810 DIImportedEntity Module(N);
811 assert(Module.Verify());
812 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
813 constructImportedEntityDIE(TheCU, Module, D);
816 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
817 const MDNode *N, DIE *Context) {
818 DIImportedEntity Module(N);
819 assert(Module.Verify());
820 return constructImportedEntityDIE(TheCU, Module, Context);
823 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
824 const DIImportedEntity &Module,
826 assert(Module.Verify() &&
827 "Use one of the MDNode * overloads to handle invalid metadata");
828 assert(Context && "Should always have a context for an imported_module");
829 DIE *IMDie = new DIE(Module.getTag());
830 TheCU->insertDIE(Module, IMDie);
832 DIDescriptor Entity = Module.getEntity();
833 if (Entity.isNameSpace())
834 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
835 else if (Entity.isSubprogram())
836 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
837 else if (Entity.isType())
838 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
840 EntityDie = TheCU->getDIE(Entity);
841 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
842 Module.getContext().getDirectory(),
843 TheCU->getUniqueID());
844 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
845 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
846 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
847 StringRef Name = Module.getName();
849 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
850 Context->addChild(IMDie);
853 // Emit all Dwarf sections that should come prior to the content. Create
854 // global DIEs and emit initial debug info sections. This is invoked by
855 // the target AsmPrinter.
856 void DwarfDebug::beginModule() {
857 if (DisableDebugInfoPrinting)
860 const Module *M = MMI->getModule();
862 // If module has named metadata anchors then use them, otherwise scan the
863 // module using debug info finder to collect debug info.
864 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
867 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
869 // Emit initial sections so we can reference labels later.
872 for (MDNode *N : CU_Nodes->operands()) {
873 DICompileUnit CUNode(N);
874 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
875 DIArray ImportedEntities = CUNode.getImportedEntities();
876 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
877 ScopesWithImportedEntities.push_back(std::make_pair(
878 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
879 ImportedEntities.getElement(i)));
880 std::sort(ScopesWithImportedEntities.begin(),
881 ScopesWithImportedEntities.end(), less_first());
882 DIArray GVs = CUNode.getGlobalVariables();
883 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
884 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
885 DIArray SPs = CUNode.getSubprograms();
886 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
887 constructSubprogramDIE(CU, SPs.getElement(i));
888 DIArray EnumTypes = CUNode.getEnumTypes();
889 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
890 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
891 DIArray RetainedTypes = CUNode.getRetainedTypes();
892 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
893 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
894 // Emit imported_modules last so that the relevant context is already
896 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
897 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
900 // Tell MMI that we have debug info.
901 MMI->setDebugInfoAvailability(true);
903 // Prime section data.
904 SectionMap[Asm->getObjFileLowering().getTextSection()];
907 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
908 void DwarfDebug::computeInlinedDIEs() {
909 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
910 for (DIE *ISP : InlinedSubprogramDIEs)
911 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
913 for (const auto &AI : AbstractSPDies) {
914 DIE *ISP = AI.second;
915 if (InlinedSubprogramDIEs.count(ISP))
917 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
921 // Collect info for variables that were optimized out.
922 void DwarfDebug::collectDeadVariables() {
923 const Module *M = MMI->getModule();
925 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
926 for (MDNode *N : CU_Nodes->operands()) {
927 DICompileUnit TheCU(N);
928 DIArray Subprograms = TheCU.getSubprograms();
929 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
930 DISubprogram SP(Subprograms.getElement(i));
931 if (ProcessedSPNodes.count(SP) != 0)
933 if (!SP.isSubprogram())
935 if (!SP.isDefinition())
937 DIArray Variables = SP.getVariables();
938 if (Variables.getNumElements() == 0)
941 // Construct subprogram DIE and add variables DIEs.
942 DwarfCompileUnit *SPCU =
943 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
944 assert(SPCU && "Unable to find Compile Unit!");
945 // FIXME: See the comment in constructSubprogramDIE about duplicate
947 constructSubprogramDIE(SPCU, SP);
948 DIE *SPDIE = SPCU->getDIE(SP);
949 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
950 DIVariable DV(Variables.getElement(vi));
951 if (!DV.isVariable())
953 DbgVariable NewVar(DV, NULL, this);
954 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
955 SPDIE->addChild(VariableDIE);
962 void DwarfDebug::finalizeModuleInfo() {
963 // Collect info for variables that were optimized out.
964 collectDeadVariables();
966 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
967 computeInlinedDIEs();
969 // Handle anything that needs to be done on a per-unit basis after
970 // all other generation.
971 for (DwarfUnit *TheU : getUnits()) {
972 // Emit DW_AT_containing_type attribute to connect types with their
973 // vtable holding type.
974 TheU->constructContainingTypeDIEs();
976 // Add CU specific attributes if we need to add any.
977 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
978 // If we're splitting the dwarf out now that we've got the entire
979 // CU then add the dwo id to it.
980 DwarfCompileUnit *SkCU =
981 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
982 if (useSplitDwarf()) {
983 // This should be a unique identifier when we want to build .dwp files.
985 if (GenerateCUHash) {
987 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
989 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
990 dwarf::DW_FORM_data8, ID);
991 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
992 dwarf::DW_FORM_data8, ID);
995 // If we have code split among multiple sections or we've requested
996 // it then emit a DW_AT_ranges attribute on the unit that will remain
997 // in the .o file, otherwise add a DW_AT_low_pc.
998 // FIXME: Also add a high pc if we can.
999 // FIXME: We should use ranges if we have multiple compile units or
1000 // allow reordering of code ala .subsections_via_symbols in mach-o.
1001 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1002 if (useCURanges() && TheU->getRanges().size()) {
1003 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1004 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1005 DwarfDebugRangeSectionSym);
1007 // A DW_AT_low_pc attribute may also be specified in combination with
1008 // DW_AT_ranges to specify the default base address for use in location
1009 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1010 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1013 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1018 // Compute DIE offsets and sizes.
1019 InfoHolder.computeSizeAndOffsets();
1020 if (useSplitDwarf())
1021 SkeletonHolder.computeSizeAndOffsets();
1024 void DwarfDebug::endSections() {
1025 // Filter labels by section.
1026 for (const SymbolCU &SCU : ArangeLabels) {
1027 if (SCU.Sym->isInSection()) {
1028 // Make a note of this symbol and it's section.
1029 const MCSection *Section = &SCU.Sym->getSection();
1030 if (!Section->getKind().isMetadata())
1031 SectionMap[Section].push_back(SCU);
1033 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1034 // appear in the output. This sucks as we rely on sections to build
1035 // arange spans. We can do it without, but it's icky.
1036 SectionMap[NULL].push_back(SCU);
1040 // Build a list of sections used.
1041 std::vector<const MCSection *> Sections;
1042 for (const auto &it : SectionMap) {
1043 const MCSection *Section = it.first;
1044 Sections.push_back(Section);
1047 // Sort the sections into order.
1048 // This is only done to ensure consistent output order across different runs.
1049 std::sort(Sections.begin(), Sections.end(), SectionSort);
1051 // Add terminating symbols for each section.
1052 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1053 const MCSection *Section = Sections[ID];
1054 MCSymbol *Sym = NULL;
1057 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1058 // if we know the section name up-front. For user-created sections, the
1059 // resulting label may not be valid to use as a label. (section names can
1060 // use a greater set of characters on some systems)
1061 Sym = Asm->GetTempSymbol("debug_end", ID);
1062 Asm->OutStreamer.SwitchSection(Section);
1063 Asm->OutStreamer.EmitLabel(Sym);
1066 // Insert a final terminator.
1067 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1070 // For now only turn on CU ranges if we've explicitly asked for it,
1071 // we have -ffunction-sections enabled, we've emitted a function
1072 // into a unique section, or we're using LTO. If we're using LTO then
1073 // we can't know that any particular function in the module is correlated
1074 // to a particular CU and so we need to be conservative. At this point all
1075 // sections should be finalized except for dwarf sections.
1076 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1077 TargetMachine::getFunctionSections();
1080 // Emit all Dwarf sections that should come after the content.
1081 void DwarfDebug::endModule() {
1088 // End any existing sections.
1089 // TODO: Does this need to happen?
1092 // Finalize the debug info for the module.
1093 finalizeModuleInfo();
1097 // Emit all the DIEs into a debug info section.
1100 // Corresponding abbreviations into a abbrev section.
1101 emitAbbreviations();
1103 // Emit info into a debug loc section.
1106 // Emit info into a debug aranges section.
1107 if (GenerateARangeSection)
1110 // Emit info into a debug ranges section.
1113 if (useSplitDwarf()) {
1116 emitDebugAbbrevDWO();
1117 // Emit DWO addresses.
1118 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1121 // Emit info into the dwarf accelerator table sections.
1122 if (useDwarfAccelTables()) {
1125 emitAccelNamespaces();
1129 // Emit the pubnames and pubtypes sections if requested.
1130 if (HasDwarfPubSections) {
1131 emitDebugPubNames(GenerateGnuPubSections);
1132 emitDebugPubTypes(GenerateGnuPubSections);
1138 // Reset these for the next Module if we have one.
1142 // Find abstract variable, if any, associated with Var.
1143 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1144 DebugLoc ScopeLoc) {
1145 LLVMContext &Ctx = DV->getContext();
1146 // More then one inlined variable corresponds to one abstract variable.
1147 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1148 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1150 return AbsDbgVariable;
1152 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1156 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1157 addScopeVariable(Scope, AbsDbgVariable);
1158 AbstractVariables[Var] = AbsDbgVariable;
1159 return AbsDbgVariable;
1162 // If Var is a current function argument then add it to CurrentFnArguments list.
1163 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1164 if (!LScopes.isCurrentFunctionScope(Scope))
1166 DIVariable DV = Var->getVariable();
1167 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1169 unsigned ArgNo = DV.getArgNumber();
1173 size_t Size = CurrentFnArguments.size();
1175 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1176 // llvm::Function argument size is not good indicator of how many
1177 // arguments does the function have at source level.
1179 CurrentFnArguments.resize(ArgNo * 2);
1180 CurrentFnArguments[ArgNo - 1] = Var;
1184 // Collect variable information from side table maintained by MMI.
1185 void DwarfDebug::collectVariableInfoFromMMITable(
1186 SmallPtrSet<const MDNode *, 16> &Processed) {
1187 for (const auto &VI : MMI->getVariableDbgInfo()) {
1188 const MDNode *Var = VI.first;
1191 Processed.insert(Var);
1193 const std::pair<unsigned, DebugLoc> &VP = VI.second;
1195 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1197 // If variable scope is not found then skip this variable.
1201 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1202 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1203 RegVar->setFrameIndex(VP.first);
1204 if (!addCurrentFnArgument(RegVar, Scope))
1205 addScopeVariable(Scope, RegVar);
1207 AbsDbgVariable->setFrameIndex(VP.first);
1211 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1213 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1214 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1215 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1216 MI->getOperand(0).getReg() &&
1217 (MI->getOperand(1).isImm() ||
1218 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1221 // Get .debug_loc entry for the instruction range starting at MI.
1222 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1223 const MCSymbol *FLabel,
1224 const MCSymbol *SLabel,
1225 const MachineInstr *MI) {
1226 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1228 assert(MI->getNumOperands() == 3);
1229 if (MI->getOperand(0).isReg()) {
1230 MachineLocation MLoc;
1231 // If the second operand is an immediate, this is a
1232 // register-indirect address.
1233 if (!MI->getOperand(1).isImm())
1234 MLoc.set(MI->getOperand(0).getReg());
1236 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1237 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1239 if (MI->getOperand(0).isImm())
1240 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1241 if (MI->getOperand(0).isFPImm())
1242 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1243 if (MI->getOperand(0).isCImm())
1244 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1246 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1249 // Find variables for each lexical scope.
1251 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1253 // Grab the variable info that was squirreled away in the MMI side-table.
1254 collectVariableInfoFromMMITable(Processed);
1256 for (const MDNode *Var : UserVariables) {
1257 if (Processed.count(Var))
1260 // History contains relevant DBG_VALUE instructions for Var and instructions
1262 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1263 if (History.empty())
1265 const MachineInstr *MInsn = History.front();
1268 LexicalScope *Scope = NULL;
1269 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1270 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1271 Scope = LScopes.getCurrentFunctionScope();
1272 else if (MDNode *IA = DV.getInlinedAt())
1273 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1275 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1276 // If variable scope is not found then skip this variable.
1280 Processed.insert(DV);
1281 assert(MInsn->isDebugValue() && "History must begin with debug value");
1282 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1283 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1284 if (!addCurrentFnArgument(RegVar, Scope))
1285 addScopeVariable(Scope, RegVar);
1287 AbsVar->setMInsn(MInsn);
1289 // Simplify ranges that are fully coalesced.
1290 if (History.size() <= 1 ||
1291 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1292 RegVar->setMInsn(MInsn);
1296 // Handle multiple DBG_VALUE instructions describing one variable.
1297 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1299 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1300 HI = History.begin(),
1303 const MachineInstr *Begin = *HI;
1304 assert(Begin->isDebugValue() && "Invalid History entry");
1306 // Check if DBG_VALUE is truncating a range.
1307 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1308 !Begin->getOperand(0).getReg())
1311 // Compute the range for a register location.
1312 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1313 const MCSymbol *SLabel = 0;
1316 // If Begin is the last instruction in History then its value is valid
1317 // until the end of the function.
1318 SLabel = FunctionEndSym;
1320 const MachineInstr *End = HI[1];
1321 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1322 << "\t" << *Begin << "\t" << *End << "\n");
1323 if (End->isDebugValue())
1324 SLabel = getLabelBeforeInsn(End);
1326 // End is a normal instruction clobbering the range.
1327 SLabel = getLabelAfterInsn(End);
1328 assert(SLabel && "Forgot label after clobber instruction");
1333 // The value is valid until the next DBG_VALUE or clobber.
1334 DotDebugLocEntries.push_back(
1335 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1337 DotDebugLocEntries.push_back(DotDebugLocEntry());
1340 // Collect info for variables that were optimized out.
1341 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1342 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1343 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1344 DIVariable DV(Variables.getElement(i));
1345 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1347 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1348 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1352 // Return Label preceding the instruction.
1353 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1354 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1355 assert(Label && "Didn't insert label before instruction");
1359 // Return Label immediately following the instruction.
1360 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1361 return LabelsAfterInsn.lookup(MI);
1364 // Process beginning of an instruction.
1365 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1368 // Check if source location changes, but ignore DBG_VALUE locations.
1369 if (!MI->isDebugValue()) {
1370 DebugLoc DL = MI->getDebugLoc();
1371 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1374 if (DL == PrologEndLoc) {
1375 Flags |= DWARF2_FLAG_PROLOGUE_END;
1376 PrologEndLoc = DebugLoc();
1378 if (PrologEndLoc.isUnknown())
1379 Flags |= DWARF2_FLAG_IS_STMT;
1381 if (!DL.isUnknown()) {
1382 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1383 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1385 recordSourceLine(0, 0, 0, 0);
1389 // Insert labels where requested.
1390 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1391 LabelsBeforeInsn.find(MI);
1394 if (I == LabelsBeforeInsn.end())
1397 // Label already assigned.
1402 PrevLabel = MMI->getContext().CreateTempSymbol();
1403 Asm->OutStreamer.EmitLabel(PrevLabel);
1405 I->second = PrevLabel;
1408 // Process end of an instruction.
1409 void DwarfDebug::endInstruction() {
1411 // Don't create a new label after DBG_VALUE instructions.
1412 // They don't generate code.
1413 if (!CurMI->isDebugValue())
1416 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1417 LabelsAfterInsn.find(CurMI);
1421 if (I == LabelsAfterInsn.end())
1424 // Label already assigned.
1428 // We need a label after this instruction.
1430 PrevLabel = MMI->getContext().CreateTempSymbol();
1431 Asm->OutStreamer.EmitLabel(PrevLabel);
1433 I->second = PrevLabel;
1436 // Each LexicalScope has first instruction and last instruction to mark
1437 // beginning and end of a scope respectively. Create an inverse map that list
1438 // scopes starts (and ends) with an instruction. One instruction may start (or
1439 // end) multiple scopes. Ignore scopes that are not reachable.
1440 void DwarfDebug::identifyScopeMarkers() {
1441 SmallVector<LexicalScope *, 4> WorkList;
1442 WorkList.push_back(LScopes.getCurrentFunctionScope());
1443 while (!WorkList.empty()) {
1444 LexicalScope *S = WorkList.pop_back_val();
1446 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1447 if (!Children.empty())
1448 WorkList.append(Children.begin(), Children.end());
1450 if (S->isAbstractScope())
1453 for (const InsnRange &R : S->getRanges()) {
1454 assert(R.first && "InsnRange does not have first instruction!");
1455 assert(R.second && "InsnRange does not have second instruction!");
1456 requestLabelBeforeInsn(R.first);
1457 requestLabelAfterInsn(R.second);
1462 // Gather pre-function debug information. Assumes being called immediately
1463 // after the function entry point has been emitted.
1464 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1467 // If there's no debug info for the function we're not going to do anything.
1468 if (!MMI->hasDebugInfo())
1471 // Grab the lexical scopes for the function, if we don't have any of those
1472 // then we're not going to be able to do anything.
1473 LScopes.initialize(*MF);
1474 if (LScopes.empty())
1477 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1479 // Make sure that each lexical scope will have a begin/end label.
1480 identifyScopeMarkers();
1482 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1483 // belongs to so that we add to the correct per-cu line table in the
1485 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1486 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1487 assert(TheCU && "Unable to find compile unit!");
1488 if (Asm->OutStreamer.hasRawTextSupport())
1489 // Use a single line table if we are generating assembly.
1490 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1492 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1494 // Check the current section against the standard text section. If different
1495 // keep track so that we will know when we're emitting functions into multiple
1497 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1498 UsedNonDefaultText = true;
1500 // Emit a label for the function so that we have a beginning address.
1501 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1502 // Assumes in correct section after the entry point.
1503 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1505 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1506 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1507 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1509 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1511 bool AtBlockEntry = true;
1512 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1514 const MachineInstr *MI = II;
1516 if (MI->isDebugValue()) {
1517 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1519 // Keep track of user variables.
1521 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1523 // Variable is in a register, we need to check for clobbers.
1524 if (isDbgValueInDefinedReg(MI))
1525 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1527 // Check the history of this variable.
1528 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1529 if (History.empty()) {
1530 UserVariables.push_back(Var);
1531 // The first mention of a function argument gets the FunctionBeginSym
1532 // label, so arguments are visible when breaking at function entry.
1534 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1535 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1536 LabelsBeforeInsn[MI] = FunctionBeginSym;
1538 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1539 const MachineInstr *Prev = History.back();
1540 if (Prev->isDebugValue()) {
1541 // Coalesce identical entries at the end of History.
1542 if (History.size() >= 2 &&
1543 Prev->isIdenticalTo(History[History.size() - 2])) {
1544 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1545 << "\t" << *Prev << "\t"
1546 << *History[History.size() - 2] << "\n");
1550 // Terminate old register assignments that don't reach MI;
1551 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1552 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1553 isDbgValueInDefinedReg(Prev)) {
1554 // Previous register assignment needs to terminate at the end of
1556 MachineBasicBlock::const_iterator LastMI =
1557 PrevMBB->getLastNonDebugInstr();
1558 if (LastMI == PrevMBB->end()) {
1559 // Drop DBG_VALUE for empty range.
1560 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1561 << "\t" << *Prev << "\n");
1563 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1564 // Terminate after LastMI.
1565 History.push_back(LastMI);
1569 History.push_back(MI);
1571 // Not a DBG_VALUE instruction.
1572 if (!MI->isPosition())
1573 AtBlockEntry = false;
1575 // First known non-DBG_VALUE and non-frame setup location marks
1576 // the beginning of the function body.
1577 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1578 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1579 PrologEndLoc = MI->getDebugLoc();
1581 // Check if the instruction clobbers any registers with debug vars.
1582 for (const MachineOperand &MO : MI->operands()) {
1583 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1585 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1588 const MDNode *Var = LiveUserVar[Reg];
1591 // Reg is now clobbered.
1592 LiveUserVar[Reg] = 0;
1594 // Was MD last defined by a DBG_VALUE referring to Reg?
1595 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1596 if (HistI == DbgValues.end())
1598 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1599 if (History.empty())
1601 const MachineInstr *Prev = History.back();
1602 // Sanity-check: Register assignments are terminated at the end of
1604 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1606 // Is the variable still in Reg?
1607 if (!isDbgValueInDefinedReg(Prev) ||
1608 Prev->getOperand(0).getReg() != Reg)
1610 // Var is clobbered. Make sure the next instruction gets a label.
1611 History.push_back(MI);
1618 for (auto &I : DbgValues) {
1619 SmallVectorImpl<const MachineInstr *> &History = I.second;
1620 if (History.empty())
1623 // Make sure the final register assignments are terminated.
1624 const MachineInstr *Prev = History.back();
1625 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1626 const MachineBasicBlock *PrevMBB = Prev->getParent();
1627 MachineBasicBlock::const_iterator LastMI =
1628 PrevMBB->getLastNonDebugInstr();
1629 if (LastMI == PrevMBB->end())
1630 // Drop DBG_VALUE for empty range.
1632 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1633 // Terminate after LastMI.
1634 History.push_back(LastMI);
1637 // Request labels for the full history.
1638 for (const MachineInstr *MI : History) {
1639 if (MI->isDebugValue())
1640 requestLabelBeforeInsn(MI);
1642 requestLabelAfterInsn(MI);
1646 PrevInstLoc = DebugLoc();
1647 PrevLabel = FunctionBeginSym;
1649 // Record beginning of function.
1650 if (!PrologEndLoc.isUnknown()) {
1651 DebugLoc FnStartDL =
1652 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1654 FnStartDL.getLine(), FnStartDL.getCol(),
1655 FnStartDL.getScope(MF->getFunction()->getContext()),
1656 // We'd like to list the prologue as "not statements" but GDB behaves
1657 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1658 DWARF2_FLAG_IS_STMT);
1662 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1663 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1664 DIVariable DV = Var->getVariable();
1665 // Variables with positive arg numbers are parameters.
1666 if (unsigned ArgNum = DV.getArgNumber()) {
1667 // Keep all parameters in order at the start of the variable list to ensure
1668 // function types are correct (no out-of-order parameters)
1670 // This could be improved by only doing it for optimized builds (unoptimized
1671 // builds have the right order to begin with), searching from the back (this
1672 // would catch the unoptimized case quickly), or doing a binary search
1673 // rather than linear search.
1674 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1675 while (I != Vars.end()) {
1676 unsigned CurNum = (*I)->getVariable().getArgNumber();
1677 // A local (non-parameter) variable has been found, insert immediately
1681 // A later indexed parameter has been found, insert immediately before it.
1682 if (CurNum > ArgNum)
1686 Vars.insert(I, Var);
1690 Vars.push_back(Var);
1693 // Gather and emit post-function debug information.
1694 void DwarfDebug::endFunction(const MachineFunction *MF) {
1695 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1696 // though the beginFunction may not be called at all.
1697 // We should handle both cases.
1701 assert(CurFn == MF);
1704 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1709 // Define end label for subprogram.
1710 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1711 // Assumes in correct section after the entry point.
1712 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1714 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1715 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1717 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1718 collectVariableInfo(ProcessedVars);
1720 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1721 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1722 assert(TheCU && "Unable to find compile unit!");
1724 // Construct abstract scopes.
1725 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1726 DISubprogram SP(AScope->getScopeNode());
1727 if (SP.isSubprogram()) {
1728 // Collect info for variables that were optimized out.
1729 DIArray Variables = SP.getVariables();
1730 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1731 DIVariable DV(Variables.getElement(i));
1732 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1734 // Check that DbgVariable for DV wasn't created earlier, when
1735 // findAbstractVariable() was called for inlined instance of DV.
1736 LLVMContext &Ctx = DV->getContext();
1737 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1738 if (AbstractVariables.lookup(CleanDV))
1740 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1741 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1744 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1745 constructScopeDIE(TheCU, AScope);
1748 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1749 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1750 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1752 // Add the range of this function to the list of ranges for the CU.
1753 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1754 TheCU->addRange(std::move(Span));
1757 for (auto &I : ScopeVariables)
1758 DeleteContainerPointers(I.second);
1759 ScopeVariables.clear();
1760 DeleteContainerPointers(CurrentFnArguments);
1761 UserVariables.clear();
1763 AbstractVariables.clear();
1764 LabelsBeforeInsn.clear();
1765 LabelsAfterInsn.clear();
1770 // Register a source line with debug info. Returns the unique label that was
1771 // emitted and which provides correspondence to the source line list.
1772 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1777 unsigned Discriminator = 0;
1779 DIDescriptor Scope(S);
1781 if (Scope.isCompileUnit()) {
1782 DICompileUnit CU(S);
1783 Fn = CU.getFilename();
1784 Dir = CU.getDirectory();
1785 } else if (Scope.isFile()) {
1787 Fn = F.getFilename();
1788 Dir = F.getDirectory();
1789 } else if (Scope.isSubprogram()) {
1791 Fn = SP.getFilename();
1792 Dir = SP.getDirectory();
1793 } else if (Scope.isLexicalBlockFile()) {
1794 DILexicalBlockFile DBF(S);
1795 Fn = DBF.getFilename();
1796 Dir = DBF.getDirectory();
1797 } else if (Scope.isLexicalBlock()) {
1798 DILexicalBlock DB(S);
1799 Fn = DB.getFilename();
1800 Dir = DB.getDirectory();
1801 Discriminator = DB.getDiscriminator();
1803 llvm_unreachable("Unexpected scope info");
1805 Src = getOrCreateSourceID(
1806 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1808 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1812 //===----------------------------------------------------------------------===//
1814 //===----------------------------------------------------------------------===//
1816 // Compute the size and offset of a DIE. The offset is relative to start of the
1817 // CU. It returns the offset after laying out the DIE.
1818 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1819 // Record the abbreviation.
1820 assignAbbrevNumber(Die->getAbbrev());
1822 // Get the abbreviation for this DIE.
1823 const DIEAbbrev &Abbrev = Die->getAbbrev();
1826 Die->setOffset(Offset);
1828 // Start the size with the size of abbreviation code.
1829 Offset += getULEB128Size(Die->getAbbrevNumber());
1831 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1832 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1834 // Size the DIE attribute values.
1835 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1836 // Size attribute value.
1837 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1839 // Get the children.
1840 const std::vector<DIE *> &Children = Die->getChildren();
1842 // Size the DIE children if any.
1843 if (!Children.empty()) {
1844 assert(Abbrev.hasChildren() && "Children flag not set");
1846 for (DIE *Child : Children)
1847 Offset = computeSizeAndOffset(Child, Offset);
1849 // End of children marker.
1850 Offset += sizeof(int8_t);
1853 Die->setSize(Offset - Die->getOffset());
1857 // Compute the size and offset for each DIE.
1858 void DwarfFile::computeSizeAndOffsets() {
1859 // Offset from the first CU in the debug info section is 0 initially.
1860 unsigned SecOffset = 0;
1862 // Iterate over each compile unit and set the size and offsets for each
1863 // DIE within each compile unit. All offsets are CU relative.
1864 for (DwarfUnit *TheU : CUs) {
1865 TheU->setDebugInfoOffset(SecOffset);
1867 // CU-relative offset is reset to 0 here.
1868 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1869 TheU->getHeaderSize(); // Unit-specific headers
1871 // EndOffset here is CU-relative, after laying out
1872 // all of the CU DIE.
1873 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1874 SecOffset += EndOffset;
1878 // Emit initial Dwarf sections with a label at the start of each one.
1879 void DwarfDebug::emitSectionLabels() {
1880 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1882 // Dwarf sections base addresses.
1883 DwarfInfoSectionSym =
1884 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1885 if (useSplitDwarf())
1886 DwarfInfoDWOSectionSym =
1887 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1888 DwarfAbbrevSectionSym =
1889 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1890 if (useSplitDwarf())
1891 DwarfAbbrevDWOSectionSym = emitSectionSym(
1892 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1893 if (GenerateARangeSection)
1894 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1896 DwarfLineSectionSym =
1897 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1898 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1899 if (GenerateGnuPubSections) {
1900 DwarfGnuPubNamesSectionSym =
1901 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1902 DwarfGnuPubTypesSectionSym =
1903 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1904 } else if (HasDwarfPubSections) {
1905 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1906 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1909 DwarfStrSectionSym =
1910 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1911 if (useSplitDwarf()) {
1912 DwarfStrDWOSectionSym =
1913 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1914 DwarfAddrSectionSym =
1915 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1917 DwarfDebugRangeSectionSym =
1918 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1920 DwarfDebugLocSectionSym =
1921 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1924 // Recursively emits a debug information entry.
1925 void DwarfDebug::emitDIE(DIE *Die) {
1926 // Get the abbreviation for this DIE.
1927 const DIEAbbrev &Abbrev = Die->getAbbrev();
1929 // Emit the code (index) for the abbreviation.
1930 if (Asm->isVerbose())
1931 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1932 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1933 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1934 dwarf::TagString(Abbrev.getTag()));
1935 Asm->EmitULEB128(Abbrev.getNumber());
1937 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1938 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1940 // Emit the DIE attribute values.
1941 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1942 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1943 dwarf::Form Form = AbbrevData[i].getForm();
1944 assert(Form && "Too many attributes for DIE (check abbreviation)");
1946 if (Asm->isVerbose()) {
1947 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1948 if (Attr == dwarf::DW_AT_accessibility)
1949 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1950 cast<DIEInteger>(Values[i])->getValue()));
1953 // Emit an attribute using the defined form.
1954 Values[i]->EmitValue(Asm, Form);
1957 // Emit the DIE children if any.
1958 if (Abbrev.hasChildren()) {
1959 const std::vector<DIE *> &Children = Die->getChildren();
1961 for (DIE *Child : Children)
1964 Asm->OutStreamer.AddComment("End Of Children Mark");
1969 // Emit the various dwarf units to the unit section USection with
1970 // the abbreviations going into ASection.
1971 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1972 const MCSymbol *ASectionSym) {
1973 for (DwarfUnit *TheU : CUs) {
1974 DIE *Die = TheU->getUnitDie();
1975 const MCSection *USection = TheU->getSection();
1976 Asm->OutStreamer.SwitchSection(USection);
1978 // Emit the compile units header.
1979 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1981 // Emit size of content not including length itself
1982 Asm->OutStreamer.AddComment("Length of Unit");
1983 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1985 TheU->emitHeader(ASection, ASectionSym);
1988 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1992 // Emit the debug info section.
1993 void DwarfDebug::emitDebugInfo() {
1994 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1996 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1997 DwarfAbbrevSectionSym);
2000 // Emit the abbreviation section.
2001 void DwarfDebug::emitAbbreviations() {
2002 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2004 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2007 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2008 // Check to see if it is worth the effort.
2009 if (!Abbreviations.empty()) {
2010 // Start the debug abbrev section.
2011 Asm->OutStreamer.SwitchSection(Section);
2013 // For each abbrevation.
2014 for (const DIEAbbrev *Abbrev : Abbreviations) {
2015 // Emit the abbrevations code (base 1 index.)
2016 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2018 // Emit the abbreviations data.
2022 // Mark end of abbreviations.
2023 Asm->EmitULEB128(0, "EOM(3)");
2027 // Emit the last address of the section and the end of the line matrix.
2028 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2029 // Define last address of section.
2030 Asm->OutStreamer.AddComment("Extended Op");
2033 Asm->OutStreamer.AddComment("Op size");
2034 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2035 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2036 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2038 Asm->OutStreamer.AddComment("Section end label");
2040 Asm->OutStreamer.EmitSymbolValue(
2041 Asm->GetTempSymbol("section_end", SectionEnd),
2042 Asm->getDataLayout().getPointerSize());
2044 // Mark end of matrix.
2045 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2051 // Emit visible names into a hashed accelerator table section.
2052 void DwarfDebug::emitAccelNames() {
2054 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2055 for (DwarfUnit *TheU : getUnits()) {
2056 for (const auto &GI : TheU->getAccelNames()) {
2057 StringRef Name = GI.getKey();
2058 for (const DIE *D : GI.second)
2059 AT.AddName(Name, D);
2063 AT.FinalizeTable(Asm, "Names");
2064 Asm->OutStreamer.SwitchSection(
2065 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2066 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2067 Asm->OutStreamer.EmitLabel(SectionBegin);
2069 // Emit the full data.
2070 AT.Emit(Asm, SectionBegin, &InfoHolder);
2073 // Emit objective C classes and categories into a hashed accelerator table
2075 void DwarfDebug::emitAccelObjC() {
2077 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2078 for (DwarfUnit *TheU : getUnits()) {
2079 for (const auto &GI : TheU->getAccelObjC()) {
2080 StringRef Name = GI.getKey();
2081 for (const DIE *D : GI.second)
2082 AT.AddName(Name, D);
2086 AT.FinalizeTable(Asm, "ObjC");
2087 Asm->OutStreamer.SwitchSection(
2088 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2089 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2090 Asm->OutStreamer.EmitLabel(SectionBegin);
2092 // Emit the full data.
2093 AT.Emit(Asm, SectionBegin, &InfoHolder);
2096 // Emit namespace dies into a hashed accelerator table.
2097 void DwarfDebug::emitAccelNamespaces() {
2099 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2100 for (DwarfUnit *TheU : getUnits()) {
2101 for (const auto &GI : TheU->getAccelNamespace()) {
2102 StringRef Name = GI.getKey();
2103 for (const DIE *D : GI.second)
2104 AT.AddName(Name, D);
2108 AT.FinalizeTable(Asm, "namespac");
2109 Asm->OutStreamer.SwitchSection(
2110 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2111 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2112 Asm->OutStreamer.EmitLabel(SectionBegin);
2114 // Emit the full data.
2115 AT.Emit(Asm, SectionBegin, &InfoHolder);
2118 // Emit type dies into a hashed accelerator table.
2119 void DwarfDebug::emitAccelTypes() {
2120 std::vector<DwarfAccelTable::Atom> Atoms;
2122 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2124 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2126 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2127 DwarfAccelTable AT(Atoms);
2128 for (DwarfUnit *TheU : getUnits()) {
2129 for (const auto &GI : TheU->getAccelTypes()) {
2130 StringRef Name = GI.getKey();
2131 for (const auto &DI : GI.second)
2132 AT.AddName(Name, DI.first, DI.second);
2136 AT.FinalizeTable(Asm, "types");
2137 Asm->OutStreamer.SwitchSection(
2138 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2139 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2140 Asm->OutStreamer.EmitLabel(SectionBegin);
2142 // Emit the full data.
2143 AT.Emit(Asm, SectionBegin, &InfoHolder);
2146 // Public name handling.
2147 // The format for the various pubnames:
2149 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2150 // for the DIE that is named.
2152 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2153 // into the CU and the index value is computed according to the type of value
2154 // for the DIE that is named.
2156 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2157 // it's the offset within the debug_info/debug_types dwo section, however, the
2158 // reference in the pubname header doesn't change.
2160 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2161 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2163 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2165 // We could have a specification DIE that has our most of our knowledge,
2166 // look for that now.
2167 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2169 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2170 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2171 Linkage = dwarf::GIEL_EXTERNAL;
2172 } else if (Die->findAttribute(dwarf::DW_AT_external))
2173 Linkage = dwarf::GIEL_EXTERNAL;
2175 switch (Die->getTag()) {
2176 case dwarf::DW_TAG_class_type:
2177 case dwarf::DW_TAG_structure_type:
2178 case dwarf::DW_TAG_union_type:
2179 case dwarf::DW_TAG_enumeration_type:
2180 return dwarf::PubIndexEntryDescriptor(
2181 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2182 ? dwarf::GIEL_STATIC
2183 : dwarf::GIEL_EXTERNAL);
2184 case dwarf::DW_TAG_typedef:
2185 case dwarf::DW_TAG_base_type:
2186 case dwarf::DW_TAG_subrange_type:
2187 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2188 case dwarf::DW_TAG_namespace:
2189 return dwarf::GIEK_TYPE;
2190 case dwarf::DW_TAG_subprogram:
2191 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2192 case dwarf::DW_TAG_constant:
2193 case dwarf::DW_TAG_variable:
2194 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2195 case dwarf::DW_TAG_enumerator:
2196 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2197 dwarf::GIEL_STATIC);
2199 return dwarf::GIEK_NONE;
2203 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2205 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2206 const MCSection *PSec =
2207 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2208 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2210 for (const auto &NU : CUMap) {
2211 DwarfCompileUnit *TheU = NU.second;
2212 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2214 unsigned ID = TheU->getUniqueID();
2216 // Start the dwarf pubnames section.
2217 Asm->OutStreamer.SwitchSection(PSec);
2219 // Emit a label so we can reference the beginning of this pubname section.
2221 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2224 Asm->OutStreamer.AddComment("Length of Public Names Info");
2225 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2226 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2227 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2229 Asm->OutStreamer.EmitLabel(BeginLabel);
2231 Asm->OutStreamer.AddComment("DWARF Version");
2232 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2234 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2235 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2237 Asm->OutStreamer.AddComment("Compilation Unit Length");
2238 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2240 // Emit the pubnames for this compilation unit.
2241 for (const auto &GI : getUnits()[ID]->getGlobalNames()) {
2242 const char *Name = GI.getKeyData();
2243 const DIE *Entity = GI.second;
2245 Asm->OutStreamer.AddComment("DIE offset");
2246 Asm->EmitInt32(Entity->getOffset());
2249 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2250 Asm->OutStreamer.AddComment(
2251 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2252 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2253 Asm->EmitInt8(Desc.toBits());
2256 Asm->OutStreamer.AddComment("External Name");
2257 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2260 Asm->OutStreamer.AddComment("End Mark");
2262 Asm->OutStreamer.EmitLabel(EndLabel);
2266 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2267 const MCSection *PSec =
2268 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2269 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2271 for (const auto &NU : CUMap) {
2272 DwarfCompileUnit *TheU = NU.second;
2273 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2275 unsigned ID = TheU->getUniqueID();
2277 // Start the dwarf pubtypes section.
2278 Asm->OutStreamer.SwitchSection(PSec);
2280 // Emit a label so we can reference the beginning of this pubtype section.
2282 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2285 Asm->OutStreamer.AddComment("Length of Public Types Info");
2286 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2287 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2288 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2290 Asm->OutStreamer.EmitLabel(BeginLabel);
2292 Asm->OutStreamer.AddComment("DWARF Version");
2293 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2295 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2296 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2298 Asm->OutStreamer.AddComment("Compilation Unit Length");
2299 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2301 // Emit the pubtypes.
2302 for (const auto &GI : getUnits()[ID]->getGlobalTypes()) {
2303 const char *Name = GI.getKeyData();
2304 const DIE *Entity = GI.second;
2306 Asm->OutStreamer.AddComment("DIE offset");
2307 Asm->EmitInt32(Entity->getOffset());
2310 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2311 Asm->OutStreamer.AddComment(
2312 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2313 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2314 Asm->EmitInt8(Desc.toBits());
2317 Asm->OutStreamer.AddComment("External Name");
2319 // Emit the name with a terminating null byte.
2320 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2323 Asm->OutStreamer.AddComment("End Mark");
2325 Asm->OutStreamer.EmitLabel(EndLabel);
2329 // Emit strings into a string section.
2330 void DwarfFile::emitStrings(const MCSection *StrSection,
2331 const MCSection *OffsetSection = NULL,
2332 const MCSymbol *StrSecSym = NULL) {
2334 if (StringPool.empty())
2337 // Start the dwarf str section.
2338 Asm->OutStreamer.SwitchSection(StrSection);
2340 // Get all of the string pool entries and put them in an array by their ID so
2341 // we can sort them.
2342 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2344 for (const auto &I : StringPool)
2345 Entries.push_back(std::make_pair(I.second.second, &I));
2347 array_pod_sort(Entries.begin(), Entries.end());
2349 for (const auto &Entry : Entries) {
2350 // Emit a label for reference from debug information entries.
2351 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2353 // Emit the string itself with a terminating null byte.
2354 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2355 Entry.second->getKeyLength() + 1));
2358 // If we've got an offset section go ahead and emit that now as well.
2359 if (OffsetSection) {
2360 Asm->OutStreamer.SwitchSection(OffsetSection);
2361 unsigned offset = 0;
2362 unsigned size = 4; // FIXME: DWARF64 is 8.
2363 for (const auto &Entry : Entries) {
2364 Asm->OutStreamer.EmitIntValue(offset, size);
2365 offset += Entry.second->getKeyLength() + 1;
2370 // Emit addresses into the section given.
2371 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2373 if (AddressPool.empty())
2376 // Start the dwarf addr section.
2377 Asm->OutStreamer.SwitchSection(AddrSection);
2379 // Order the address pool entries by ID
2380 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2382 for (const auto &I : AddressPool)
2383 Entries[I.second.Number] =
2385 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2386 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2388 for (const MCExpr *Entry : Entries)
2389 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2392 // Emit visible names into a debug str section.
2393 void DwarfDebug::emitDebugStr() {
2394 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2395 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2398 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2399 const DotDebugLocEntry &Entry) {
2400 DIVariable DV(Entry.getVariable());
2401 if (Entry.isInt()) {
2402 DIBasicType BTy(DV.getType());
2403 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2404 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2405 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2406 Streamer.EmitSLEB128(Entry.getInt());
2408 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2409 Streamer.EmitULEB128(Entry.getInt());
2411 } else if (Entry.isLocation()) {
2412 MachineLocation Loc = Entry.getLoc();
2413 if (!DV.hasComplexAddress())
2415 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2417 // Complex address entry.
2418 unsigned N = DV.getNumAddrElements();
2420 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2421 if (Loc.getOffset()) {
2423 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2424 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2425 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2426 Streamer.EmitSLEB128(DV.getAddrElement(1));
2428 // If first address element is OpPlus then emit
2429 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2430 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2431 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2435 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2438 // Emit remaining complex address elements.
2439 for (; i < N; ++i) {
2440 uint64_t Element = DV.getAddrElement(i);
2441 if (Element == DIBuilder::OpPlus) {
2442 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2443 Streamer.EmitULEB128(DV.getAddrElement(++i));
2444 } else if (Element == DIBuilder::OpDeref) {
2446 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2448 llvm_unreachable("unknown Opcode found in complex address");
2452 // else ... ignore constant fp. There is not any good way to
2453 // to represent them here in dwarf.
2457 // Emit locations into the debug loc section.
2458 void DwarfDebug::emitDebugLoc() {
2459 if (DotDebugLocEntries.empty())
2462 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2463 I = DotDebugLocEntries.begin(),
2464 E = DotDebugLocEntries.end();
2466 DotDebugLocEntry &Entry = *I;
2467 if (I + 1 != DotDebugLocEntries.end())
2471 // Start the dwarf loc section.
2472 Asm->OutStreamer.SwitchSection(
2473 Asm->getObjFileLowering().getDwarfLocSection());
2474 unsigned char Size = Asm->getDataLayout().getPointerSize();
2475 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2477 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2478 I = DotDebugLocEntries.begin(),
2479 E = DotDebugLocEntries.end();
2480 I != E; ++I, ++index) {
2481 const DotDebugLocEntry &Entry = *I;
2482 if (Entry.isMerged())
2485 if (Entry.isEmpty()) {
2486 Asm->OutStreamer.EmitIntValue(0, Size);
2487 Asm->OutStreamer.EmitIntValue(0, Size);
2488 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2490 // Set up the range.
2491 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2492 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2493 Asm->OutStreamer.AddComment("Loc expr size");
2494 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2495 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2496 Asm->EmitLabelDifference(end, begin, 2);
2497 Asm->OutStreamer.EmitLabel(begin);
2499 APByteStreamer Streamer(*Asm);
2500 emitDebugLocEntry(Streamer, Entry);
2502 Asm->OutStreamer.EmitLabel(end);
2508 const MCSymbol *Start, *End;
2511 // Emit a debug aranges section, containing a CU lookup for any
2512 // address we can tie back to a CU.
2513 void DwarfDebug::emitDebugARanges() {
2514 // Start the dwarf aranges section.
2515 Asm->OutStreamer.SwitchSection(
2516 Asm->getObjFileLowering().getDwarfARangesSection());
2518 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2522 // Build a list of sections used.
2523 std::vector<const MCSection *> Sections;
2524 for (const auto &it : SectionMap) {
2525 const MCSection *Section = it.first;
2526 Sections.push_back(Section);
2529 // Sort the sections into order.
2530 // This is only done to ensure consistent output order across different runs.
2531 std::sort(Sections.begin(), Sections.end(), SectionSort);
2533 // Build a set of address spans, sorted by CU.
2534 for (const MCSection *Section : Sections) {
2535 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2536 if (List.size() < 2)
2539 // Sort the symbols by offset within the section.
2540 std::sort(List.begin(), List.end(),
2541 [&](const SymbolCU &A, const SymbolCU &B) {
2542 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2543 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2545 // Symbols with no order assigned should be placed at the end.
2546 // (e.g. section end labels)
2554 // If we have no section (e.g. common), just write out
2555 // individual spans for each symbol.
2556 if (Section == NULL) {
2557 for (const SymbolCU &Cur : List) {
2559 Span.Start = Cur.Sym;
2562 Spans[Cur.CU].push_back(Span);
2565 // Build spans between each label.
2566 const MCSymbol *StartSym = List[0].Sym;
2567 for (size_t n = 1, e = List.size(); n < e; n++) {
2568 const SymbolCU &Prev = List[n - 1];
2569 const SymbolCU &Cur = List[n];
2571 // Try and build the longest span we can within the same CU.
2572 if (Cur.CU != Prev.CU) {
2574 Span.Start = StartSym;
2576 Spans[Prev.CU].push_back(Span);
2583 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2585 // Build a list of CUs used.
2586 std::vector<DwarfCompileUnit *> CUs;
2587 for (const auto &it : Spans) {
2588 DwarfCompileUnit *CU = it.first;
2592 // Sort the CU list (again, to ensure consistent output order).
2593 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2594 return A->getUniqueID() < B->getUniqueID();
2597 // Emit an arange table for each CU we used.
2598 for (DwarfCompileUnit *CU : CUs) {
2599 std::vector<ArangeSpan> &List = Spans[CU];
2601 // Emit size of content not including length itself.
2602 unsigned ContentSize =
2603 sizeof(int16_t) + // DWARF ARange version number
2604 sizeof(int32_t) + // Offset of CU in the .debug_info section
2605 sizeof(int8_t) + // Pointer Size (in bytes)
2606 sizeof(int8_t); // Segment Size (in bytes)
2608 unsigned TupleSize = PtrSize * 2;
2610 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2612 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2614 ContentSize += Padding;
2615 ContentSize += (List.size() + 1) * TupleSize;
2617 // For each compile unit, write the list of spans it covers.
2618 Asm->OutStreamer.AddComment("Length of ARange Set");
2619 Asm->EmitInt32(ContentSize);
2620 Asm->OutStreamer.AddComment("DWARF Arange version number");
2621 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2622 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2623 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2624 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2625 Asm->EmitInt8(PtrSize);
2626 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2629 Asm->OutStreamer.EmitFill(Padding, 0xff);
2631 for (const ArangeSpan &Span : List) {
2632 Asm->EmitLabelReference(Span.Start, PtrSize);
2634 // Calculate the size as being from the span start to it's end.
2636 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2638 // For symbols without an end marker (e.g. common), we
2639 // write a single arange entry containing just that one symbol.
2640 uint64_t Size = SymSize[Span.Start];
2644 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2648 Asm->OutStreamer.AddComment("ARange terminator");
2649 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2650 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2654 // Emit visible names into a debug ranges section.
2655 void DwarfDebug::emitDebugRanges() {
2656 // Start the dwarf ranges section.
2657 Asm->OutStreamer.SwitchSection(
2658 Asm->getObjFileLowering().getDwarfRangesSection());
2660 // Size for our labels.
2661 unsigned char Size = Asm->getDataLayout().getPointerSize();
2663 // Grab the specific ranges for the compile units in the module.
2664 for (const auto &I : CUMap) {
2665 DwarfCompileUnit *TheCU = I.second;
2667 // Emit a symbol so we can find the beginning of our ranges.
2668 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2670 // Iterate over the misc ranges for the compile units in the module.
2671 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2672 // Emit our symbol so we can find the beginning of the range.
2673 Asm->OutStreamer.EmitLabel(List.getSym());
2675 for (const RangeSpan &Range : List.getRanges()) {
2676 const MCSymbol *Begin = Range.getStart();
2677 const MCSymbol *End = Range.getEnd();
2678 assert(Begin && "Range without a begin symbol?");
2679 assert(End && "Range without an end symbol?");
2680 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2681 Asm->OutStreamer.EmitSymbolValue(End, Size);
2684 // And terminate the list with two 0 values.
2685 Asm->OutStreamer.EmitIntValue(0, Size);
2686 Asm->OutStreamer.EmitIntValue(0, Size);
2689 // Now emit a range for the CU itself.
2690 if (useCURanges() && TheCU->getRanges().size()) {
2691 Asm->OutStreamer.EmitLabel(
2692 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2693 for (const RangeSpan &Range : TheCU->getRanges()) {
2694 const MCSymbol *Begin = Range.getStart();
2695 const MCSymbol *End = Range.getEnd();
2696 assert(Begin && "Range without a begin symbol?");
2697 assert(End && "Range without an end symbol?");
2698 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2699 Asm->OutStreamer.EmitSymbolValue(End, Size);
2701 // And terminate the list with two 0 values.
2702 Asm->OutStreamer.EmitIntValue(0, Size);
2703 Asm->OutStreamer.EmitIntValue(0, Size);
2708 // DWARF5 Experimental Separate Dwarf emitters.
2710 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2712 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2713 U->getCUNode().getSplitDebugFilename());
2715 // Relocate to the beginning of the addr_base section, else 0 for the
2716 // beginning of the one for this compile unit.
2717 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2718 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2720 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2722 if (!CompilationDir.empty())
2723 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2725 addGnuPubAttributes(NewU, Die);
2727 SkeletonHolder.addUnit(NewU);
2730 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2731 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2732 // DW_AT_ranges_base, DW_AT_addr_base.
2733 // TODO: Implement DW_AT_ranges_base.
2734 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2736 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2737 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2738 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2739 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2740 DwarfInfoSectionSym);
2742 NewCU->initStmtList(DwarfLineSectionSym);
2744 initSkeletonUnit(CU, Die, NewCU);
2749 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2751 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2752 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2753 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2755 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2756 DwarfTypeUnit *NewTU =
2757 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2758 NewTU->setTypeSignature(TU->getTypeSignature());
2759 NewTU->setType(NULL);
2761 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2762 CU.applyStmtList(*Die);
2764 initSkeletonUnit(TU, Die, NewTU);
2768 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2769 // compile units that would normally be in debug_info.
2770 void DwarfDebug::emitDebugInfoDWO() {
2771 assert(useSplitDwarf() && "No split dwarf debug info?");
2772 InfoHolder.emitUnits(this,
2773 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2774 DwarfAbbrevDWOSectionSym);
2777 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2778 // abbreviations for the .debug_info.dwo section.
2779 void DwarfDebug::emitDebugAbbrevDWO() {
2780 assert(useSplitDwarf() && "No split dwarf?");
2781 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2784 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2785 // string section and is identical in format to traditional .debug_str
2787 void DwarfDebug::emitDebugStrDWO() {
2788 assert(useSplitDwarf() && "No split dwarf?");
2789 const MCSection *OffSec =
2790 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2791 const MCSymbol *StrSym = DwarfStrSectionSym;
2792 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2796 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2797 StringRef Identifier, DIE *RefDie,
2798 DICompositeType CTy) {
2799 // Flag the type unit reference as a declaration so that if it contains
2800 // members (implicit special members, static data member definitions, member
2801 // declarations for definitions in this CU, etc) consumers don't get confused
2802 // and think this is a full definition.
2803 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2805 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2807 CU.addDIETypeSignature(RefDie, *TU);
2811 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2812 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2813 UnitDie, CU, Asm, this, &InfoHolder);
2815 InfoHolder.addUnit(NewTU);
2817 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2821 Hash.update(Identifier);
2822 // ... take the least significant 8 bytes and return those. Our MD5
2823 // implementation always returns its results in little endian, swap bytes
2825 MD5::MD5Result Result;
2827 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2828 NewTU->setTypeSignature(Signature);
2829 if (useSplitDwarf())
2830 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2832 CU.applyStmtList(*UnitDie);
2834 NewTU->setType(NewTU->createTypeDIE(CTy));
2838 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2839 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2841 CU.addDIETypeSignature(RefDie, *NewTU);
2844 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2845 MCSymbol *Begin, MCSymbol *End) {
2846 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2847 if (DwarfVersion < 4)
2848 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2850 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);