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."),
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
70 cl::desc("Generate dwarf aranges"),
74 enum DefaultOnOff { Default, Enable, Disable };
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
112 /// resolve - Look in the DwarfDebug map for the MDNode that
113 /// corresponds to the reference.
114 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
115 return DD->resolve(Ref);
118 bool DbgVariable::isBlockByrefVariable() const {
119 assert(Var.isVariable() && "Invalid complex DbgVariable!");
120 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
124 DIType DbgVariable::getType() const {
125 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
126 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
127 // addresses instead.
128 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
129 /* Byref variables, in Blocks, are declared by the programmer as
130 "SomeType VarName;", but the compiler creates a
131 __Block_byref_x_VarName struct, and gives the variable VarName
132 either the struct, or a pointer to the struct, as its type. This
133 is necessary for various behind-the-scenes things the compiler
134 needs to do with by-reference variables in blocks.
136 However, as far as the original *programmer* is concerned, the
137 variable should still have type 'SomeType', as originally declared.
139 The following function dives into the __Block_byref_x_VarName
140 struct to find the original type of the variable. This will be
141 passed back to the code generating the type for the Debug
142 Information Entry for the variable 'VarName'. 'VarName' will then
143 have the original type 'SomeType' in its debug information.
145 The original type 'SomeType' will be the type of the field named
146 'VarName' inside the __Block_byref_x_VarName struct.
148 NOTE: In order for this to not completely fail on the debugger
149 side, the Debug Information Entry for the variable VarName needs to
150 have a DW_AT_location that tells the debugger how to unwind through
151 the pointers and __Block_byref_x_VarName struct to find the actual
152 value of the variable. The function addBlockByrefType does this. */
154 uint16_t tag = Ty.getTag();
156 if (tag == dwarf::DW_TAG_pointer_type)
157 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
159 DIArray Elements = DICompositeType(subType).getTypeArray();
160 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
161 DIDerivedType DT(Elements.getElement(i));
162 if (getName() == DT.getName())
163 return (resolve(DT.getTypeDerivedFrom()));
169 } // end llvm namespace
171 /// Return Dwarf Version by checking module flags.
172 static unsigned getDwarfVersionFromModule(const Module *M) {
173 Value *Val = M->getModuleFlag("Dwarf Version");
175 return dwarf::DWARF_VERSION;
176 return cast<ConstantInt>(Val)->getZExtValue();
179 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
180 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
181 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
182 UsedNonDefaultText(false),
183 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
187 DwarfAddrSectionSym = 0;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
189 FunctionBeginSym = FunctionEndSym = 0;
193 // Turn on accelerator tables for Darwin by default, pubnames by
194 // default for non-Darwin, and handle split dwarf.
195 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
197 if (DwarfAccelTables == Default)
198 HasDwarfAccelTables = IsDarwin;
200 HasDwarfAccelTables = DwarfAccelTables == Enable;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable;
207 if (DwarfPubSections == Default)
208 HasDwarfPubSections = !IsDarwin;
210 HasDwarfPubSections = DwarfPubSections == Enable;
212 DwarfVersion = DwarfVersionNumber
214 : getDwarfVersionFromModule(MMI->getModule());
217 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
222 // Switch to the specified MCSection and emit an assembler
223 // temporary label to it if SymbolStem is specified.
224 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
225 const char *SymbolStem = 0) {
226 Asm->OutStreamer.SwitchSection(Section);
230 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
231 Asm->OutStreamer.EmitLabel(TmpSym);
235 DwarfFile::~DwarfFile() {
236 for (DwarfUnit *DU : CUs)
240 MCSymbol *DwarfFile::getStringPoolSym() {
241 return Asm->GetTempSymbol(StringPref);
244 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
245 std::pair<MCSymbol *, unsigned> &Entry =
246 StringPool.GetOrCreateValue(Str).getValue();
250 Entry.second = NextStringPoolNumber++;
251 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
254 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
255 std::pair<MCSymbol *, unsigned> &Entry =
256 StringPool.GetOrCreateValue(Str).getValue();
260 Entry.second = NextStringPoolNumber++;
261 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
265 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
266 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
267 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
269 ++NextAddrPoolNumber;
270 return P.first->second.Number;
273 // Define a unique number for the abbreviation.
275 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
276 // Check the set for priors.
277 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
279 // If it's newly added.
280 if (InSet == &Abbrev) {
281 // Add to abbreviation list.
282 Abbreviations.push_back(&Abbrev);
284 // Assign the vector position + 1 as its number.
285 Abbrev.setNumber(Abbreviations.size());
287 // Assign existing abbreviation number.
288 Abbrev.setNumber(InSet->getNumber());
292 static bool isObjCClass(StringRef Name) {
293 return Name.startswith("+") || Name.startswith("-");
296 static bool hasObjCCategory(StringRef Name) {
297 if (!isObjCClass(Name))
300 return Name.find(") ") != StringRef::npos;
303 static void getObjCClassCategory(StringRef In, StringRef &Class,
304 StringRef &Category) {
305 if (!hasObjCCategory(In)) {
306 Class = In.slice(In.find('[') + 1, In.find(' '));
311 Class = In.slice(In.find('[') + 1, In.find('('));
312 Category = In.slice(In.find('[') + 1, In.find(' '));
316 static StringRef getObjCMethodName(StringRef In) {
317 return In.slice(In.find(' ') + 1, In.find(']'));
320 // Helper for sorting sections into a stable output order.
321 static bool SectionSort(const MCSection *A, const MCSection *B) {
322 std::string LA = (A ? A->getLabelBeginName() : "");
323 std::string LB = (B ? B->getLabelBeginName() : "");
327 // Add the various names to the Dwarf accelerator table names.
328 // TODO: Determine whether or not we should add names for programs
329 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
330 // is only slightly different than the lookup of non-standard ObjC names.
331 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
332 if (!SP.isDefinition())
334 TheU->addAccelName(SP.getName(), Die);
336 // If the linkage name is different than the name, go ahead and output
337 // that as well into the name table.
338 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
339 TheU->addAccelName(SP.getLinkageName(), Die);
341 // If this is an Objective-C selector name add it to the ObjC accelerator
343 if (isObjCClass(SP.getName())) {
344 StringRef Class, Category;
345 getObjCClassCategory(SP.getName(), Class, Category);
346 TheU->addAccelObjC(Class, Die);
348 TheU->addAccelObjC(Category, Die);
349 // Also add the base method name to the name table.
350 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
354 /// isSubprogramContext - Return true if Context is either a subprogram
355 /// or another context nested inside a subprogram.
356 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
359 DIDescriptor D(Context);
360 if (D.isSubprogram())
363 return isSubprogramContext(resolve(DIType(Context).getContext()));
367 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
368 // and DW_AT_high_pc attributes. If there are global variables in this
369 // scope then create and insert DIEs for these variables.
370 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
372 SP = SPCU->getOdrUniqueSubprogram(resolve(SP.getContext()), SP);
373 DIE *SPDie = SPCU->getDIE(SP);
375 assert(SPDie && "Unable to find subprogram DIE!");
377 // If we're updating an abstract DIE, then we will be adding the children and
378 // object pointer later on. But what we don't want to do is process the
379 // concrete DIE twice.
380 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
381 // Pick up abstract subprogram DIE.
383 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
384 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
386 DISubprogram SPDecl = SP.getFunctionDeclaration();
387 if (!SPDecl.isSubprogram()) {
388 // There is not any need to generate specification DIE for a function
389 // defined at compile unit level. If a function is defined inside another
390 // function then gdb prefers the definition at top level and but does not
391 // expect specification DIE in parent function. So avoid creating
392 // specification DIE for a function defined inside a function.
393 DIScope SPContext = resolve(SP.getContext());
394 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
395 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
396 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
399 DICompositeType SPTy = SP.getType();
400 DIArray Args = SPTy.getTypeArray();
401 uint16_t SPTag = SPTy.getTag();
402 if (SPTag == dwarf::DW_TAG_subroutine_type)
403 SPCU->constructSubprogramArguments(*SPDie, Args);
404 DIE *SPDeclDie = SPDie;
405 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
406 *SPCU->getUnitDie());
407 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
412 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
414 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
415 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
416 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
418 // Add name to the name table, we do this here because we're guaranteed
419 // to have concrete versions of our DW_TAG_subprogram nodes.
420 addSubprogramNames(SPCU, SP, SPDie);
425 /// Check whether we should create a DIE for the given Scope, return true
426 /// if we don't create a DIE (the corresponding DIE is null).
427 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
428 if (Scope->isAbstractScope())
431 // We don't create a DIE if there is no Range.
432 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
436 if (Ranges.size() > 1)
439 // We don't create a DIE if we have a single Range and the end label
441 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
442 MCSymbol *End = getLabelAfterInsn(RI->second);
446 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
447 dwarf::Attribute A, const MCSymbol *L,
448 const MCSymbol *Sec) {
449 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
450 U->addSectionLabel(D, A, L);
452 U->addSectionDelta(D, A, L, Sec);
455 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
456 const SmallVectorImpl<InsnRange> &Range) {
457 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
458 // emitting it appropriately.
459 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
460 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
461 DwarfDebugRangeSectionSym);
463 RangeSpanList List(RangeSym);
464 for (const InsnRange &R : Range) {
465 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
466 List.addRange(std::move(Span));
469 // Add the range list to the set of ranges to be emitted.
470 TheCU->addRangeList(std::move(List));
473 // Construct new DW_TAG_lexical_block for this scope and attach
474 // DW_AT_low_pc/DW_AT_high_pc labels.
475 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
476 LexicalScope *Scope) {
477 if (isLexicalScopeDIENull(Scope))
480 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
481 if (Scope->isAbstractScope())
484 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
486 // If we have multiple ranges, emit them into the range section.
487 if (ScopeRanges.size() > 1) {
488 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
492 // Construct the address range for this DIE.
493 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
494 MCSymbol *Start = getLabelBeforeInsn(RI->first);
495 MCSymbol *End = getLabelAfterInsn(RI->second);
496 assert(End && "End label should not be null!");
498 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
499 assert(End->isDefined() && "Invalid end label for an inlined scope!");
501 attachLowHighPC(TheCU, ScopeDIE, Start, End);
506 // This scope represents inlined body of a function. Construct DIE to
507 // represent this concrete inlined copy of the function.
508 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
509 LexicalScope *Scope) {
510 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
511 assert(!ScopeRanges.empty() &&
512 "LexicalScope does not have instruction markers!");
514 if (!Scope->getScopeNode())
516 DIScope DS(Scope->getScopeNode());
517 DISubprogram InlinedSP = getDISubprogram(DS);
518 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
520 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
524 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
525 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
527 // If we have multiple ranges, emit them into the range section.
528 if (ScopeRanges.size() > 1)
529 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
531 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
532 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
533 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
535 if (StartLabel == 0 || EndLabel == 0)
536 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
538 assert(StartLabel->isDefined() &&
539 "Invalid starting label for an inlined scope!");
540 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
542 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
545 InlinedSubprogramDIEs.insert(OriginDIE);
547 // Add the call site information to the DIE.
548 DILocation DL(Scope->getInlinedAt());
550 ScopeDIE, dwarf::DW_AT_call_file, None,
551 TheCU->getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
552 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
554 // Add name to the name table, we do this here because we're guaranteed
555 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
556 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
561 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
563 SmallVectorImpl<DIE *> &Children) {
564 DIE *ObjectPointer = NULL;
566 // Collect arguments for current function.
567 if (LScopes.isCurrentFunctionScope(Scope)) {
568 for (DbgVariable *ArgDV : CurrentFnArguments)
571 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
572 Children.push_back(Arg);
573 if (ArgDV->isObjectPointer())
577 // If this is a variadic function, add an unspecified parameter.
578 DISubprogram SP(Scope->getScopeNode());
579 DIArray FnArgs = SP.getType().getTypeArray();
580 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
581 .isUnspecifiedParameter()) {
582 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
583 Children.push_back(Ellipsis);
587 // Collect lexical scope children first.
588 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
589 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
590 Scope->isAbstractScope())) {
591 Children.push_back(Variable);
592 if (DV->isObjectPointer())
593 ObjectPointer = Variable;
595 for (LexicalScope *LS : Scope->getChildren())
596 if (DIE *Nested = constructScopeDIE(TheCU, LS))
597 Children.push_back(Nested);
598 return ObjectPointer;
601 // Construct a DIE for this scope.
602 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
603 LexicalScope *Scope) {
604 if (!Scope || !Scope->getScopeNode())
607 DIScope DS(Scope->getScopeNode());
609 SmallVector<DIE *, 8> Children;
610 DIE *ObjectPointer = NULL;
611 bool ChildrenCreated = false;
613 // We try to create the scope DIE first, then the children DIEs. This will
614 // avoid creating un-used children then removing them later when we find out
615 // the scope DIE is null.
616 DIE *ScopeDIE = NULL;
617 if (Scope->getInlinedAt())
618 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
619 else if (DS.isSubprogram()) {
620 ProcessedSPNodes.insert(DS);
621 if (Scope->isAbstractScope()) {
622 ScopeDIE = TheCU->getDIE(DS);
623 // Note down abstract DIE.
625 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
627 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
629 // Early exit when we know the scope DIE is going to be null.
630 if (isLexicalScopeDIENull(Scope))
633 // We create children here when we know the scope DIE is not going to be
634 // null and the children will be added to the scope DIE.
635 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
636 ChildrenCreated = true;
638 // There is no need to emit empty lexical block DIE.
639 std::pair<ImportedEntityMap::const_iterator,
640 ImportedEntityMap::const_iterator> Range =
642 ScopesWithImportedEntities.begin(),
643 ScopesWithImportedEntities.end(),
644 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
646 if (Children.empty() && Range.first == Range.second)
648 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
649 assert(ScopeDIE && "Scope DIE should not be null.");
650 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
652 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
656 assert(Children.empty() &&
657 "We create children only when the scope DIE is not null.");
660 if (!ChildrenCreated)
661 // We create children when the scope DIE is not null.
662 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
665 for (DIE *I : Children)
666 ScopeDIE->addChild(I);
668 if (DS.isSubprogram() && ObjectPointer != NULL)
669 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
674 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
675 if (!GenerateGnuPubSections)
678 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
681 // Create new DwarfCompileUnit for the given metadata node with tag
682 // DW_TAG_compile_unit.
683 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit,
685 StringRef FN = DIUnit.getFilename();
686 CompilationDir = DIUnit.getDirectory();
688 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
689 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
690 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
691 InfoHolder.addUnit(NewCU);
692 if (!Asm->OutStreamer.hasRawTextSupport() || Singular)
693 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
694 NewCU->getUniqueID(), CompilationDir);
696 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
697 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
698 DIUnit.getLanguage());
699 NewCU->addString(Die, dwarf::DW_AT_name, FN);
701 if (!useSplitDwarf()) {
702 NewCU->initStmtList(DwarfLineSectionSym);
704 // If we're using split dwarf the compilation dir is going to be in the
705 // skeleton CU and so we don't need to duplicate it here.
706 if (!CompilationDir.empty())
707 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
709 addGnuPubAttributes(NewCU, Die);
712 if (DIUnit.isOptimized())
713 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
715 StringRef Flags = DIUnit.getFlags();
717 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
719 if (unsigned RVer = DIUnit.getRunTimeVersion())
720 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
721 dwarf::DW_FORM_data1, RVer);
726 if (useSplitDwarf()) {
727 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
728 DwarfInfoDWOSectionSym);
729 NewCU->setSkeleton(constructSkeletonCU(NewCU));
731 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
732 DwarfInfoSectionSym);
734 CUMap.insert(std::make_pair(DIUnit, NewCU));
735 CUDieMap.insert(std::make_pair(Die, NewCU));
739 // Construct subprogram DIE.
740 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
742 // FIXME: We should only call this routine once, however, during LTO if a
743 // program is defined in multiple CUs we could end up calling it out of
744 // beginModule as we walk the CUs.
746 DwarfCompileUnit *&CURef = SPMap[N];
752 if (!SP.isDefinition())
753 // This is a method declaration which will be handled while constructing
757 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
759 // Expose as a global name.
760 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
763 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
765 DIImportedEntity Module(N);
766 assert(Module.Verify());
767 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
768 constructImportedEntityDIE(TheCU, Module, D);
771 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
772 const MDNode *N, DIE *Context) {
773 DIImportedEntity Module(N);
774 assert(Module.Verify());
775 return constructImportedEntityDIE(TheCU, Module, Context);
778 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
779 const DIImportedEntity &Module,
781 assert(Module.Verify() &&
782 "Use one of the MDNode * overloads to handle invalid metadata");
783 assert(Context && "Should always have a context for an imported_module");
784 DIE *IMDie = new DIE(Module.getTag());
785 TheCU->insertDIE(Module, IMDie);
787 DIDescriptor Entity = Module.getEntity();
788 if (Entity.isNameSpace())
789 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
790 else if (Entity.isSubprogram())
791 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
792 else if (Entity.isType())
793 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
795 EntityDie = TheCU->getDIE(Entity);
796 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
797 Module.getContext().getFilename(),
798 Module.getContext().getDirectory());
799 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
800 StringRef Name = Module.getName();
802 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
803 Context->addChild(IMDie);
806 // Emit all Dwarf sections that should come prior to the content. Create
807 // global DIEs and emit initial debug info sections. This is invoked by
808 // the target AsmPrinter.
809 void DwarfDebug::beginModule() {
810 if (DisableDebugInfoPrinting)
813 const Module *M = MMI->getModule();
815 // If module has named metadata anchors then use them, otherwise scan the
816 // module using debug info finder to collect debug info.
817 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
820 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
822 // Emit initial sections so we can reference labels later.
825 auto Operands = CU_Nodes->operands();
827 bool SingleCU = std::next(Operands.begin()) == Operands.end();
829 for (MDNode *N : Operands) {
830 DICompileUnit CUNode(N);
831 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode, SingleCU);
832 DIArray ImportedEntities = CUNode.getImportedEntities();
833 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
834 ScopesWithImportedEntities.push_back(std::make_pair(
835 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
836 ImportedEntities.getElement(i)));
837 std::sort(ScopesWithImportedEntities.begin(),
838 ScopesWithImportedEntities.end(), less_first());
839 DIArray GVs = CUNode.getGlobalVariables();
840 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
841 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
842 DIArray SPs = CUNode.getSubprograms();
843 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
844 constructSubprogramDIE(CU, SPs.getElement(i));
845 DIArray EnumTypes = CUNode.getEnumTypes();
846 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
847 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
848 DIArray RetainedTypes = CUNode.getRetainedTypes();
849 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
850 DIType Ty(RetainedTypes.getElement(i));
851 // The retained types array by design contains pointers to
852 // MDNodes rather than DIRefs. Unique them here.
853 DIType UniqueTy(resolve(Ty.getRef()));
854 CU->getOrCreateTypeDIE(UniqueTy);
856 // Emit imported_modules last so that the relevant context is already
858 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
859 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
862 // Tell MMI that we have debug info.
863 MMI->setDebugInfoAvailability(true);
865 // Prime section data.
866 SectionMap[Asm->getObjFileLowering().getTextSection()];
869 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
870 void DwarfDebug::computeInlinedDIEs() {
871 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
872 for (DIE *ISP : InlinedSubprogramDIEs)
873 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
875 for (const auto &AI : AbstractSPDies) {
876 DIE *ISP = AI.second;
877 if (InlinedSubprogramDIEs.count(ISP))
879 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
883 // Collect info for variables that were optimized out.
884 void DwarfDebug::collectDeadVariables() {
885 const Module *M = MMI->getModule();
887 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
888 for (MDNode *N : CU_Nodes->operands()) {
889 DICompileUnit TheCU(N);
890 DIArray Subprograms = TheCU.getSubprograms();
891 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
892 DISubprogram SP(Subprograms.getElement(i));
893 if (ProcessedSPNodes.count(SP) != 0)
895 if (!SP.isSubprogram())
897 if (!SP.isDefinition())
899 DIArray Variables = SP.getVariables();
900 if (Variables.getNumElements() == 0)
903 // Construct subprogram DIE and add variables DIEs.
904 DwarfCompileUnit *SPCU =
905 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
906 assert(SPCU && "Unable to find Compile Unit!");
907 // FIXME: See the comment in constructSubprogramDIE about duplicate
909 constructSubprogramDIE(SPCU, SP);
910 DIE *SPDIE = SPCU->getDIE(SP);
911 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
912 DIVariable DV(Variables.getElement(vi));
913 if (!DV.isVariable())
915 DbgVariable NewVar(DV, NULL, this);
916 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
917 SPDIE->addChild(VariableDIE);
924 void DwarfDebug::finalizeModuleInfo() {
925 // Collect info for variables that were optimized out.
926 collectDeadVariables();
928 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
929 computeInlinedDIEs();
931 // Handle anything that needs to be done on a per-unit basis after
932 // all other generation.
933 for (DwarfUnit *TheU : getUnits()) {
934 // Emit DW_AT_containing_type attribute to connect types with their
935 // vtable holding type.
936 TheU->constructContainingTypeDIEs();
938 // Add CU specific attributes if we need to add any.
939 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
940 // If we're splitting the dwarf out now that we've got the entire
941 // CU then add the dwo id to it.
942 DwarfCompileUnit *SkCU =
943 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
944 if (useSplitDwarf()) {
945 // Emit a unique identifier for this CU.
946 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
947 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
948 dwarf::DW_FORM_data8, ID);
949 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
950 dwarf::DW_FORM_data8, ID);
953 // If we have code split among multiple sections or we've requested
954 // it then emit a DW_AT_ranges attribute on the unit that will remain
955 // in the .o file, otherwise add a DW_AT_low_pc.
956 // FIXME: Also add a high pc if we can.
957 // FIXME: We should use ranges if we have multiple compile units or
958 // allow reordering of code ala .subsections_via_symbols in mach-o.
959 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
960 if (useCURanges() && TheU->getRanges().size()) {
961 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
962 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
963 DwarfDebugRangeSectionSym);
965 // A DW_AT_low_pc attribute may also be specified in combination with
966 // DW_AT_ranges to specify the default base address for use in location
967 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
968 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
971 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
976 // Compute DIE offsets and sizes.
977 InfoHolder.computeSizeAndOffsets();
979 SkeletonHolder.computeSizeAndOffsets();
982 void DwarfDebug::endSections() {
983 // Filter labels by section.
984 for (const SymbolCU &SCU : ArangeLabels) {
985 if (SCU.Sym->isInSection()) {
986 // Make a note of this symbol and it's section.
987 const MCSection *Section = &SCU.Sym->getSection();
988 if (!Section->getKind().isMetadata())
989 SectionMap[Section].push_back(SCU);
991 // Some symbols (e.g. common/bss on mach-o) can have no section but still
992 // appear in the output. This sucks as we rely on sections to build
993 // arange spans. We can do it without, but it's icky.
994 SectionMap[NULL].push_back(SCU);
998 // Build a list of sections used.
999 std::vector<const MCSection *> Sections;
1000 for (const auto &it : SectionMap) {
1001 const MCSection *Section = it.first;
1002 Sections.push_back(Section);
1005 // Sort the sections into order.
1006 // This is only done to ensure consistent output order across different runs.
1007 std::sort(Sections.begin(), Sections.end(), SectionSort);
1009 // Add terminating symbols for each section.
1010 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1011 const MCSection *Section = Sections[ID];
1012 MCSymbol *Sym = NULL;
1015 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1016 // if we know the section name up-front. For user-created sections, the
1017 // resulting label may not be valid to use as a label. (section names can
1018 // use a greater set of characters on some systems)
1019 Sym = Asm->GetTempSymbol("debug_end", ID);
1020 Asm->OutStreamer.SwitchSection(Section);
1021 Asm->OutStreamer.EmitLabel(Sym);
1024 // Insert a final terminator.
1025 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1028 // For now only turn on CU ranges if we have -ffunction-sections enabled,
1029 // we've emitted a function into a unique section, or we're using LTO. If
1030 // we're using LTO then we can't know that any particular function in the
1031 // module is correlated to a particular CU and so we need to be conservative.
1032 // At this point all sections should be finalized except for dwarf sections.
1033 HasCURanges = UsedNonDefaultText || (CUMap.size() > 1) ||
1034 TargetMachine::getFunctionSections();
1037 // Emit all Dwarf sections that should come after the content.
1038 void DwarfDebug::endModule() {
1045 // End any existing sections.
1046 // TODO: Does this need to happen?
1049 // Finalize the debug info for the module.
1050 finalizeModuleInfo();
1054 // Emit all the DIEs into a debug info section.
1057 // Corresponding abbreviations into a abbrev section.
1058 emitAbbreviations();
1060 // Emit info into a debug loc section.
1063 // Emit info into a debug aranges section.
1064 if (GenerateARangeSection)
1067 // Emit info into a debug ranges section.
1070 if (useSplitDwarf()) {
1073 emitDebugAbbrevDWO();
1075 // Emit DWO addresses.
1076 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1079 // Emit info into the dwarf accelerator table sections.
1080 if (useDwarfAccelTables()) {
1083 emitAccelNamespaces();
1087 // Emit the pubnames and pubtypes sections if requested.
1088 if (HasDwarfPubSections) {
1089 emitDebugPubNames(GenerateGnuPubSections);
1090 emitDebugPubTypes(GenerateGnuPubSections);
1096 // Reset these for the next Module if we have one.
1100 // Find abstract variable, if any, associated with Var.
1101 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1102 DebugLoc ScopeLoc) {
1103 LLVMContext &Ctx = DV->getContext();
1104 // More then one inlined variable corresponds to one abstract variable.
1105 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1106 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1108 return AbsDbgVariable;
1110 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1114 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1115 addScopeVariable(Scope, AbsDbgVariable);
1116 AbstractVariables[Var] = AbsDbgVariable;
1117 return AbsDbgVariable;
1120 // If Var is a current function argument then add it to CurrentFnArguments list.
1121 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1122 if (!LScopes.isCurrentFunctionScope(Scope))
1124 DIVariable DV = Var->getVariable();
1125 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1127 unsigned ArgNo = DV.getArgNumber();
1131 size_t Size = CurrentFnArguments.size();
1133 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1134 // llvm::Function argument size is not good indicator of how many
1135 // arguments does the function have at source level.
1137 CurrentFnArguments.resize(ArgNo * 2);
1138 CurrentFnArguments[ArgNo - 1] = Var;
1142 // Collect variable information from side table maintained by MMI.
1143 void DwarfDebug::collectVariableInfoFromMMITable(
1144 SmallPtrSet<const MDNode *, 16> &Processed) {
1145 for (const auto &VI : MMI->getVariableDbgInfo()) {
1148 Processed.insert(VI.Var);
1149 DIVariable DV(VI.Var);
1150 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1152 // If variable scope is not found then skip this variable.
1156 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1157 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1158 RegVar->setFrameIndex(VI.Slot);
1159 if (!addCurrentFnArgument(RegVar, Scope))
1160 addScopeVariable(Scope, RegVar);
1162 AbsDbgVariable->setFrameIndex(VI.Slot);
1166 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1168 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1169 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1170 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1171 MI->getOperand(0).getReg() &&
1172 (MI->getOperand(1).isImm() ||
1173 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1176 // Get .debug_loc entry for the instruction range starting at MI.
1177 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1178 const MCSymbol *FLabel,
1179 const MCSymbol *SLabel,
1180 const MachineInstr *MI) {
1181 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1183 assert(MI->getNumOperands() == 3);
1184 if (MI->getOperand(0).isReg()) {
1185 MachineLocation MLoc;
1186 // If the second operand is an immediate, this is a
1187 // register-indirect address.
1188 if (!MI->getOperand(1).isImm())
1189 MLoc.set(MI->getOperand(0).getReg());
1191 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1192 return DebugLocEntry(FLabel, SLabel, MLoc, Var);
1194 if (MI->getOperand(0).isImm())
1195 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1196 if (MI->getOperand(0).isFPImm())
1197 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1198 if (MI->getOperand(0).isCImm())
1199 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1201 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1204 // Find variables for each lexical scope.
1206 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1208 // Grab the variable info that was squirreled away in the MMI side-table.
1209 collectVariableInfoFromMMITable(Processed);
1211 for (const MDNode *Var : UserVariables) {
1212 if (Processed.count(Var))
1215 // History contains relevant DBG_VALUE instructions for Var and instructions
1217 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1218 if (History.empty())
1220 const MachineInstr *MInsn = History.front();
1223 LexicalScope *Scope = NULL;
1224 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1225 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1226 Scope = LScopes.getCurrentFunctionScope();
1227 else if (MDNode *IA = DV.getInlinedAt())
1228 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1230 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1231 // If variable scope is not found then skip this variable.
1235 Processed.insert(DV);
1236 assert(MInsn->isDebugValue() && "History must begin with debug value");
1237 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1238 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1239 if (!addCurrentFnArgument(RegVar, Scope))
1240 addScopeVariable(Scope, RegVar);
1242 AbsVar->setMInsn(MInsn);
1244 // Simplify ranges that are fully coalesced.
1245 if (History.size() <= 1 ||
1246 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1247 RegVar->setMInsn(MInsn);
1251 // Handle multiple DBG_VALUE instructions describing one variable.
1252 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1254 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1255 HI = History.begin(),
1258 const MachineInstr *Begin = *HI;
1259 assert(Begin->isDebugValue() && "Invalid History entry");
1261 // Check if DBG_VALUE is truncating a range.
1262 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1263 !Begin->getOperand(0).getReg())
1266 // Compute the range for a register location.
1267 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1268 const MCSymbol *SLabel = 0;
1271 // If Begin is the last instruction in History then its value is valid
1272 // until the end of the function.
1273 SLabel = FunctionEndSym;
1275 const MachineInstr *End = HI[1];
1276 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1277 << "\t" << *Begin << "\t" << *End << "\n");
1278 if (End->isDebugValue())
1279 SLabel = getLabelBeforeInsn(End);
1281 // End is a normal instruction clobbering the range.
1282 SLabel = getLabelAfterInsn(End);
1283 assert(SLabel && "Forgot label after clobber instruction");
1288 // The value is valid until the next DBG_VALUE or clobber.
1289 DotDebugLocEntries.push_back(
1290 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1292 DotDebugLocEntries.push_back(DebugLocEntry());
1295 // Collect info for variables that were optimized out.
1296 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1297 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1298 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1299 DIVariable DV(Variables.getElement(i));
1300 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1302 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1303 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1307 // Return Label preceding the instruction.
1308 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1309 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1310 assert(Label && "Didn't insert label before instruction");
1314 // Return Label immediately following the instruction.
1315 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1316 return LabelsAfterInsn.lookup(MI);
1319 // Process beginning of an instruction.
1320 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1323 // Check if source location changes, but ignore DBG_VALUE locations.
1324 if (!MI->isDebugValue()) {
1325 DebugLoc DL = MI->getDebugLoc();
1326 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1329 if (DL == PrologEndLoc) {
1330 Flags |= DWARF2_FLAG_PROLOGUE_END;
1331 PrologEndLoc = DebugLoc();
1333 if (PrologEndLoc.isUnknown())
1334 Flags |= DWARF2_FLAG_IS_STMT;
1336 if (!DL.isUnknown()) {
1337 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1338 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1340 recordSourceLine(0, 0, 0, 0);
1344 // Insert labels where requested.
1345 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1346 LabelsBeforeInsn.find(MI);
1349 if (I == LabelsBeforeInsn.end())
1352 // Label already assigned.
1357 PrevLabel = MMI->getContext().CreateTempSymbol();
1358 Asm->OutStreamer.EmitLabel(PrevLabel);
1360 I->second = PrevLabel;
1363 // Process end of an instruction.
1364 void DwarfDebug::endInstruction() {
1366 // Don't create a new label after DBG_VALUE instructions.
1367 // They don't generate code.
1368 if (!CurMI->isDebugValue())
1371 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1372 LabelsAfterInsn.find(CurMI);
1376 if (I == LabelsAfterInsn.end())
1379 // Label already assigned.
1383 // We need a label after this instruction.
1385 PrevLabel = MMI->getContext().CreateTempSymbol();
1386 Asm->OutStreamer.EmitLabel(PrevLabel);
1388 I->second = PrevLabel;
1391 // Each LexicalScope has first instruction and last instruction to mark
1392 // beginning and end of a scope respectively. Create an inverse map that list
1393 // scopes starts (and ends) with an instruction. One instruction may start (or
1394 // end) multiple scopes. Ignore scopes that are not reachable.
1395 void DwarfDebug::identifyScopeMarkers() {
1396 SmallVector<LexicalScope *, 4> WorkList;
1397 WorkList.push_back(LScopes.getCurrentFunctionScope());
1398 while (!WorkList.empty()) {
1399 LexicalScope *S = WorkList.pop_back_val();
1401 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1402 if (!Children.empty())
1403 WorkList.append(Children.begin(), Children.end());
1405 if (S->isAbstractScope())
1408 for (const InsnRange &R : S->getRanges()) {
1409 assert(R.first && "InsnRange does not have first instruction!");
1410 assert(R.second && "InsnRange does not have second instruction!");
1411 requestLabelBeforeInsn(R.first);
1412 requestLabelAfterInsn(R.second);
1417 // Gather pre-function debug information. Assumes being called immediately
1418 // after the function entry point has been emitted.
1419 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1422 // If there's no debug info for the function we're not going to do anything.
1423 if (!MMI->hasDebugInfo())
1426 // Grab the lexical scopes for the function, if we don't have any of those
1427 // then we're not going to be able to do anything.
1428 LScopes.initialize(*MF);
1429 if (LScopes.empty()) {
1430 // If we don't have a lexical scope for this function then there will
1431 // be a hole in the range information. Keep note of this.
1432 UsedNonDefaultText = true;
1436 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1438 // Make sure that each lexical scope will have a begin/end label.
1439 identifyScopeMarkers();
1441 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1442 // belongs to so that we add to the correct per-cu line table in the
1444 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1445 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1446 assert(TheCU && "Unable to find compile unit!");
1447 if (Asm->OutStreamer.hasRawTextSupport())
1448 // Use a single line table if we are generating assembly.
1449 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1451 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1453 // Check the current section against the standard text section. If different
1454 // keep track so that we will know when we're emitting functions into multiple
1456 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1457 UsedNonDefaultText = true;
1459 // Emit a label for the function so that we have a beginning address.
1460 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1461 // Assumes in correct section after the entry point.
1462 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1464 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1465 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1466 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1468 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1470 bool AtBlockEntry = true;
1471 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1473 const MachineInstr *MI = II;
1475 if (MI->isDebugValue()) {
1476 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1478 // Keep track of user variables.
1480 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1482 // Variable is in a register, we need to check for clobbers.
1483 if (isDbgValueInDefinedReg(MI))
1484 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1486 // Check the history of this variable.
1487 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1488 if (History.empty()) {
1489 UserVariables.push_back(Var);
1490 // The first mention of a function argument gets the FunctionBeginSym
1491 // label, so arguments are visible when breaking at function entry.
1493 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1494 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1495 LabelsBeforeInsn[MI] = FunctionBeginSym;
1497 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1498 const MachineInstr *Prev = History.back();
1499 if (Prev->isDebugValue()) {
1500 // Coalesce identical entries at the end of History.
1501 if (History.size() >= 2 &&
1502 Prev->isIdenticalTo(History[History.size() - 2])) {
1503 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1504 << "\t" << *Prev << "\t"
1505 << *History[History.size() - 2] << "\n");
1509 // Terminate old register assignments that don't reach MI;
1510 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1511 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1512 isDbgValueInDefinedReg(Prev)) {
1513 // Previous register assignment needs to terminate at the end of
1515 MachineBasicBlock::const_iterator LastMI =
1516 PrevMBB->getLastNonDebugInstr();
1517 if (LastMI == PrevMBB->end()) {
1518 // Drop DBG_VALUE for empty range.
1519 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1520 << "\t" << *Prev << "\n");
1522 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1523 // Terminate after LastMI.
1524 History.push_back(LastMI);
1528 History.push_back(MI);
1530 // Not a DBG_VALUE instruction.
1531 if (!MI->isPosition())
1532 AtBlockEntry = false;
1534 // First known non-DBG_VALUE and non-frame setup location marks
1535 // the beginning of the function body.
1536 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1537 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1538 PrologEndLoc = MI->getDebugLoc();
1540 // Check if the instruction clobbers any registers with debug vars.
1541 for (const MachineOperand &MO : MI->operands()) {
1542 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1544 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1547 const MDNode *Var = LiveUserVar[Reg];
1550 // Reg is now clobbered.
1551 LiveUserVar[Reg] = 0;
1553 // Was MD last defined by a DBG_VALUE referring to Reg?
1554 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1555 if (HistI == DbgValues.end())
1557 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1558 if (History.empty())
1560 const MachineInstr *Prev = History.back();
1561 // Sanity-check: Register assignments are terminated at the end of
1563 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1565 // Is the variable still in Reg?
1566 if (!isDbgValueInDefinedReg(Prev) ||
1567 Prev->getOperand(0).getReg() != Reg)
1569 // Var is clobbered. Make sure the next instruction gets a label.
1570 History.push_back(MI);
1577 for (auto &I : DbgValues) {
1578 SmallVectorImpl<const MachineInstr *> &History = I.second;
1579 if (History.empty())
1582 // Make sure the final register assignments are terminated.
1583 const MachineInstr *Prev = History.back();
1584 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1585 const MachineBasicBlock *PrevMBB = Prev->getParent();
1586 MachineBasicBlock::const_iterator LastMI =
1587 PrevMBB->getLastNonDebugInstr();
1588 if (LastMI == PrevMBB->end())
1589 // Drop DBG_VALUE for empty range.
1591 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1592 // Terminate after LastMI.
1593 History.push_back(LastMI);
1596 // Request labels for the full history.
1597 for (const MachineInstr *MI : History) {
1598 if (MI->isDebugValue())
1599 requestLabelBeforeInsn(MI);
1601 requestLabelAfterInsn(MI);
1605 PrevInstLoc = DebugLoc();
1606 PrevLabel = FunctionBeginSym;
1608 // Record beginning of function.
1609 if (!PrologEndLoc.isUnknown()) {
1610 DebugLoc FnStartDL =
1611 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1613 FnStartDL.getLine(), FnStartDL.getCol(),
1614 FnStartDL.getScope(MF->getFunction()->getContext()),
1615 // We'd like to list the prologue as "not statements" but GDB behaves
1616 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1617 DWARF2_FLAG_IS_STMT);
1621 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1622 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1623 DIVariable DV = Var->getVariable();
1624 // Variables with positive arg numbers are parameters.
1625 if (unsigned ArgNum = DV.getArgNumber()) {
1626 // Keep all parameters in order at the start of the variable list to ensure
1627 // function types are correct (no out-of-order parameters)
1629 // This could be improved by only doing it for optimized builds (unoptimized
1630 // builds have the right order to begin with), searching from the back (this
1631 // would catch the unoptimized case quickly), or doing a binary search
1632 // rather than linear search.
1633 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1634 while (I != Vars.end()) {
1635 unsigned CurNum = (*I)->getVariable().getArgNumber();
1636 // A local (non-parameter) variable has been found, insert immediately
1640 // A later indexed parameter has been found, insert immediately before it.
1641 if (CurNum > ArgNum)
1645 Vars.insert(I, Var);
1649 Vars.push_back(Var);
1652 // Gather and emit post-function debug information.
1653 void DwarfDebug::endFunction(const MachineFunction *MF) {
1654 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1655 // though the beginFunction may not be called at all.
1656 // We should handle both cases.
1660 assert(CurFn == MF);
1663 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1668 // Define end label for subprogram.
1669 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1670 // Assumes in correct section after the entry point.
1671 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1673 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1674 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1676 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1677 collectVariableInfo(ProcessedVars);
1679 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1680 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1681 assert(TheCU && "Unable to find compile unit!");
1683 // Construct abstract scopes.
1684 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1685 DISubprogram SP(AScope->getScopeNode());
1686 if (SP.isSubprogram()) {
1687 // Collect info for variables that were optimized out.
1688 DIArray Variables = SP.getVariables();
1689 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1690 DIVariable DV(Variables.getElement(i));
1691 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1693 // Check that DbgVariable for DV wasn't created earlier, when
1694 // findAbstractVariable() was called for inlined instance of DV.
1695 LLVMContext &Ctx = DV->getContext();
1696 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1697 if (AbstractVariables.lookup(CleanDV))
1699 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1700 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1703 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1704 constructScopeDIE(TheCU, AScope);
1707 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1708 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1709 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1711 // Add the range of this function to the list of ranges for the CU.
1712 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1713 TheCU->addRange(std::move(Span));
1716 for (auto &I : ScopeVariables)
1717 DeleteContainerPointers(I.second);
1718 ScopeVariables.clear();
1719 DeleteContainerPointers(CurrentFnArguments);
1720 UserVariables.clear();
1722 AbstractVariables.clear();
1723 LabelsBeforeInsn.clear();
1724 LabelsAfterInsn.clear();
1729 // Register a source line with debug info. Returns the unique label that was
1730 // emitted and which provides correspondence to the source line list.
1731 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1736 unsigned Discriminator = 0;
1738 DIDescriptor Scope(S);
1740 if (Scope.isCompileUnit()) {
1741 DICompileUnit CU(S);
1742 Fn = CU.getFilename();
1743 Dir = CU.getDirectory();
1744 } else if (Scope.isFile()) {
1746 Fn = F.getFilename();
1747 Dir = F.getDirectory();
1748 } else if (Scope.isSubprogram()) {
1750 Fn = SP.getFilename();
1751 Dir = SP.getDirectory();
1752 } else if (Scope.isLexicalBlockFile()) {
1753 DILexicalBlockFile DBF(S);
1754 Fn = DBF.getFilename();
1755 Dir = DBF.getDirectory();
1756 } else if (Scope.isLexicalBlock()) {
1757 DILexicalBlock DB(S);
1758 Fn = DB.getFilename();
1759 Dir = DB.getDirectory();
1760 Discriminator = DB.getDiscriminator();
1762 llvm_unreachable("Unexpected scope info");
1764 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1765 Src = static_cast<DwarfCompileUnit *>(InfoHolder.getUnits()[CUID])
1766 ->getOrCreateSourceID(Fn, Dir);
1768 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1772 //===----------------------------------------------------------------------===//
1774 //===----------------------------------------------------------------------===//
1776 // Compute the size and offset of a DIE. The offset is relative to start of the
1777 // CU. It returns the offset after laying out the DIE.
1778 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1779 // Record the abbreviation.
1780 assignAbbrevNumber(Die->getAbbrev());
1782 // Get the abbreviation for this DIE.
1783 const DIEAbbrev &Abbrev = Die->getAbbrev();
1786 Die->setOffset(Offset);
1788 // Start the size with the size of abbreviation code.
1789 Offset += getULEB128Size(Die->getAbbrevNumber());
1791 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1792 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1794 // Size the DIE attribute values.
1795 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1796 // Size attribute value.
1797 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1799 // Get the children.
1800 const std::vector<DIE *> &Children = Die->getChildren();
1802 // Size the DIE children if any.
1803 if (!Children.empty()) {
1804 assert(Abbrev.hasChildren() && "Children flag not set");
1806 for (DIE *Child : Children)
1807 Offset = computeSizeAndOffset(Child, Offset);
1809 // End of children marker.
1810 Offset += sizeof(int8_t);
1813 Die->setSize(Offset - Die->getOffset());
1817 // Compute the size and offset for each DIE.
1818 void DwarfFile::computeSizeAndOffsets() {
1819 // Offset from the first CU in the debug info section is 0 initially.
1820 unsigned SecOffset = 0;
1822 // Iterate over each compile unit and set the size and offsets for each
1823 // DIE within each compile unit. All offsets are CU relative.
1824 for (DwarfUnit *TheU : CUs) {
1825 TheU->setDebugInfoOffset(SecOffset);
1827 // CU-relative offset is reset to 0 here.
1828 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1829 TheU->getHeaderSize(); // Unit-specific headers
1831 // EndOffset here is CU-relative, after laying out
1832 // all of the CU DIE.
1833 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1834 SecOffset += EndOffset;
1838 // Emit initial Dwarf sections with a label at the start of each one.
1839 void DwarfDebug::emitSectionLabels() {
1840 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1842 // Dwarf sections base addresses.
1843 DwarfInfoSectionSym =
1844 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1845 if (useSplitDwarf())
1846 DwarfInfoDWOSectionSym =
1847 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1848 DwarfAbbrevSectionSym =
1849 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1850 if (useSplitDwarf())
1851 DwarfAbbrevDWOSectionSym = emitSectionSym(
1852 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1853 if (GenerateARangeSection)
1854 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1856 DwarfLineSectionSym =
1857 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1858 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1859 if (GenerateGnuPubSections) {
1860 DwarfGnuPubNamesSectionSym =
1861 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1862 DwarfGnuPubTypesSectionSym =
1863 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1864 } else if (HasDwarfPubSections) {
1865 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1866 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1869 DwarfStrSectionSym =
1870 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1871 if (useSplitDwarf()) {
1872 DwarfStrDWOSectionSym =
1873 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1874 DwarfAddrSectionSym =
1875 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1877 DwarfDebugRangeSectionSym =
1878 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1880 DwarfDebugLocSectionSym =
1881 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1884 // Recursively emits a debug information entry.
1885 void DwarfDebug::emitDIE(DIE *Die) {
1886 // Get the abbreviation for this DIE.
1887 const DIEAbbrev &Abbrev = Die->getAbbrev();
1889 // Emit the code (index) for the abbreviation.
1890 if (Asm->isVerbose())
1891 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1892 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1893 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1894 dwarf::TagString(Abbrev.getTag()));
1895 Asm->EmitULEB128(Abbrev.getNumber());
1897 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1898 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1900 // Emit the DIE attribute values.
1901 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1902 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1903 dwarf::Form Form = AbbrevData[i].getForm();
1904 assert(Form && "Too many attributes for DIE (check abbreviation)");
1906 if (Asm->isVerbose()) {
1907 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1908 if (Attr == dwarf::DW_AT_accessibility)
1909 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1910 cast<DIEInteger>(Values[i])->getValue()));
1913 // Emit an attribute using the defined form.
1914 Values[i]->EmitValue(Asm, Form);
1917 // Emit the DIE children if any.
1918 if (Abbrev.hasChildren()) {
1919 const std::vector<DIE *> &Children = Die->getChildren();
1921 for (DIE *Child : Children)
1924 Asm->OutStreamer.AddComment("End Of Children Mark");
1929 // Emit the various dwarf units to the unit section USection with
1930 // the abbreviations going into ASection.
1931 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1932 const MCSymbol *ASectionSym) {
1933 for (DwarfUnit *TheU : CUs) {
1934 DIE *Die = TheU->getUnitDie();
1935 const MCSection *USection = TheU->getSection();
1936 Asm->OutStreamer.SwitchSection(USection);
1938 // Emit the compile units header.
1939 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1941 // Emit size of content not including length itself
1942 Asm->OutStreamer.AddComment("Length of Unit");
1943 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1945 TheU->emitHeader(ASection, ASectionSym);
1948 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1952 // Emit the debug info section.
1953 void DwarfDebug::emitDebugInfo() {
1954 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1956 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1957 DwarfAbbrevSectionSym);
1960 // Emit the abbreviation section.
1961 void DwarfDebug::emitAbbreviations() {
1962 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1964 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1967 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1968 // Check to see if it is worth the effort.
1969 if (!Abbreviations.empty()) {
1970 // Start the debug abbrev section.
1971 Asm->OutStreamer.SwitchSection(Section);
1973 // For each abbrevation.
1974 for (const DIEAbbrev *Abbrev : Abbreviations) {
1975 // Emit the abbrevations code (base 1 index.)
1976 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1978 // Emit the abbreviations data.
1982 // Mark end of abbreviations.
1983 Asm->EmitULEB128(0, "EOM(3)");
1987 // Emit the last address of the section and the end of the line matrix.
1988 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1989 // Define last address of section.
1990 Asm->OutStreamer.AddComment("Extended Op");
1993 Asm->OutStreamer.AddComment("Op size");
1994 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1995 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1996 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1998 Asm->OutStreamer.AddComment("Section end label");
2000 Asm->OutStreamer.EmitSymbolValue(
2001 Asm->GetTempSymbol("section_end", SectionEnd),
2002 Asm->getDataLayout().getPointerSize());
2004 // Mark end of matrix.
2005 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2011 // Emit visible names into a hashed accelerator table section.
2012 void DwarfDebug::emitAccelNames() {
2014 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2015 for (DwarfUnit *TheU : getUnits()) {
2016 for (const auto &GI : TheU->getAccelNames()) {
2017 StringRef Name = GI.getKey();
2018 for (const DIE *D : GI.second)
2019 AT.AddName(Name, D);
2023 AT.FinalizeTable(Asm, "Names");
2024 Asm->OutStreamer.SwitchSection(
2025 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2026 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2027 Asm->OutStreamer.EmitLabel(SectionBegin);
2029 // Emit the full data.
2030 AT.Emit(Asm, SectionBegin, &InfoHolder);
2033 // Emit objective C classes and categories into a hashed accelerator table
2035 void DwarfDebug::emitAccelObjC() {
2037 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2038 for (DwarfUnit *TheU : getUnits()) {
2039 for (const auto &GI : TheU->getAccelObjC()) {
2040 StringRef Name = GI.getKey();
2041 for (const DIE *D : GI.second)
2042 AT.AddName(Name, D);
2046 AT.FinalizeTable(Asm, "ObjC");
2047 Asm->OutStreamer.SwitchSection(
2048 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2049 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2050 Asm->OutStreamer.EmitLabel(SectionBegin);
2052 // Emit the full data.
2053 AT.Emit(Asm, SectionBegin, &InfoHolder);
2056 // Emit namespace dies into a hashed accelerator table.
2057 void DwarfDebug::emitAccelNamespaces() {
2059 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2060 for (DwarfUnit *TheU : getUnits()) {
2061 for (const auto &GI : TheU->getAccelNamespace()) {
2062 StringRef Name = GI.getKey();
2063 for (const DIE *D : GI.second)
2064 AT.AddName(Name, D);
2068 AT.FinalizeTable(Asm, "namespac");
2069 Asm->OutStreamer.SwitchSection(
2070 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2071 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2072 Asm->OutStreamer.EmitLabel(SectionBegin);
2074 // Emit the full data.
2075 AT.Emit(Asm, SectionBegin, &InfoHolder);
2078 // Emit type dies into a hashed accelerator table.
2079 void DwarfDebug::emitAccelTypes() {
2080 std::vector<DwarfAccelTable::Atom> Atoms;
2082 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2084 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2086 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2087 DwarfAccelTable AT(Atoms);
2088 for (DwarfUnit *TheU : getUnits()) {
2089 for (const auto &GI : TheU->getAccelTypes()) {
2090 StringRef Name = GI.getKey();
2091 for (const auto &DI : GI.second)
2092 AT.AddName(Name, DI.first, DI.second);
2096 AT.FinalizeTable(Asm, "types");
2097 Asm->OutStreamer.SwitchSection(
2098 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2099 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2100 Asm->OutStreamer.EmitLabel(SectionBegin);
2102 // Emit the full data.
2103 AT.Emit(Asm, SectionBegin, &InfoHolder);
2106 // Public name handling.
2107 // The format for the various pubnames:
2109 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2110 // for the DIE that is named.
2112 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2113 // into the CU and the index value is computed according to the type of value
2114 // for the DIE that is named.
2116 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2117 // it's the offset within the debug_info/debug_types dwo section, however, the
2118 // reference in the pubname header doesn't change.
2120 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2121 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2123 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2125 // We could have a specification DIE that has our most of our knowledge,
2126 // look for that now.
2127 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2129 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2130 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2131 Linkage = dwarf::GIEL_EXTERNAL;
2132 } else if (Die->findAttribute(dwarf::DW_AT_external))
2133 Linkage = dwarf::GIEL_EXTERNAL;
2135 switch (Die->getTag()) {
2136 case dwarf::DW_TAG_class_type:
2137 case dwarf::DW_TAG_structure_type:
2138 case dwarf::DW_TAG_union_type:
2139 case dwarf::DW_TAG_enumeration_type:
2140 return dwarf::PubIndexEntryDescriptor(
2141 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2142 ? dwarf::GIEL_STATIC
2143 : dwarf::GIEL_EXTERNAL);
2144 case dwarf::DW_TAG_typedef:
2145 case dwarf::DW_TAG_base_type:
2146 case dwarf::DW_TAG_subrange_type:
2147 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2148 case dwarf::DW_TAG_namespace:
2149 return dwarf::GIEK_TYPE;
2150 case dwarf::DW_TAG_subprogram:
2151 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2152 case dwarf::DW_TAG_constant:
2153 case dwarf::DW_TAG_variable:
2154 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2155 case dwarf::DW_TAG_enumerator:
2156 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2157 dwarf::GIEL_STATIC);
2159 return dwarf::GIEK_NONE;
2163 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2165 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2166 const MCSection *PSec =
2167 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2168 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2170 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2173 void DwarfDebug::emitDebugPubSection(
2174 bool GnuStyle, const MCSection *PSec, StringRef Name,
2175 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2176 for (const auto &NU : CUMap) {
2177 DwarfCompileUnit *TheU = NU.second;
2179 const auto &Globals = (TheU->*Accessor)();
2181 if (Globals.empty())
2184 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2186 unsigned ID = TheU->getUniqueID();
2188 // Start the dwarf pubnames section.
2189 Asm->OutStreamer.SwitchSection(PSec);
2192 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2193 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2194 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2195 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2197 Asm->OutStreamer.EmitLabel(BeginLabel);
2199 Asm->OutStreamer.AddComment("DWARF Version");
2200 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2202 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2203 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2205 Asm->OutStreamer.AddComment("Compilation Unit Length");
2206 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2208 // Emit the pubnames for this compilation unit.
2209 for (const auto &GI : Globals) {
2210 const char *Name = GI.getKeyData();
2211 const DIE *Entity = GI.second;
2213 Asm->OutStreamer.AddComment("DIE offset");
2214 Asm->EmitInt32(Entity->getOffset());
2217 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2218 Asm->OutStreamer.AddComment(
2219 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2220 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2221 Asm->EmitInt8(Desc.toBits());
2224 Asm->OutStreamer.AddComment("External Name");
2225 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2228 Asm->OutStreamer.AddComment("End Mark");
2230 Asm->OutStreamer.EmitLabel(EndLabel);
2234 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2235 const MCSection *PSec =
2236 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2237 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2239 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2242 // Emit strings into a string section.
2243 void DwarfFile::emitStrings(const MCSection *StrSection,
2244 const MCSection *OffsetSection = NULL,
2245 const MCSymbol *StrSecSym = NULL) {
2247 if (StringPool.empty())
2250 // Start the dwarf str section.
2251 Asm->OutStreamer.SwitchSection(StrSection);
2253 // Get all of the string pool entries and put them in an array by their ID so
2254 // we can sort them.
2255 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2257 for (const auto &I : StringPool)
2258 Entries.push_back(std::make_pair(I.second.second, &I));
2260 array_pod_sort(Entries.begin(), Entries.end());
2262 for (const auto &Entry : Entries) {
2263 // Emit a label for reference from debug information entries.
2264 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2266 // Emit the string itself with a terminating null byte.
2267 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2268 Entry.second->getKeyLength() + 1));
2271 // If we've got an offset section go ahead and emit that now as well.
2272 if (OffsetSection) {
2273 Asm->OutStreamer.SwitchSection(OffsetSection);
2274 unsigned offset = 0;
2275 unsigned size = 4; // FIXME: DWARF64 is 8.
2276 for (const auto &Entry : Entries) {
2277 Asm->OutStreamer.EmitIntValue(offset, size);
2278 offset += Entry.second->getKeyLength() + 1;
2283 // Emit addresses into the section given.
2284 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2286 if (AddressPool.empty())
2289 // Start the dwarf addr section.
2290 Asm->OutStreamer.SwitchSection(AddrSection);
2292 // Order the address pool entries by ID
2293 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2295 for (const auto &I : AddressPool)
2296 Entries[I.second.Number] =
2298 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2299 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2301 for (const MCExpr *Entry : Entries)
2302 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2305 // Emit visible names into a debug str section.
2306 void DwarfDebug::emitDebugStr() {
2307 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2308 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2311 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2312 const DebugLocEntry &Entry) {
2313 DIVariable DV(Entry.getVariable());
2314 if (Entry.isInt()) {
2315 DIBasicType BTy(resolve(DV.getType()));
2316 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2317 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2318 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2319 Streamer.EmitSLEB128(Entry.getInt());
2321 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2322 Streamer.EmitULEB128(Entry.getInt());
2324 } else if (Entry.isLocation()) {
2325 MachineLocation Loc = Entry.getLoc();
2326 if (!DV.hasComplexAddress())
2328 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2330 // Complex address entry.
2331 unsigned N = DV.getNumAddrElements();
2333 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2334 if (Loc.getOffset()) {
2336 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2337 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2338 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2339 Streamer.EmitSLEB128(DV.getAddrElement(1));
2341 // If first address element is OpPlus then emit
2342 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2343 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2344 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2348 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2351 // Emit remaining complex address elements.
2352 for (; i < N; ++i) {
2353 uint64_t Element = DV.getAddrElement(i);
2354 if (Element == DIBuilder::OpPlus) {
2355 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2356 Streamer.EmitULEB128(DV.getAddrElement(++i));
2357 } else if (Element == DIBuilder::OpDeref) {
2359 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2361 llvm_unreachable("unknown Opcode found in complex address");
2365 // else ... ignore constant fp. There is not any good way to
2366 // to represent them here in dwarf.
2370 // Emit locations into the debug loc section.
2371 void DwarfDebug::emitDebugLoc() {
2372 if (DotDebugLocEntries.empty())
2375 for (SmallVectorImpl<DebugLocEntry>::iterator
2376 I = DotDebugLocEntries.begin(),
2377 E = DotDebugLocEntries.end();
2379 DebugLocEntry &Entry = *I;
2380 if (I + 1 != DotDebugLocEntries.end())
2384 // Start the dwarf loc section.
2385 Asm->OutStreamer.SwitchSection(
2386 Asm->getObjFileLowering().getDwarfLocSection());
2387 unsigned char Size = Asm->getDataLayout().getPointerSize();
2388 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2390 for (SmallVectorImpl<DebugLocEntry>::const_iterator
2391 I = DotDebugLocEntries.begin(),
2392 E = DotDebugLocEntries.end();
2393 I != E; ++I, ++index) {
2394 const DebugLocEntry &Entry = *I;
2395 if (Entry.isMerged())
2398 if (Entry.isEmpty()) {
2399 Asm->OutStreamer.EmitIntValue(0, Size);
2400 Asm->OutStreamer.EmitIntValue(0, Size);
2401 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2403 // Set up the range.
2404 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2405 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2406 Asm->OutStreamer.AddComment("Loc expr size");
2407 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2408 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2409 Asm->EmitLabelDifference(end, begin, 2);
2410 Asm->OutStreamer.EmitLabel(begin);
2412 APByteStreamer Streamer(*Asm);
2413 emitDebugLocEntry(Streamer, Entry);
2415 Asm->OutStreamer.EmitLabel(end);
2421 const MCSymbol *Start, *End;
2424 // Emit a debug aranges section, containing a CU lookup for any
2425 // address we can tie back to a CU.
2426 void DwarfDebug::emitDebugARanges() {
2427 // Start the dwarf aranges section.
2428 Asm->OutStreamer.SwitchSection(
2429 Asm->getObjFileLowering().getDwarfARangesSection());
2431 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2435 // Build a list of sections used.
2436 std::vector<const MCSection *> Sections;
2437 for (const auto &it : SectionMap) {
2438 const MCSection *Section = it.first;
2439 Sections.push_back(Section);
2442 // Sort the sections into order.
2443 // This is only done to ensure consistent output order across different runs.
2444 std::sort(Sections.begin(), Sections.end(), SectionSort);
2446 // Build a set of address spans, sorted by CU.
2447 for (const MCSection *Section : Sections) {
2448 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2449 if (List.size() < 2)
2452 // Sort the symbols by offset within the section.
2453 std::sort(List.begin(), List.end(),
2454 [&](const SymbolCU &A, const SymbolCU &B) {
2455 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2456 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2458 // Symbols with no order assigned should be placed at the end.
2459 // (e.g. section end labels)
2467 // If we have no section (e.g. common), just write out
2468 // individual spans for each symbol.
2469 if (Section == NULL) {
2470 for (const SymbolCU &Cur : List) {
2472 Span.Start = Cur.Sym;
2475 Spans[Cur.CU].push_back(Span);
2478 // Build spans between each label.
2479 const MCSymbol *StartSym = List[0].Sym;
2480 for (size_t n = 1, e = List.size(); n < e; n++) {
2481 const SymbolCU &Prev = List[n - 1];
2482 const SymbolCU &Cur = List[n];
2484 // Try and build the longest span we can within the same CU.
2485 if (Cur.CU != Prev.CU) {
2487 Span.Start = StartSym;
2489 Spans[Prev.CU].push_back(Span);
2496 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2498 // Build a list of CUs used.
2499 std::vector<DwarfCompileUnit *> CUs;
2500 for (const auto &it : Spans) {
2501 DwarfCompileUnit *CU = it.first;
2505 // Sort the CU list (again, to ensure consistent output order).
2506 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2507 return A->getUniqueID() < B->getUniqueID();
2510 // Emit an arange table for each CU we used.
2511 for (DwarfCompileUnit *CU : CUs) {
2512 std::vector<ArangeSpan> &List = Spans[CU];
2514 // Emit size of content not including length itself.
2515 unsigned ContentSize =
2516 sizeof(int16_t) + // DWARF ARange version number
2517 sizeof(int32_t) + // Offset of CU in the .debug_info section
2518 sizeof(int8_t) + // Pointer Size (in bytes)
2519 sizeof(int8_t); // Segment Size (in bytes)
2521 unsigned TupleSize = PtrSize * 2;
2523 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2525 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2527 ContentSize += Padding;
2528 ContentSize += (List.size() + 1) * TupleSize;
2530 // For each compile unit, write the list of spans it covers.
2531 Asm->OutStreamer.AddComment("Length of ARange Set");
2532 Asm->EmitInt32(ContentSize);
2533 Asm->OutStreamer.AddComment("DWARF Arange version number");
2534 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2535 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2536 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2537 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2538 Asm->EmitInt8(PtrSize);
2539 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2542 Asm->OutStreamer.EmitFill(Padding, 0xff);
2544 for (const ArangeSpan &Span : List) {
2545 Asm->EmitLabelReference(Span.Start, PtrSize);
2547 // Calculate the size as being from the span start to it's end.
2549 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2551 // For symbols without an end marker (e.g. common), we
2552 // write a single arange entry containing just that one symbol.
2553 uint64_t Size = SymSize[Span.Start];
2557 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2561 Asm->OutStreamer.AddComment("ARange terminator");
2562 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2563 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2567 // Emit visible names into a debug ranges section.
2568 void DwarfDebug::emitDebugRanges() {
2569 // Start the dwarf ranges section.
2570 Asm->OutStreamer.SwitchSection(
2571 Asm->getObjFileLowering().getDwarfRangesSection());
2573 // Size for our labels.
2574 unsigned char Size = Asm->getDataLayout().getPointerSize();
2576 // Grab the specific ranges for the compile units in the module.
2577 for (const auto &I : CUMap) {
2578 DwarfCompileUnit *TheCU = I.second;
2580 // Emit a symbol so we can find the beginning of our ranges.
2581 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2583 // Iterate over the misc ranges for the compile units in the module.
2584 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2585 // Emit our symbol so we can find the beginning of the range.
2586 Asm->OutStreamer.EmitLabel(List.getSym());
2588 for (const RangeSpan &Range : List.getRanges()) {
2589 const MCSymbol *Begin = Range.getStart();
2590 const MCSymbol *End = Range.getEnd();
2591 assert(Begin && "Range without a begin symbol?");
2592 assert(End && "Range without an end symbol?");
2593 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2594 Asm->OutStreamer.EmitSymbolValue(End, Size);
2597 // And terminate the list with two 0 values.
2598 Asm->OutStreamer.EmitIntValue(0, Size);
2599 Asm->OutStreamer.EmitIntValue(0, Size);
2602 // Now emit a range for the CU itself.
2603 if (useCURanges() && TheCU->getRanges().size()) {
2604 Asm->OutStreamer.EmitLabel(
2605 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2606 for (const RangeSpan &Range : TheCU->getRanges()) {
2607 const MCSymbol *Begin = Range.getStart();
2608 const MCSymbol *End = Range.getEnd();
2609 assert(Begin && "Range without a begin symbol?");
2610 assert(End && "Range without an end symbol?");
2611 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2612 Asm->OutStreamer.EmitSymbolValue(End, Size);
2614 // And terminate the list with two 0 values.
2615 Asm->OutStreamer.EmitIntValue(0, Size);
2616 Asm->OutStreamer.EmitIntValue(0, Size);
2621 // DWARF5 Experimental Separate Dwarf emitters.
2623 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2625 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2626 U->getCUNode().getSplitDebugFilename());
2628 // Relocate to the beginning of the addr_base section, else 0 for the
2629 // beginning of the one for this compile unit.
2630 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2631 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2633 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2635 if (!CompilationDir.empty())
2636 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2638 addGnuPubAttributes(NewU, Die);
2640 SkeletonHolder.addUnit(NewU);
2643 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2644 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2645 // DW_AT_ranges_base, DW_AT_addr_base.
2646 // TODO: Implement DW_AT_ranges_base.
2647 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2649 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2650 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2651 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2652 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2653 DwarfInfoSectionSym);
2655 NewCU->initStmtList(DwarfLineSectionSym);
2657 initSkeletonUnit(CU, Die, NewCU);
2662 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2664 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2665 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2666 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2668 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2669 DwarfTypeUnit *NewTU =
2670 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2671 NewTU->setTypeSignature(TU->getTypeSignature());
2672 NewTU->setType(NULL);
2674 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2676 initSkeletonUnit(TU, Die, NewTU);
2680 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2681 // compile units that would normally be in debug_info.
2682 void DwarfDebug::emitDebugInfoDWO() {
2683 assert(useSplitDwarf() && "No split dwarf debug info?");
2684 InfoHolder.emitUnits(this,
2685 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2686 DwarfAbbrevDWOSectionSym);
2689 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2690 // abbreviations for the .debug_info.dwo section.
2691 void DwarfDebug::emitDebugAbbrevDWO() {
2692 assert(useSplitDwarf() && "No split dwarf?");
2693 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2696 void DwarfDebug::emitDebugLineDWO() {
2697 assert(useSplitDwarf() && "No split dwarf?");
2698 Asm->OutStreamer.SwitchSection(
2699 Asm->getObjFileLowering().getDwarfLineDWOSection());
2700 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2703 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2704 // string section and is identical in format to traditional .debug_str
2706 void DwarfDebug::emitDebugStrDWO() {
2707 assert(useSplitDwarf() && "No split dwarf?");
2708 const MCSection *OffSec =
2709 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2710 const MCSymbol *StrSym = DwarfStrSectionSym;
2711 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2715 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2716 StringRef Identifier, DIE *RefDie,
2717 DICompositeType CTy) {
2718 // Flag the type unit reference as a declaration so that if it contains
2719 // members (implicit special members, static data member definitions, member
2720 // declarations for definitions in this CU, etc) consumers don't get confused
2721 // and think this is a full definition.
2722 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2724 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2726 CU.addDIETypeSignature(RefDie, *TU);
2730 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2731 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
2732 InfoHolder.getUnits().size(), UnitDie, CU, Asm, this, &InfoHolder,
2733 useSplitDwarf() ? &SplitTypeUnitFileTable : nullptr);
2735 InfoHolder.addUnit(NewTU);
2737 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2741 Hash.update(Identifier);
2742 // ... take the least significant 8 bytes and return those. Our MD5
2743 // implementation always returns its results in little endian, swap bytes
2745 MD5::MD5Result Result;
2747 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2748 NewTU->setTypeSignature(Signature);
2749 if (useSplitDwarf())
2750 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2752 CU.applyStmtList(*UnitDie);
2754 NewTU->setType(NewTU->createTypeDIE(CTy));
2758 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2759 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2761 CU.addDIETypeSignature(RefDie, *NewTU);
2764 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2765 MCSymbol *Begin, MCSymbol *End) {
2766 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2767 if (DwarfVersion < 4)
2768 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2770 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);