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 DIType DbgVariable::getType() const {
119 DIType Ty = Var.getType();
120 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
121 // addresses instead.
122 if (Var.isBlockByrefVariable()) {
123 /* Byref variables, in Blocks, are declared by the programmer as
124 "SomeType VarName;", but the compiler creates a
125 __Block_byref_x_VarName struct, and gives the variable VarName
126 either the struct, or a pointer to the struct, as its type. This
127 is necessary for various behind-the-scenes things the compiler
128 needs to do with by-reference variables in blocks.
130 However, as far as the original *programmer* is concerned, the
131 variable should still have type 'SomeType', as originally declared.
133 The following function dives into the __Block_byref_x_VarName
134 struct to find the original type of the variable. This will be
135 passed back to the code generating the type for the Debug
136 Information Entry for the variable 'VarName'. 'VarName' will then
137 have the original type 'SomeType' in its debug information.
139 The original type 'SomeType' will be the type of the field named
140 'VarName' inside the __Block_byref_x_VarName struct.
142 NOTE: In order for this to not completely fail on the debugger
143 side, the Debug Information Entry for the variable VarName needs to
144 have a DW_AT_location that tells the debugger how to unwind through
145 the pointers and __Block_byref_x_VarName struct to find the actual
146 value of the variable. The function addBlockByrefType does this. */
148 uint16_t tag = Ty.getTag();
150 if (tag == dwarf::DW_TAG_pointer_type)
151 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
153 DIArray Elements = DICompositeType(subType).getTypeArray();
154 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
155 DIDerivedType DT(Elements.getElement(i));
156 if (getName() == DT.getName())
157 return (resolve(DT.getTypeDerivedFrom()));
163 } // end llvm namespace
165 /// Return Dwarf Version by checking module flags.
166 static unsigned getDwarfVersionFromModule(const Module *M) {
167 Value *Val = M->getModuleFlag("Dwarf Version");
169 return dwarf::DWARF_VERSION;
170 return cast<ConstantInt>(Val)->getZExtValue();
173 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
174 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
175 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
176 UsedNonDefaultText(false),
177 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
179 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
180 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
181 DwarfAddrSectionSym = 0;
182 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
183 FunctionBeginSym = FunctionEndSym = 0;
187 // Turn on accelerator tables for Darwin by default, pubnames by
188 // default for non-Darwin, and handle split dwarf.
189 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
191 if (DwarfAccelTables == Default)
192 HasDwarfAccelTables = IsDarwin;
194 HasDwarfAccelTables = DwarfAccelTables == Enable;
196 if (SplitDwarf == Default)
197 HasSplitDwarf = false;
199 HasSplitDwarf = SplitDwarf == Enable;
201 if (DwarfPubSections == Default)
202 HasDwarfPubSections = !IsDarwin;
204 HasDwarfPubSections = DwarfPubSections == Enable;
206 DwarfVersion = DwarfVersionNumber
208 : getDwarfVersionFromModule(MMI->getModule());
211 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
216 // Switch to the specified MCSection and emit an assembler
217 // temporary label to it if SymbolStem is specified.
218 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
219 const char *SymbolStem = 0) {
220 Asm->OutStreamer.SwitchSection(Section);
224 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
225 Asm->OutStreamer.EmitLabel(TmpSym);
229 DwarfFile::~DwarfFile() {
230 for (DwarfUnit *DU : CUs)
234 MCSymbol *DwarfFile::getStringPoolSym() {
235 return Asm->GetTempSymbol(StringPref);
238 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
239 std::pair<MCSymbol *, unsigned> &Entry =
240 StringPool.GetOrCreateValue(Str).getValue();
244 Entry.second = NextStringPoolNumber++;
245 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
248 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
249 std::pair<MCSymbol *, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
254 Entry.second = NextStringPoolNumber++;
255 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
259 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
260 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
261 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
263 ++NextAddrPoolNumber;
264 return P.first->second.Number;
267 // Define a unique number for the abbreviation.
269 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
270 // Check the set for priors.
271 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
273 // If it's newly added.
274 if (InSet == &Abbrev) {
275 // Add to abbreviation list.
276 Abbreviations.push_back(&Abbrev);
278 // Assign the vector position + 1 as its number.
279 Abbrev.setNumber(Abbreviations.size());
281 // Assign existing abbreviation number.
282 Abbrev.setNumber(InSet->getNumber());
286 static bool isObjCClass(StringRef Name) {
287 return Name.startswith("+") || Name.startswith("-");
290 static bool hasObjCCategory(StringRef Name) {
291 if (!isObjCClass(Name))
294 return Name.find(") ") != StringRef::npos;
297 static void getObjCClassCategory(StringRef In, StringRef &Class,
298 StringRef &Category) {
299 if (!hasObjCCategory(In)) {
300 Class = In.slice(In.find('[') + 1, In.find(' '));
305 Class = In.slice(In.find('[') + 1, In.find('('));
306 Category = In.slice(In.find('[') + 1, In.find(' '));
310 static StringRef getObjCMethodName(StringRef In) {
311 return In.slice(In.find(' ') + 1, In.find(']'));
314 // Helper for sorting sections into a stable output order.
315 static bool SectionSort(const MCSection *A, const MCSection *B) {
316 std::string LA = (A ? A->getLabelBeginName() : "");
317 std::string LB = (B ? B->getLabelBeginName() : "");
321 // Add the various names to the Dwarf accelerator table names.
322 // TODO: Determine whether or not we should add names for programs
323 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
324 // is only slightly different than the lookup of non-standard ObjC names.
325 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
326 if (!SP.isDefinition())
328 TheU->addAccelName(SP.getName(), Die);
330 // If the linkage name is different than the name, go ahead and output
331 // that as well into the name table.
332 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
333 TheU->addAccelName(SP.getLinkageName(), Die);
335 // If this is an Objective-C selector name add it to the ObjC accelerator
337 if (isObjCClass(SP.getName())) {
338 StringRef Class, Category;
339 getObjCClassCategory(SP.getName(), Class, Category);
340 TheU->addAccelObjC(Class, Die);
342 TheU->addAccelObjC(Category, Die);
343 // Also add the base method name to the name table.
344 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
348 /// isSubprogramContext - Return true if Context is either a subprogram
349 /// or another context nested inside a subprogram.
350 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
353 DIDescriptor D(Context);
354 if (D.isSubprogram())
357 return isSubprogramContext(resolve(DIType(Context).getContext()));
361 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
362 // and DW_AT_high_pc attributes. If there are global variables in this
363 // scope then create and insert DIEs for these variables.
364 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
366 SP = SPCU->getOdrUniqueSubprogram(resolve(SP.getContext()), SP);
367 DIE *SPDie = SPCU->getDIE(SP);
369 assert(SPDie && "Unable to find subprogram DIE!");
371 // If we're updating an abstract DIE, then we will be adding the children and
372 // object pointer later on. But what we don't want to do is process the
373 // concrete DIE twice.
374 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
375 // Pick up abstract subprogram DIE.
377 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
378 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
380 DISubprogram SPDecl = SP.getFunctionDeclaration();
381 if (!SPDecl.isSubprogram()) {
382 // There is not any need to generate specification DIE for a function
383 // defined at compile unit level. If a function is defined inside another
384 // function then gdb prefers the definition at top level and but does not
385 // expect specification DIE in parent function. So avoid creating
386 // specification DIE for a function defined inside a function.
387 DIScope SPContext = resolve(SP.getContext());
388 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
389 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
390 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
393 DICompositeType SPTy = SP.getType();
394 DIArray Args = SPTy.getTypeArray();
395 uint16_t SPTag = SPTy.getTag();
396 if (SPTag == dwarf::DW_TAG_subroutine_type)
397 SPCU->constructSubprogramArguments(*SPDie, Args);
398 DIE *SPDeclDie = SPDie;
399 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
400 *SPCU->getUnitDie());
401 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
406 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
408 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
409 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
410 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
412 // Add name to the name table, we do this here because we're guaranteed
413 // to have concrete versions of our DW_TAG_subprogram nodes.
414 addSubprogramNames(SPCU, SP, SPDie);
419 /// Check whether we should create a DIE for the given Scope, return true
420 /// if we don't create a DIE (the corresponding DIE is null).
421 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
422 if (Scope->isAbstractScope())
425 // We don't create a DIE if there is no Range.
426 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
430 if (Ranges.size() > 1)
433 // We don't create a DIE if we have a single Range and the end label
435 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
436 MCSymbol *End = getLabelAfterInsn(RI->second);
440 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
441 dwarf::Attribute A, const MCSymbol *L,
442 const MCSymbol *Sec) {
443 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
444 U->addSectionLabel(D, A, L);
446 U->addSectionDelta(D, A, L, Sec);
449 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
450 const SmallVectorImpl<InsnRange> &Range) {
451 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
452 // emitting it appropriately.
453 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
454 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
455 DwarfDebugRangeSectionSym);
457 RangeSpanList List(RangeSym);
458 for (const InsnRange &R : Range) {
459 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
460 List.addRange(std::move(Span));
463 // Add the range list to the set of ranges to be emitted.
464 TheCU->addRangeList(std::move(List));
467 // Construct new DW_TAG_lexical_block for this scope and attach
468 // DW_AT_low_pc/DW_AT_high_pc labels.
469 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
470 LexicalScope *Scope) {
471 if (isLexicalScopeDIENull(Scope))
474 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
475 if (Scope->isAbstractScope())
478 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
480 // If we have multiple ranges, emit them into the range section.
481 if (ScopeRanges.size() > 1) {
482 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
486 // Construct the address range for this DIE.
487 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
488 MCSymbol *Start = getLabelBeforeInsn(RI->first);
489 MCSymbol *End = getLabelAfterInsn(RI->second);
490 assert(End && "End label should not be null!");
492 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
493 assert(End->isDefined() && "Invalid end label for an inlined scope!");
495 attachLowHighPC(TheCU, ScopeDIE, Start, End);
500 // This scope represents inlined body of a function. Construct DIE to
501 // represent this concrete inlined copy of the function.
502 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
503 LexicalScope *Scope) {
504 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
505 assert(!ScopeRanges.empty() &&
506 "LexicalScope does not have instruction markers!");
508 if (!Scope->getScopeNode())
510 DIScope DS(Scope->getScopeNode());
511 DISubprogram InlinedSP = getDISubprogram(DS);
512 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
514 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
518 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
519 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
521 // If we have multiple ranges, emit them into the range section.
522 if (ScopeRanges.size() > 1)
523 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
525 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
526 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
527 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
529 if (StartLabel == 0 || EndLabel == 0)
530 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
532 assert(StartLabel->isDefined() &&
533 "Invalid starting label for an inlined scope!");
534 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
536 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
539 InlinedSubprogramDIEs.insert(OriginDIE);
541 // Add the call site information to the DIE.
542 DILocation DL(Scope->getInlinedAt());
544 ScopeDIE, dwarf::DW_AT_call_file, None,
545 TheCU->getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
546 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
548 // Add name to the name table, we do this here because we're guaranteed
549 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
550 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
555 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
557 SmallVectorImpl<DIE *> &Children) {
558 DIE *ObjectPointer = NULL;
560 // Collect arguments for current function.
561 if (LScopes.isCurrentFunctionScope(Scope)) {
562 for (DbgVariable *ArgDV : CurrentFnArguments)
565 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
566 Children.push_back(Arg);
567 if (ArgDV->isObjectPointer())
571 // If this is a variadic function, add an unspecified parameter.
572 DISubprogram SP(Scope->getScopeNode());
573 DIArray FnArgs = SP.getType().getTypeArray();
574 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
575 .isUnspecifiedParameter()) {
576 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
577 Children.push_back(Ellipsis);
581 // Collect lexical scope children first.
582 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
583 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
584 Scope->isAbstractScope())) {
585 Children.push_back(Variable);
586 if (DV->isObjectPointer())
587 ObjectPointer = Variable;
589 for (LexicalScope *LS : Scope->getChildren())
590 if (DIE *Nested = constructScopeDIE(TheCU, LS))
591 Children.push_back(Nested);
592 return ObjectPointer;
595 // Construct a DIE for this scope.
596 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
597 LexicalScope *Scope) {
598 if (!Scope || !Scope->getScopeNode())
601 DIScope DS(Scope->getScopeNode());
603 SmallVector<DIE *, 8> Children;
604 DIE *ObjectPointer = NULL;
605 bool ChildrenCreated = false;
607 // We try to create the scope DIE first, then the children DIEs. This will
608 // avoid creating un-used children then removing them later when we find out
609 // the scope DIE is null.
610 DIE *ScopeDIE = NULL;
611 if (Scope->getInlinedAt())
612 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
613 else if (DS.isSubprogram()) {
614 ProcessedSPNodes.insert(DS);
615 if (Scope->isAbstractScope()) {
616 ScopeDIE = TheCU->getDIE(DS);
617 // Note down abstract DIE.
619 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
621 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
623 // Early exit when we know the scope DIE is going to be null.
624 if (isLexicalScopeDIENull(Scope))
627 // We create children here when we know the scope DIE is not going to be
628 // null and the children will be added to the scope DIE.
629 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
630 ChildrenCreated = true;
632 // There is no need to emit empty lexical block DIE.
633 std::pair<ImportedEntityMap::const_iterator,
634 ImportedEntityMap::const_iterator> Range =
636 ScopesWithImportedEntities.begin(),
637 ScopesWithImportedEntities.end(),
638 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
640 if (Children.empty() && Range.first == Range.second)
642 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
643 assert(ScopeDIE && "Scope DIE should not be null.");
644 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
646 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
650 assert(Children.empty() &&
651 "We create children only when the scope DIE is not null.");
654 if (!ChildrenCreated)
655 // We create children when the scope DIE is not null.
656 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
659 for (DIE *I : Children)
660 ScopeDIE->addChild(I);
662 if (DS.isSubprogram() && ObjectPointer != NULL)
663 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
668 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
669 if (!GenerateGnuPubSections)
672 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
675 // Create new DwarfCompileUnit for the given metadata node with tag
676 // DW_TAG_compile_unit.
677 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit,
679 StringRef FN = DIUnit.getFilename();
680 CompilationDir = DIUnit.getDirectory();
682 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
683 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
684 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
685 InfoHolder.addUnit(NewCU);
686 if (!Asm->OutStreamer.hasRawTextSupport() || Singular)
687 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
688 NewCU->getUniqueID(), CompilationDir);
690 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
691 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
692 DIUnit.getLanguage());
693 NewCU->addString(Die, dwarf::DW_AT_name, FN);
695 if (!useSplitDwarf()) {
696 NewCU->initStmtList(DwarfLineSectionSym);
698 // If we're using split dwarf the compilation dir is going to be in the
699 // skeleton CU and so we don't need to duplicate it here.
700 if (!CompilationDir.empty())
701 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
703 addGnuPubAttributes(NewCU, Die);
706 if (DIUnit.isOptimized())
707 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
709 StringRef Flags = DIUnit.getFlags();
711 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
713 if (unsigned RVer = DIUnit.getRunTimeVersion())
714 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
715 dwarf::DW_FORM_data1, RVer);
720 if (useSplitDwarf()) {
721 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
722 DwarfInfoDWOSectionSym);
723 NewCU->setSkeleton(constructSkeletonCU(NewCU));
725 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
726 DwarfInfoSectionSym);
728 CUMap.insert(std::make_pair(DIUnit, NewCU));
729 CUDieMap.insert(std::make_pair(Die, NewCU));
733 // Construct subprogram DIE.
734 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
736 // FIXME: We should only call this routine once, however, during LTO if a
737 // program is defined in multiple CUs we could end up calling it out of
738 // beginModule as we walk the CUs.
740 DwarfCompileUnit *&CURef = SPMap[N];
746 if (!SP.isDefinition())
747 // This is a method declaration which will be handled while constructing
751 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
753 // Expose as a global name.
754 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
757 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
759 DIImportedEntity Module(N);
760 assert(Module.Verify());
761 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
762 constructImportedEntityDIE(TheCU, Module, D);
765 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
766 const MDNode *N, DIE *Context) {
767 DIImportedEntity Module(N);
768 assert(Module.Verify());
769 return constructImportedEntityDIE(TheCU, Module, Context);
772 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
773 const DIImportedEntity &Module,
775 assert(Module.Verify() &&
776 "Use one of the MDNode * overloads to handle invalid metadata");
777 assert(Context && "Should always have a context for an imported_module");
778 DIE *IMDie = new DIE(Module.getTag());
779 TheCU->insertDIE(Module, IMDie);
781 DIDescriptor Entity = Module.getEntity();
782 if (Entity.isNameSpace())
783 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
784 else if (Entity.isSubprogram())
785 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
786 else if (Entity.isType())
787 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
789 EntityDie = TheCU->getDIE(Entity);
790 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
791 Module.getContext().getFilename(),
792 Module.getContext().getDirectory());
793 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
794 StringRef Name = Module.getName();
796 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
797 Context->addChild(IMDie);
800 // Emit all Dwarf sections that should come prior to the content. Create
801 // global DIEs and emit initial debug info sections. This is invoked by
802 // the target AsmPrinter.
803 void DwarfDebug::beginModule() {
804 if (DisableDebugInfoPrinting)
807 const Module *M = MMI->getModule();
809 // If module has named metadata anchors then use them, otherwise scan the
810 // module using debug info finder to collect debug info.
811 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
814 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
816 // Emit initial sections so we can reference labels later.
819 auto Operands = CU_Nodes->operands();
821 bool SingleCU = std::next(Operands.begin()) == Operands.end();
823 for (MDNode *N : Operands) {
824 DICompileUnit CUNode(N);
825 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode, SingleCU);
826 DIArray ImportedEntities = CUNode.getImportedEntities();
827 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
828 ScopesWithImportedEntities.push_back(std::make_pair(
829 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
830 ImportedEntities.getElement(i)));
831 std::sort(ScopesWithImportedEntities.begin(),
832 ScopesWithImportedEntities.end(), less_first());
833 DIArray GVs = CUNode.getGlobalVariables();
834 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
835 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
836 DIArray SPs = CUNode.getSubprograms();
837 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
838 constructSubprogramDIE(CU, SPs.getElement(i));
839 DIArray EnumTypes = CUNode.getEnumTypes();
840 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
841 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
842 DIArray RetainedTypes = CUNode.getRetainedTypes();
843 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
844 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
845 // Emit imported_modules last so that the relevant context is already
847 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
848 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
851 // Tell MMI that we have debug info.
852 MMI->setDebugInfoAvailability(true);
854 // Prime section data.
855 SectionMap[Asm->getObjFileLowering().getTextSection()];
858 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
859 void DwarfDebug::computeInlinedDIEs() {
860 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
861 for (DIE *ISP : InlinedSubprogramDIEs)
862 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
864 for (const auto &AI : AbstractSPDies) {
865 DIE *ISP = AI.second;
866 if (InlinedSubprogramDIEs.count(ISP))
868 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
872 // Collect info for variables that were optimized out.
873 void DwarfDebug::collectDeadVariables() {
874 const Module *M = MMI->getModule();
876 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
877 for (MDNode *N : CU_Nodes->operands()) {
878 DICompileUnit TheCU(N);
879 DIArray Subprograms = TheCU.getSubprograms();
880 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
881 DISubprogram SP(Subprograms.getElement(i));
882 if (ProcessedSPNodes.count(SP) != 0)
884 if (!SP.isSubprogram())
886 if (!SP.isDefinition())
888 DIArray Variables = SP.getVariables();
889 if (Variables.getNumElements() == 0)
892 // Construct subprogram DIE and add variables DIEs.
893 DwarfCompileUnit *SPCU =
894 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
895 assert(SPCU && "Unable to find Compile Unit!");
896 // FIXME: See the comment in constructSubprogramDIE about duplicate
898 constructSubprogramDIE(SPCU, SP);
899 DIE *SPDIE = SPCU->getDIE(SP);
900 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
901 DIVariable DV(Variables.getElement(vi));
902 if (!DV.isVariable())
904 DbgVariable NewVar(DV, NULL, this);
905 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
906 SPDIE->addChild(VariableDIE);
913 void DwarfDebug::finalizeModuleInfo() {
914 // Collect info for variables that were optimized out.
915 collectDeadVariables();
917 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
918 computeInlinedDIEs();
920 // Handle anything that needs to be done on a per-unit basis after
921 // all other generation.
922 for (DwarfUnit *TheU : getUnits()) {
923 // Emit DW_AT_containing_type attribute to connect types with their
924 // vtable holding type.
925 TheU->constructContainingTypeDIEs();
927 // Add CU specific attributes if we need to add any.
928 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
929 // If we're splitting the dwarf out now that we've got the entire
930 // CU then add the dwo id to it.
931 DwarfCompileUnit *SkCU =
932 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
933 if (useSplitDwarf()) {
934 // Emit a unique identifier for this CU.
935 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
936 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
937 dwarf::DW_FORM_data8, ID);
938 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
939 dwarf::DW_FORM_data8, ID);
942 // If we have code split among multiple sections or we've requested
943 // it then emit a DW_AT_ranges attribute on the unit that will remain
944 // in the .o file, otherwise add a DW_AT_low_pc.
945 // FIXME: Also add a high pc if we can.
946 // FIXME: We should use ranges if we have multiple compile units or
947 // allow reordering of code ala .subsections_via_symbols in mach-o.
948 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
949 if (useCURanges() && TheU->getRanges().size()) {
950 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
951 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
952 DwarfDebugRangeSectionSym);
954 // A DW_AT_low_pc attribute may also be specified in combination with
955 // DW_AT_ranges to specify the default base address for use in location
956 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
957 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
960 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
965 // Compute DIE offsets and sizes.
966 InfoHolder.computeSizeAndOffsets();
968 SkeletonHolder.computeSizeAndOffsets();
971 void DwarfDebug::endSections() {
972 // Filter labels by section.
973 for (const SymbolCU &SCU : ArangeLabels) {
974 if (SCU.Sym->isInSection()) {
975 // Make a note of this symbol and it's section.
976 const MCSection *Section = &SCU.Sym->getSection();
977 if (!Section->getKind().isMetadata())
978 SectionMap[Section].push_back(SCU);
980 // Some symbols (e.g. common/bss on mach-o) can have no section but still
981 // appear in the output. This sucks as we rely on sections to build
982 // arange spans. We can do it without, but it's icky.
983 SectionMap[NULL].push_back(SCU);
987 // Build a list of sections used.
988 std::vector<const MCSection *> Sections;
989 for (const auto &it : SectionMap) {
990 const MCSection *Section = it.first;
991 Sections.push_back(Section);
994 // Sort the sections into order.
995 // This is only done to ensure consistent output order across different runs.
996 std::sort(Sections.begin(), Sections.end(), SectionSort);
998 // Add terminating symbols for each section.
999 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1000 const MCSection *Section = Sections[ID];
1001 MCSymbol *Sym = NULL;
1004 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1005 // if we know the section name up-front. For user-created sections, the
1006 // resulting label may not be valid to use as a label. (section names can
1007 // use a greater set of characters on some systems)
1008 Sym = Asm->GetTempSymbol("debug_end", ID);
1009 Asm->OutStreamer.SwitchSection(Section);
1010 Asm->OutStreamer.EmitLabel(Sym);
1013 // Insert a final terminator.
1014 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1017 // For now only turn on CU ranges if we have -ffunction-sections enabled,
1018 // we've emitted a function into a unique section, or we're using LTO. If
1019 // we're using LTO then we can't know that any particular function in the
1020 // module is correlated to a particular CU and so we need to be conservative.
1021 // At this point all sections should be finalized except for dwarf sections.
1022 HasCURanges = UsedNonDefaultText || (CUMap.size() > 1) ||
1023 TargetMachine::getFunctionSections();
1026 // Emit all Dwarf sections that should come after the content.
1027 void DwarfDebug::endModule() {
1034 // End any existing sections.
1035 // TODO: Does this need to happen?
1038 // Finalize the debug info for the module.
1039 finalizeModuleInfo();
1043 // Emit all the DIEs into a debug info section.
1046 // Corresponding abbreviations into a abbrev section.
1047 emitAbbreviations();
1049 // Emit info into a debug loc section.
1052 // Emit info into a debug aranges section.
1053 if (GenerateARangeSection)
1056 // Emit info into a debug ranges section.
1059 if (useSplitDwarf()) {
1062 emitDebugAbbrevDWO();
1063 // Emit DWO addresses.
1064 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1067 // Emit info into the dwarf accelerator table sections.
1068 if (useDwarfAccelTables()) {
1071 emitAccelNamespaces();
1075 // Emit the pubnames and pubtypes sections if requested.
1076 if (HasDwarfPubSections) {
1077 emitDebugPubNames(GenerateGnuPubSections);
1078 emitDebugPubTypes(GenerateGnuPubSections);
1084 // Reset these for the next Module if we have one.
1088 // Find abstract variable, if any, associated with Var.
1089 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1090 DebugLoc ScopeLoc) {
1091 LLVMContext &Ctx = DV->getContext();
1092 // More then one inlined variable corresponds to one abstract variable.
1093 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1094 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1096 return AbsDbgVariable;
1098 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1102 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1103 addScopeVariable(Scope, AbsDbgVariable);
1104 AbstractVariables[Var] = AbsDbgVariable;
1105 return AbsDbgVariable;
1108 // If Var is a current function argument then add it to CurrentFnArguments list.
1109 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1110 if (!LScopes.isCurrentFunctionScope(Scope))
1112 DIVariable DV = Var->getVariable();
1113 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1115 unsigned ArgNo = DV.getArgNumber();
1119 size_t Size = CurrentFnArguments.size();
1121 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1122 // llvm::Function argument size is not good indicator of how many
1123 // arguments does the function have at source level.
1125 CurrentFnArguments.resize(ArgNo * 2);
1126 CurrentFnArguments[ArgNo - 1] = Var;
1130 // Collect variable information from side table maintained by MMI.
1131 void DwarfDebug::collectVariableInfoFromMMITable(
1132 SmallPtrSet<const MDNode *, 16> &Processed) {
1133 for (const auto &VI : MMI->getVariableDbgInfo()) {
1136 Processed.insert(VI.Var);
1137 DIVariable DV(VI.Var);
1138 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1140 // If variable scope is not found then skip this variable.
1144 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1145 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1146 RegVar->setFrameIndex(VI.Slot);
1147 if (!addCurrentFnArgument(RegVar, Scope))
1148 addScopeVariable(Scope, RegVar);
1150 AbsDbgVariable->setFrameIndex(VI.Slot);
1154 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1156 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1157 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1158 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1159 MI->getOperand(0).getReg() &&
1160 (MI->getOperand(1).isImm() ||
1161 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1164 // Get .debug_loc entry for the instruction range starting at MI.
1165 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1166 const MCSymbol *FLabel,
1167 const MCSymbol *SLabel,
1168 const MachineInstr *MI) {
1169 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1171 assert(MI->getNumOperands() == 3);
1172 if (MI->getOperand(0).isReg()) {
1173 MachineLocation MLoc;
1174 // If the second operand is an immediate, this is a
1175 // register-indirect address.
1176 if (!MI->getOperand(1).isImm())
1177 MLoc.set(MI->getOperand(0).getReg());
1179 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1180 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1182 if (MI->getOperand(0).isImm())
1183 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1184 if (MI->getOperand(0).isFPImm())
1185 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1186 if (MI->getOperand(0).isCImm())
1187 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1189 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1192 // Find variables for each lexical scope.
1194 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1196 // Grab the variable info that was squirreled away in the MMI side-table.
1197 collectVariableInfoFromMMITable(Processed);
1199 for (const MDNode *Var : UserVariables) {
1200 if (Processed.count(Var))
1203 // History contains relevant DBG_VALUE instructions for Var and instructions
1205 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1206 if (History.empty())
1208 const MachineInstr *MInsn = History.front();
1211 LexicalScope *Scope = NULL;
1212 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1213 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1214 Scope = LScopes.getCurrentFunctionScope();
1215 else if (MDNode *IA = DV.getInlinedAt())
1216 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1218 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1219 // If variable scope is not found then skip this variable.
1223 Processed.insert(DV);
1224 assert(MInsn->isDebugValue() && "History must begin with debug value");
1225 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1226 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1227 if (!addCurrentFnArgument(RegVar, Scope))
1228 addScopeVariable(Scope, RegVar);
1230 AbsVar->setMInsn(MInsn);
1232 // Simplify ranges that are fully coalesced.
1233 if (History.size() <= 1 ||
1234 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1235 RegVar->setMInsn(MInsn);
1239 // Handle multiple DBG_VALUE instructions describing one variable.
1240 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1242 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1243 HI = History.begin(),
1246 const MachineInstr *Begin = *HI;
1247 assert(Begin->isDebugValue() && "Invalid History entry");
1249 // Check if DBG_VALUE is truncating a range.
1250 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1251 !Begin->getOperand(0).getReg())
1254 // Compute the range for a register location.
1255 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1256 const MCSymbol *SLabel = 0;
1259 // If Begin is the last instruction in History then its value is valid
1260 // until the end of the function.
1261 SLabel = FunctionEndSym;
1263 const MachineInstr *End = HI[1];
1264 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1265 << "\t" << *Begin << "\t" << *End << "\n");
1266 if (End->isDebugValue())
1267 SLabel = getLabelBeforeInsn(End);
1269 // End is a normal instruction clobbering the range.
1270 SLabel = getLabelAfterInsn(End);
1271 assert(SLabel && "Forgot label after clobber instruction");
1276 // The value is valid until the next DBG_VALUE or clobber.
1277 DotDebugLocEntries.push_back(
1278 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1280 DotDebugLocEntries.push_back(DotDebugLocEntry());
1283 // Collect info for variables that were optimized out.
1284 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1285 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1286 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1287 DIVariable DV(Variables.getElement(i));
1288 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1290 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1291 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1295 // Return Label preceding the instruction.
1296 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1297 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1298 assert(Label && "Didn't insert label before instruction");
1302 // Return Label immediately following the instruction.
1303 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1304 return LabelsAfterInsn.lookup(MI);
1307 // Process beginning of an instruction.
1308 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1311 // Check if source location changes, but ignore DBG_VALUE locations.
1312 if (!MI->isDebugValue()) {
1313 DebugLoc DL = MI->getDebugLoc();
1314 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1317 if (DL == PrologEndLoc) {
1318 Flags |= DWARF2_FLAG_PROLOGUE_END;
1319 PrologEndLoc = DebugLoc();
1321 if (PrologEndLoc.isUnknown())
1322 Flags |= DWARF2_FLAG_IS_STMT;
1324 if (!DL.isUnknown()) {
1325 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1326 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1328 recordSourceLine(0, 0, 0, 0);
1332 // Insert labels where requested.
1333 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1334 LabelsBeforeInsn.find(MI);
1337 if (I == LabelsBeforeInsn.end())
1340 // Label already assigned.
1345 PrevLabel = MMI->getContext().CreateTempSymbol();
1346 Asm->OutStreamer.EmitLabel(PrevLabel);
1348 I->second = PrevLabel;
1351 // Process end of an instruction.
1352 void DwarfDebug::endInstruction() {
1354 // Don't create a new label after DBG_VALUE instructions.
1355 // They don't generate code.
1356 if (!CurMI->isDebugValue())
1359 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1360 LabelsAfterInsn.find(CurMI);
1364 if (I == LabelsAfterInsn.end())
1367 // Label already assigned.
1371 // We need a label after this instruction.
1373 PrevLabel = MMI->getContext().CreateTempSymbol();
1374 Asm->OutStreamer.EmitLabel(PrevLabel);
1376 I->second = PrevLabel;
1379 // Each LexicalScope has first instruction and last instruction to mark
1380 // beginning and end of a scope respectively. Create an inverse map that list
1381 // scopes starts (and ends) with an instruction. One instruction may start (or
1382 // end) multiple scopes. Ignore scopes that are not reachable.
1383 void DwarfDebug::identifyScopeMarkers() {
1384 SmallVector<LexicalScope *, 4> WorkList;
1385 WorkList.push_back(LScopes.getCurrentFunctionScope());
1386 while (!WorkList.empty()) {
1387 LexicalScope *S = WorkList.pop_back_val();
1389 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1390 if (!Children.empty())
1391 WorkList.append(Children.begin(), Children.end());
1393 if (S->isAbstractScope())
1396 for (const InsnRange &R : S->getRanges()) {
1397 assert(R.first && "InsnRange does not have first instruction!");
1398 assert(R.second && "InsnRange does not have second instruction!");
1399 requestLabelBeforeInsn(R.first);
1400 requestLabelAfterInsn(R.second);
1405 // Gather pre-function debug information. Assumes being called immediately
1406 // after the function entry point has been emitted.
1407 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1410 // If there's no debug info for the function we're not going to do anything.
1411 if (!MMI->hasDebugInfo())
1414 // Grab the lexical scopes for the function, if we don't have any of those
1415 // then we're not going to be able to do anything.
1416 LScopes.initialize(*MF);
1417 if (LScopes.empty()) {
1418 UsedNonDefaultText = true;
1422 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1424 // Make sure that each lexical scope will have a begin/end label.
1425 identifyScopeMarkers();
1427 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1428 // belongs to so that we add to the correct per-cu line table in the
1430 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1431 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1432 assert(TheCU && "Unable to find compile unit!");
1433 if (Asm->OutStreamer.hasRawTextSupport())
1434 // Use a single line table if we are generating assembly.
1435 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1437 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1439 // Check the current section against the standard text section. If different
1440 // keep track so that we will know when we're emitting functions into multiple
1442 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1443 UsedNonDefaultText = true;
1445 // Emit a label for the function so that we have a beginning address.
1446 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1447 // Assumes in correct section after the entry point.
1448 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1450 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1451 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1452 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1454 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1456 bool AtBlockEntry = true;
1457 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1459 const MachineInstr *MI = II;
1461 if (MI->isDebugValue()) {
1462 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1464 // Keep track of user variables.
1466 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1468 // Variable is in a register, we need to check for clobbers.
1469 if (isDbgValueInDefinedReg(MI))
1470 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1472 // Check the history of this variable.
1473 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1474 if (History.empty()) {
1475 UserVariables.push_back(Var);
1476 // The first mention of a function argument gets the FunctionBeginSym
1477 // label, so arguments are visible when breaking at function entry.
1479 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1480 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1481 LabelsBeforeInsn[MI] = FunctionBeginSym;
1483 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1484 const MachineInstr *Prev = History.back();
1485 if (Prev->isDebugValue()) {
1486 // Coalesce identical entries at the end of History.
1487 if (History.size() >= 2 &&
1488 Prev->isIdenticalTo(History[History.size() - 2])) {
1489 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1490 << "\t" << *Prev << "\t"
1491 << *History[History.size() - 2] << "\n");
1495 // Terminate old register assignments that don't reach MI;
1496 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1497 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1498 isDbgValueInDefinedReg(Prev)) {
1499 // Previous register assignment needs to terminate at the end of
1501 MachineBasicBlock::const_iterator LastMI =
1502 PrevMBB->getLastNonDebugInstr();
1503 if (LastMI == PrevMBB->end()) {
1504 // Drop DBG_VALUE for empty range.
1505 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1506 << "\t" << *Prev << "\n");
1508 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1509 // Terminate after LastMI.
1510 History.push_back(LastMI);
1514 History.push_back(MI);
1516 // Not a DBG_VALUE instruction.
1517 if (!MI->isPosition())
1518 AtBlockEntry = false;
1520 // First known non-DBG_VALUE and non-frame setup location marks
1521 // the beginning of the function body.
1522 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1523 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1524 PrologEndLoc = MI->getDebugLoc();
1526 // Check if the instruction clobbers any registers with debug vars.
1527 for (const MachineOperand &MO : MI->operands()) {
1528 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1530 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1533 const MDNode *Var = LiveUserVar[Reg];
1536 // Reg is now clobbered.
1537 LiveUserVar[Reg] = 0;
1539 // Was MD last defined by a DBG_VALUE referring to Reg?
1540 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1541 if (HistI == DbgValues.end())
1543 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1544 if (History.empty())
1546 const MachineInstr *Prev = History.back();
1547 // Sanity-check: Register assignments are terminated at the end of
1549 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1551 // Is the variable still in Reg?
1552 if (!isDbgValueInDefinedReg(Prev) ||
1553 Prev->getOperand(0).getReg() != Reg)
1555 // Var is clobbered. Make sure the next instruction gets a label.
1556 History.push_back(MI);
1563 for (auto &I : DbgValues) {
1564 SmallVectorImpl<const MachineInstr *> &History = I.second;
1565 if (History.empty())
1568 // Make sure the final register assignments are terminated.
1569 const MachineInstr *Prev = History.back();
1570 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1571 const MachineBasicBlock *PrevMBB = Prev->getParent();
1572 MachineBasicBlock::const_iterator LastMI =
1573 PrevMBB->getLastNonDebugInstr();
1574 if (LastMI == PrevMBB->end())
1575 // Drop DBG_VALUE for empty range.
1577 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1578 // Terminate after LastMI.
1579 History.push_back(LastMI);
1582 // Request labels for the full history.
1583 for (const MachineInstr *MI : History) {
1584 if (MI->isDebugValue())
1585 requestLabelBeforeInsn(MI);
1587 requestLabelAfterInsn(MI);
1591 PrevInstLoc = DebugLoc();
1592 PrevLabel = FunctionBeginSym;
1594 // Record beginning of function.
1595 if (!PrologEndLoc.isUnknown()) {
1596 DebugLoc FnStartDL =
1597 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1599 FnStartDL.getLine(), FnStartDL.getCol(),
1600 FnStartDL.getScope(MF->getFunction()->getContext()),
1601 // We'd like to list the prologue as "not statements" but GDB behaves
1602 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1603 DWARF2_FLAG_IS_STMT);
1607 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1608 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1609 DIVariable DV = Var->getVariable();
1610 // Variables with positive arg numbers are parameters.
1611 if (unsigned ArgNum = DV.getArgNumber()) {
1612 // Keep all parameters in order at the start of the variable list to ensure
1613 // function types are correct (no out-of-order parameters)
1615 // This could be improved by only doing it for optimized builds (unoptimized
1616 // builds have the right order to begin with), searching from the back (this
1617 // would catch the unoptimized case quickly), or doing a binary search
1618 // rather than linear search.
1619 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1620 while (I != Vars.end()) {
1621 unsigned CurNum = (*I)->getVariable().getArgNumber();
1622 // A local (non-parameter) variable has been found, insert immediately
1626 // A later indexed parameter has been found, insert immediately before it.
1627 if (CurNum > ArgNum)
1631 Vars.insert(I, Var);
1635 Vars.push_back(Var);
1638 // Gather and emit post-function debug information.
1639 void DwarfDebug::endFunction(const MachineFunction *MF) {
1640 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1641 // though the beginFunction may not be called at all.
1642 // We should handle both cases.
1646 assert(CurFn == MF);
1649 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1654 // Define end label for subprogram.
1655 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1656 // Assumes in correct section after the entry point.
1657 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1659 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1660 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1662 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1663 collectVariableInfo(ProcessedVars);
1665 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1666 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1667 assert(TheCU && "Unable to find compile unit!");
1669 // Construct abstract scopes.
1670 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1671 DISubprogram SP(AScope->getScopeNode());
1672 if (SP.isSubprogram()) {
1673 // Collect info for variables that were optimized out.
1674 DIArray Variables = SP.getVariables();
1675 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1676 DIVariable DV(Variables.getElement(i));
1677 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1679 // Check that DbgVariable for DV wasn't created earlier, when
1680 // findAbstractVariable() was called for inlined instance of DV.
1681 LLVMContext &Ctx = DV->getContext();
1682 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1683 if (AbstractVariables.lookup(CleanDV))
1685 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1686 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1689 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1690 constructScopeDIE(TheCU, AScope);
1693 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1694 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1695 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1697 // Add the range of this function to the list of ranges for the CU.
1698 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1699 TheCU->addRange(std::move(Span));
1702 for (auto &I : ScopeVariables)
1703 DeleteContainerPointers(I.second);
1704 ScopeVariables.clear();
1705 DeleteContainerPointers(CurrentFnArguments);
1706 UserVariables.clear();
1708 AbstractVariables.clear();
1709 LabelsBeforeInsn.clear();
1710 LabelsAfterInsn.clear();
1715 // Register a source line with debug info. Returns the unique label that was
1716 // emitted and which provides correspondence to the source line list.
1717 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1722 unsigned Discriminator = 0;
1724 DIDescriptor Scope(S);
1726 if (Scope.isCompileUnit()) {
1727 DICompileUnit CU(S);
1728 Fn = CU.getFilename();
1729 Dir = CU.getDirectory();
1730 } else if (Scope.isFile()) {
1732 Fn = F.getFilename();
1733 Dir = F.getDirectory();
1734 } else if (Scope.isSubprogram()) {
1736 Fn = SP.getFilename();
1737 Dir = SP.getDirectory();
1738 } else if (Scope.isLexicalBlockFile()) {
1739 DILexicalBlockFile DBF(S);
1740 Fn = DBF.getFilename();
1741 Dir = DBF.getDirectory();
1742 } else if (Scope.isLexicalBlock()) {
1743 DILexicalBlock DB(S);
1744 Fn = DB.getFilename();
1745 Dir = DB.getDirectory();
1746 Discriminator = DB.getDiscriminator();
1748 llvm_unreachable("Unexpected scope info");
1750 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1751 Src = static_cast<DwarfCompileUnit *>(InfoHolder.getUnits()[CUID])
1752 ->getOrCreateSourceID(Fn, Dir);
1754 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1758 //===----------------------------------------------------------------------===//
1760 //===----------------------------------------------------------------------===//
1762 // Compute the size and offset of a DIE. The offset is relative to start of the
1763 // CU. It returns the offset after laying out the DIE.
1764 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1765 // Record the abbreviation.
1766 assignAbbrevNumber(Die->getAbbrev());
1768 // Get the abbreviation for this DIE.
1769 const DIEAbbrev &Abbrev = Die->getAbbrev();
1772 Die->setOffset(Offset);
1774 // Start the size with the size of abbreviation code.
1775 Offset += getULEB128Size(Die->getAbbrevNumber());
1777 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1778 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1780 // Size the DIE attribute values.
1781 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1782 // Size attribute value.
1783 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1785 // Get the children.
1786 const std::vector<DIE *> &Children = Die->getChildren();
1788 // Size the DIE children if any.
1789 if (!Children.empty()) {
1790 assert(Abbrev.hasChildren() && "Children flag not set");
1792 for (DIE *Child : Children)
1793 Offset = computeSizeAndOffset(Child, Offset);
1795 // End of children marker.
1796 Offset += sizeof(int8_t);
1799 Die->setSize(Offset - Die->getOffset());
1803 // Compute the size and offset for each DIE.
1804 void DwarfFile::computeSizeAndOffsets() {
1805 // Offset from the first CU in the debug info section is 0 initially.
1806 unsigned SecOffset = 0;
1808 // Iterate over each compile unit and set the size and offsets for each
1809 // DIE within each compile unit. All offsets are CU relative.
1810 for (DwarfUnit *TheU : CUs) {
1811 TheU->setDebugInfoOffset(SecOffset);
1813 // CU-relative offset is reset to 0 here.
1814 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1815 TheU->getHeaderSize(); // Unit-specific headers
1817 // EndOffset here is CU-relative, after laying out
1818 // all of the CU DIE.
1819 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1820 SecOffset += EndOffset;
1824 // Emit initial Dwarf sections with a label at the start of each one.
1825 void DwarfDebug::emitSectionLabels() {
1826 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1828 // Dwarf sections base addresses.
1829 DwarfInfoSectionSym =
1830 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1831 if (useSplitDwarf())
1832 DwarfInfoDWOSectionSym =
1833 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1834 DwarfAbbrevSectionSym =
1835 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1836 if (useSplitDwarf())
1837 DwarfAbbrevDWOSectionSym = emitSectionSym(
1838 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1839 if (GenerateARangeSection)
1840 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1842 DwarfLineSectionSym =
1843 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1844 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1845 if (GenerateGnuPubSections) {
1846 DwarfGnuPubNamesSectionSym =
1847 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1848 DwarfGnuPubTypesSectionSym =
1849 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1850 } else if (HasDwarfPubSections) {
1851 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1852 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1855 DwarfStrSectionSym =
1856 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1857 if (useSplitDwarf()) {
1858 DwarfStrDWOSectionSym =
1859 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1860 DwarfAddrSectionSym =
1861 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1863 DwarfDebugRangeSectionSym =
1864 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1866 DwarfDebugLocSectionSym =
1867 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1870 // Recursively emits a debug information entry.
1871 void DwarfDebug::emitDIE(DIE *Die) {
1872 // Get the abbreviation for this DIE.
1873 const DIEAbbrev &Abbrev = Die->getAbbrev();
1875 // Emit the code (index) for the abbreviation.
1876 if (Asm->isVerbose())
1877 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1878 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1879 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1880 dwarf::TagString(Abbrev.getTag()));
1881 Asm->EmitULEB128(Abbrev.getNumber());
1883 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1884 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1886 // Emit the DIE attribute values.
1887 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1888 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1889 dwarf::Form Form = AbbrevData[i].getForm();
1890 assert(Form && "Too many attributes for DIE (check abbreviation)");
1892 if (Asm->isVerbose()) {
1893 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1894 if (Attr == dwarf::DW_AT_accessibility)
1895 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1896 cast<DIEInteger>(Values[i])->getValue()));
1899 // Emit an attribute using the defined form.
1900 Values[i]->EmitValue(Asm, Form);
1903 // Emit the DIE children if any.
1904 if (Abbrev.hasChildren()) {
1905 const std::vector<DIE *> &Children = Die->getChildren();
1907 for (DIE *Child : Children)
1910 Asm->OutStreamer.AddComment("End Of Children Mark");
1915 // Emit the various dwarf units to the unit section USection with
1916 // the abbreviations going into ASection.
1917 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1918 const MCSymbol *ASectionSym) {
1919 for (DwarfUnit *TheU : CUs) {
1920 DIE *Die = TheU->getUnitDie();
1921 const MCSection *USection = TheU->getSection();
1922 Asm->OutStreamer.SwitchSection(USection);
1924 // Emit the compile units header.
1925 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1927 // Emit size of content not including length itself
1928 Asm->OutStreamer.AddComment("Length of Unit");
1929 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1931 TheU->emitHeader(ASection, ASectionSym);
1934 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1938 // Emit the debug info section.
1939 void DwarfDebug::emitDebugInfo() {
1940 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1942 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1943 DwarfAbbrevSectionSym);
1946 // Emit the abbreviation section.
1947 void DwarfDebug::emitAbbreviations() {
1948 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1950 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1953 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1954 // Check to see if it is worth the effort.
1955 if (!Abbreviations.empty()) {
1956 // Start the debug abbrev section.
1957 Asm->OutStreamer.SwitchSection(Section);
1959 // For each abbrevation.
1960 for (const DIEAbbrev *Abbrev : Abbreviations) {
1961 // Emit the abbrevations code (base 1 index.)
1962 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1964 // Emit the abbreviations data.
1968 // Mark end of abbreviations.
1969 Asm->EmitULEB128(0, "EOM(3)");
1973 // Emit the last address of the section and the end of the line matrix.
1974 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1975 // Define last address of section.
1976 Asm->OutStreamer.AddComment("Extended Op");
1979 Asm->OutStreamer.AddComment("Op size");
1980 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1981 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1982 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1984 Asm->OutStreamer.AddComment("Section end label");
1986 Asm->OutStreamer.EmitSymbolValue(
1987 Asm->GetTempSymbol("section_end", SectionEnd),
1988 Asm->getDataLayout().getPointerSize());
1990 // Mark end of matrix.
1991 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1997 // Emit visible names into a hashed accelerator table section.
1998 void DwarfDebug::emitAccelNames() {
2000 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2001 for (DwarfUnit *TheU : getUnits()) {
2002 for (const auto &GI : TheU->getAccelNames()) {
2003 StringRef Name = GI.getKey();
2004 for (const DIE *D : GI.second)
2005 AT.AddName(Name, D);
2009 AT.FinalizeTable(Asm, "Names");
2010 Asm->OutStreamer.SwitchSection(
2011 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2012 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2013 Asm->OutStreamer.EmitLabel(SectionBegin);
2015 // Emit the full data.
2016 AT.Emit(Asm, SectionBegin, &InfoHolder);
2019 // Emit objective C classes and categories into a hashed accelerator table
2021 void DwarfDebug::emitAccelObjC() {
2023 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2024 for (DwarfUnit *TheU : getUnits()) {
2025 for (const auto &GI : TheU->getAccelObjC()) {
2026 StringRef Name = GI.getKey();
2027 for (const DIE *D : GI.second)
2028 AT.AddName(Name, D);
2032 AT.FinalizeTable(Asm, "ObjC");
2033 Asm->OutStreamer.SwitchSection(
2034 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2035 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2036 Asm->OutStreamer.EmitLabel(SectionBegin);
2038 // Emit the full data.
2039 AT.Emit(Asm, SectionBegin, &InfoHolder);
2042 // Emit namespace dies into a hashed accelerator table.
2043 void DwarfDebug::emitAccelNamespaces() {
2045 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2046 for (DwarfUnit *TheU : getUnits()) {
2047 for (const auto &GI : TheU->getAccelNamespace()) {
2048 StringRef Name = GI.getKey();
2049 for (const DIE *D : GI.second)
2050 AT.AddName(Name, D);
2054 AT.FinalizeTable(Asm, "namespac");
2055 Asm->OutStreamer.SwitchSection(
2056 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2057 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2058 Asm->OutStreamer.EmitLabel(SectionBegin);
2060 // Emit the full data.
2061 AT.Emit(Asm, SectionBegin, &InfoHolder);
2064 // Emit type dies into a hashed accelerator table.
2065 void DwarfDebug::emitAccelTypes() {
2066 std::vector<DwarfAccelTable::Atom> Atoms;
2068 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2070 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2072 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2073 DwarfAccelTable AT(Atoms);
2074 for (DwarfUnit *TheU : getUnits()) {
2075 for (const auto &GI : TheU->getAccelTypes()) {
2076 StringRef Name = GI.getKey();
2077 for (const auto &DI : GI.second)
2078 AT.AddName(Name, DI.first, DI.second);
2082 AT.FinalizeTable(Asm, "types");
2083 Asm->OutStreamer.SwitchSection(
2084 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2085 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2086 Asm->OutStreamer.EmitLabel(SectionBegin);
2088 // Emit the full data.
2089 AT.Emit(Asm, SectionBegin, &InfoHolder);
2092 // Public name handling.
2093 // The format for the various pubnames:
2095 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2096 // for the DIE that is named.
2098 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2099 // into the CU and the index value is computed according to the type of value
2100 // for the DIE that is named.
2102 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2103 // it's the offset within the debug_info/debug_types dwo section, however, the
2104 // reference in the pubname header doesn't change.
2106 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2107 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2109 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2111 // We could have a specification DIE that has our most of our knowledge,
2112 // look for that now.
2113 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2115 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2116 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2117 Linkage = dwarf::GIEL_EXTERNAL;
2118 } else if (Die->findAttribute(dwarf::DW_AT_external))
2119 Linkage = dwarf::GIEL_EXTERNAL;
2121 switch (Die->getTag()) {
2122 case dwarf::DW_TAG_class_type:
2123 case dwarf::DW_TAG_structure_type:
2124 case dwarf::DW_TAG_union_type:
2125 case dwarf::DW_TAG_enumeration_type:
2126 return dwarf::PubIndexEntryDescriptor(
2127 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2128 ? dwarf::GIEL_STATIC
2129 : dwarf::GIEL_EXTERNAL);
2130 case dwarf::DW_TAG_typedef:
2131 case dwarf::DW_TAG_base_type:
2132 case dwarf::DW_TAG_subrange_type:
2133 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2134 case dwarf::DW_TAG_namespace:
2135 return dwarf::GIEK_TYPE;
2136 case dwarf::DW_TAG_subprogram:
2137 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2138 case dwarf::DW_TAG_constant:
2139 case dwarf::DW_TAG_variable:
2140 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2141 case dwarf::DW_TAG_enumerator:
2142 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2143 dwarf::GIEL_STATIC);
2145 return dwarf::GIEK_NONE;
2149 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2151 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2152 const MCSection *PSec =
2153 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2154 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2156 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2159 void DwarfDebug::emitDebugPubSection(
2160 bool GnuStyle, const MCSection *PSec, StringRef Name,
2161 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2162 for (const auto &NU : CUMap) {
2163 DwarfCompileUnit *TheU = NU.second;
2165 const auto &Globals = (TheU->*Accessor)();
2167 if (Globals.empty())
2170 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2172 unsigned ID = TheU->getUniqueID();
2174 // Start the dwarf pubnames section.
2175 Asm->OutStreamer.SwitchSection(PSec);
2178 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2179 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2180 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2181 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2183 Asm->OutStreamer.EmitLabel(BeginLabel);
2185 Asm->OutStreamer.AddComment("DWARF Version");
2186 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2188 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2189 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2191 Asm->OutStreamer.AddComment("Compilation Unit Length");
2192 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2194 // Emit the pubnames for this compilation unit.
2195 for (const auto &GI : Globals) {
2196 const char *Name = GI.getKeyData();
2197 const DIE *Entity = GI.second;
2199 Asm->OutStreamer.AddComment("DIE offset");
2200 Asm->EmitInt32(Entity->getOffset());
2203 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2204 Asm->OutStreamer.AddComment(
2205 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2206 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2207 Asm->EmitInt8(Desc.toBits());
2210 Asm->OutStreamer.AddComment("External Name");
2211 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2214 Asm->OutStreamer.AddComment("End Mark");
2216 Asm->OutStreamer.EmitLabel(EndLabel);
2220 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2221 const MCSection *PSec =
2222 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2223 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2225 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2228 // Emit strings into a string section.
2229 void DwarfFile::emitStrings(const MCSection *StrSection,
2230 const MCSection *OffsetSection = NULL,
2231 const MCSymbol *StrSecSym = NULL) {
2233 if (StringPool.empty())
2236 // Start the dwarf str section.
2237 Asm->OutStreamer.SwitchSection(StrSection);
2239 // Get all of the string pool entries and put them in an array by their ID so
2240 // we can sort them.
2241 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2243 for (const auto &I : StringPool)
2244 Entries.push_back(std::make_pair(I.second.second, &I));
2246 array_pod_sort(Entries.begin(), Entries.end());
2248 for (const auto &Entry : Entries) {
2249 // Emit a label for reference from debug information entries.
2250 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2252 // Emit the string itself with a terminating null byte.
2253 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2254 Entry.second->getKeyLength() + 1));
2257 // If we've got an offset section go ahead and emit that now as well.
2258 if (OffsetSection) {
2259 Asm->OutStreamer.SwitchSection(OffsetSection);
2260 unsigned offset = 0;
2261 unsigned size = 4; // FIXME: DWARF64 is 8.
2262 for (const auto &Entry : Entries) {
2263 Asm->OutStreamer.EmitIntValue(offset, size);
2264 offset += Entry.second->getKeyLength() + 1;
2269 // Emit addresses into the section given.
2270 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2272 if (AddressPool.empty())
2275 // Start the dwarf addr section.
2276 Asm->OutStreamer.SwitchSection(AddrSection);
2278 // Order the address pool entries by ID
2279 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2281 for (const auto &I : AddressPool)
2282 Entries[I.second.Number] =
2284 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2285 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2287 for (const MCExpr *Entry : Entries)
2288 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2291 // Emit visible names into a debug str section.
2292 void DwarfDebug::emitDebugStr() {
2293 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2294 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2297 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2298 const DotDebugLocEntry &Entry) {
2299 DIVariable DV(Entry.getVariable());
2300 if (Entry.isInt()) {
2301 DIBasicType BTy(DV.getType());
2302 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2303 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2304 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2305 Streamer.EmitSLEB128(Entry.getInt());
2307 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2308 Streamer.EmitULEB128(Entry.getInt());
2310 } else if (Entry.isLocation()) {
2311 MachineLocation Loc = Entry.getLoc();
2312 if (!DV.hasComplexAddress())
2314 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2316 // Complex address entry.
2317 unsigned N = DV.getNumAddrElements();
2319 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2320 if (Loc.getOffset()) {
2322 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2323 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2324 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2325 Streamer.EmitSLEB128(DV.getAddrElement(1));
2327 // If first address element is OpPlus then emit
2328 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2329 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2330 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2334 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2337 // Emit remaining complex address elements.
2338 for (; i < N; ++i) {
2339 uint64_t Element = DV.getAddrElement(i);
2340 if (Element == DIBuilder::OpPlus) {
2341 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2342 Streamer.EmitULEB128(DV.getAddrElement(++i));
2343 } else if (Element == DIBuilder::OpDeref) {
2345 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2347 llvm_unreachable("unknown Opcode found in complex address");
2351 // else ... ignore constant fp. There is not any good way to
2352 // to represent them here in dwarf.
2356 // Emit locations into the debug loc section.
2357 void DwarfDebug::emitDebugLoc() {
2358 if (DotDebugLocEntries.empty())
2361 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2362 I = DotDebugLocEntries.begin(),
2363 E = DotDebugLocEntries.end();
2365 DotDebugLocEntry &Entry = *I;
2366 if (I + 1 != DotDebugLocEntries.end())
2370 // Start the dwarf loc section.
2371 Asm->OutStreamer.SwitchSection(
2372 Asm->getObjFileLowering().getDwarfLocSection());
2373 unsigned char Size = Asm->getDataLayout().getPointerSize();
2374 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2376 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2377 I = DotDebugLocEntries.begin(),
2378 E = DotDebugLocEntries.end();
2379 I != E; ++I, ++index) {
2380 const DotDebugLocEntry &Entry = *I;
2381 if (Entry.isMerged())
2384 if (Entry.isEmpty()) {
2385 Asm->OutStreamer.EmitIntValue(0, Size);
2386 Asm->OutStreamer.EmitIntValue(0, Size);
2387 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2389 // Set up the range.
2390 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2391 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2392 Asm->OutStreamer.AddComment("Loc expr size");
2393 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2394 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2395 Asm->EmitLabelDifference(end, begin, 2);
2396 Asm->OutStreamer.EmitLabel(begin);
2398 APByteStreamer Streamer(*Asm);
2399 emitDebugLocEntry(Streamer, Entry);
2401 Asm->OutStreamer.EmitLabel(end);
2407 const MCSymbol *Start, *End;
2410 // Emit a debug aranges section, containing a CU lookup for any
2411 // address we can tie back to a CU.
2412 void DwarfDebug::emitDebugARanges() {
2413 // Start the dwarf aranges section.
2414 Asm->OutStreamer.SwitchSection(
2415 Asm->getObjFileLowering().getDwarfARangesSection());
2417 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2421 // Build a list of sections used.
2422 std::vector<const MCSection *> Sections;
2423 for (const auto &it : SectionMap) {
2424 const MCSection *Section = it.first;
2425 Sections.push_back(Section);
2428 // Sort the sections into order.
2429 // This is only done to ensure consistent output order across different runs.
2430 std::sort(Sections.begin(), Sections.end(), SectionSort);
2432 // Build a set of address spans, sorted by CU.
2433 for (const MCSection *Section : Sections) {
2434 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2435 if (List.size() < 2)
2438 // Sort the symbols by offset within the section.
2439 std::sort(List.begin(), List.end(),
2440 [&](const SymbolCU &A, const SymbolCU &B) {
2441 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2442 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2444 // Symbols with no order assigned should be placed at the end.
2445 // (e.g. section end labels)
2453 // If we have no section (e.g. common), just write out
2454 // individual spans for each symbol.
2455 if (Section == NULL) {
2456 for (const SymbolCU &Cur : List) {
2458 Span.Start = Cur.Sym;
2461 Spans[Cur.CU].push_back(Span);
2464 // Build spans between each label.
2465 const MCSymbol *StartSym = List[0].Sym;
2466 for (size_t n = 1, e = List.size(); n < e; n++) {
2467 const SymbolCU &Prev = List[n - 1];
2468 const SymbolCU &Cur = List[n];
2470 // Try and build the longest span we can within the same CU.
2471 if (Cur.CU != Prev.CU) {
2473 Span.Start = StartSym;
2475 Spans[Prev.CU].push_back(Span);
2482 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2484 // Build a list of CUs used.
2485 std::vector<DwarfCompileUnit *> CUs;
2486 for (const auto &it : Spans) {
2487 DwarfCompileUnit *CU = it.first;
2491 // Sort the CU list (again, to ensure consistent output order).
2492 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2493 return A->getUniqueID() < B->getUniqueID();
2496 // Emit an arange table for each CU we used.
2497 for (DwarfCompileUnit *CU : CUs) {
2498 std::vector<ArangeSpan> &List = Spans[CU];
2500 // Emit size of content not including length itself.
2501 unsigned ContentSize =
2502 sizeof(int16_t) + // DWARF ARange version number
2503 sizeof(int32_t) + // Offset of CU in the .debug_info section
2504 sizeof(int8_t) + // Pointer Size (in bytes)
2505 sizeof(int8_t); // Segment Size (in bytes)
2507 unsigned TupleSize = PtrSize * 2;
2509 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2511 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2513 ContentSize += Padding;
2514 ContentSize += (List.size() + 1) * TupleSize;
2516 // For each compile unit, write the list of spans it covers.
2517 Asm->OutStreamer.AddComment("Length of ARange Set");
2518 Asm->EmitInt32(ContentSize);
2519 Asm->OutStreamer.AddComment("DWARF Arange version number");
2520 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2521 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2522 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2523 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2524 Asm->EmitInt8(PtrSize);
2525 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2528 Asm->OutStreamer.EmitFill(Padding, 0xff);
2530 for (const ArangeSpan &Span : List) {
2531 Asm->EmitLabelReference(Span.Start, PtrSize);
2533 // Calculate the size as being from the span start to it's end.
2535 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2537 // For symbols without an end marker (e.g. common), we
2538 // write a single arange entry containing just that one symbol.
2539 uint64_t Size = SymSize[Span.Start];
2543 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2547 Asm->OutStreamer.AddComment("ARange terminator");
2548 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2549 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2553 // Emit visible names into a debug ranges section.
2554 void DwarfDebug::emitDebugRanges() {
2555 // Start the dwarf ranges section.
2556 Asm->OutStreamer.SwitchSection(
2557 Asm->getObjFileLowering().getDwarfRangesSection());
2559 // Size for our labels.
2560 unsigned char Size = Asm->getDataLayout().getPointerSize();
2562 // Grab the specific ranges for the compile units in the module.
2563 for (const auto &I : CUMap) {
2564 DwarfCompileUnit *TheCU = I.second;
2566 // Emit a symbol so we can find the beginning of our ranges.
2567 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2569 // Iterate over the misc ranges for the compile units in the module.
2570 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2571 // Emit our symbol so we can find the beginning of the range.
2572 Asm->OutStreamer.EmitLabel(List.getSym());
2574 for (const RangeSpan &Range : List.getRanges()) {
2575 const MCSymbol *Begin = Range.getStart();
2576 const MCSymbol *End = Range.getEnd();
2577 assert(Begin && "Range without a begin symbol?");
2578 assert(End && "Range without an end symbol?");
2579 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2580 Asm->OutStreamer.EmitSymbolValue(End, Size);
2583 // And terminate the list with two 0 values.
2584 Asm->OutStreamer.EmitIntValue(0, Size);
2585 Asm->OutStreamer.EmitIntValue(0, Size);
2588 // Now emit a range for the CU itself.
2589 if (useCURanges() && TheCU->getRanges().size()) {
2590 Asm->OutStreamer.EmitLabel(
2591 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2592 for (const RangeSpan &Range : TheCU->getRanges()) {
2593 const MCSymbol *Begin = Range.getStart();
2594 const MCSymbol *End = Range.getEnd();
2595 assert(Begin && "Range without a begin symbol?");
2596 assert(End && "Range without an end symbol?");
2597 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2598 Asm->OutStreamer.EmitSymbolValue(End, Size);
2600 // And terminate the list with two 0 values.
2601 Asm->OutStreamer.EmitIntValue(0, Size);
2602 Asm->OutStreamer.EmitIntValue(0, Size);
2607 // DWARF5 Experimental Separate Dwarf emitters.
2609 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2611 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2612 U->getCUNode().getSplitDebugFilename());
2614 // Relocate to the beginning of the addr_base section, else 0 for the
2615 // beginning of the one for this compile unit.
2616 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2617 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2619 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2621 if (!CompilationDir.empty())
2622 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2624 addGnuPubAttributes(NewU, Die);
2626 SkeletonHolder.addUnit(NewU);
2629 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2630 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2631 // DW_AT_ranges_base, DW_AT_addr_base.
2632 // TODO: Implement DW_AT_ranges_base.
2633 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2635 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2636 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2637 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2638 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2639 DwarfInfoSectionSym);
2641 NewCU->initStmtList(DwarfLineSectionSym);
2643 initSkeletonUnit(CU, Die, NewCU);
2648 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2650 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2651 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2652 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2654 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2655 DwarfTypeUnit *NewTU =
2656 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2657 NewTU->setTypeSignature(TU->getTypeSignature());
2658 NewTU->setType(NULL);
2660 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2661 CU.applyStmtList(*Die);
2663 initSkeletonUnit(TU, Die, NewTU);
2667 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2668 // compile units that would normally be in debug_info.
2669 void DwarfDebug::emitDebugInfoDWO() {
2670 assert(useSplitDwarf() && "No split dwarf debug info?");
2671 InfoHolder.emitUnits(this,
2672 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2673 DwarfAbbrevDWOSectionSym);
2676 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2677 // abbreviations for the .debug_info.dwo section.
2678 void DwarfDebug::emitDebugAbbrevDWO() {
2679 assert(useSplitDwarf() && "No split dwarf?");
2680 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2683 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2684 // string section and is identical in format to traditional .debug_str
2686 void DwarfDebug::emitDebugStrDWO() {
2687 assert(useSplitDwarf() && "No split dwarf?");
2688 const MCSection *OffSec =
2689 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2690 const MCSymbol *StrSym = DwarfStrSectionSym;
2691 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2695 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2696 StringRef Identifier, DIE *RefDie,
2697 DICompositeType CTy) {
2698 // Flag the type unit reference as a declaration so that if it contains
2699 // members (implicit special members, static data member definitions, member
2700 // declarations for definitions in this CU, etc) consumers don't get confused
2701 // and think this is a full definition.
2702 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2704 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2706 CU.addDIETypeSignature(RefDie, *TU);
2710 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2711 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2712 UnitDie, CU, Asm, this, &InfoHolder);
2714 InfoHolder.addUnit(NewTU);
2716 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2720 Hash.update(Identifier);
2721 // ... take the least significant 8 bytes and return those. Our MD5
2722 // implementation always returns its results in little endian, swap bytes
2724 MD5::MD5Result Result;
2726 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2727 NewTU->setTypeSignature(Signature);
2728 if (useSplitDwarf())
2729 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2731 CU.applyStmtList(*UnitDie);
2733 NewTU->setType(NewTU->createTypeDIE(CTy));
2737 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2738 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2740 CU.addDIETypeSignature(RefDie, *NewTU);
2743 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2744 MCSymbol *Begin, MCSymbol *End) {
2745 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2746 if (DwarfVersion < 4)
2747 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2749 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);