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 "DwarfDebug.h"
18 #include "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Dwarf.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MD5.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Target/TargetFrameLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
54 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
55 cl::desc("Disable debug info printing"));
57 static cl::opt<bool> UnknownLocations(
58 "use-unknown-locations", cl::Hidden,
59 cl::desc("Make an absence of debug location information explicit."),
62 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
63 cl::desc("Add the CU hash as the dwo_id."),
67 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
68 cl::desc("Generate GNU-style pubnames and pubtypes"),
71 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
73 cl::desc("Generate dwarf aranges"),
77 enum DefaultOnOff { Default, Enable, Disable };
80 static cl::opt<DefaultOnOff>
81 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
82 cl::desc("Output prototype dwarf accelerator tables."),
83 cl::values(clEnumVal(Default, "Default for platform"),
84 clEnumVal(Enable, "Enabled"),
85 clEnumVal(Disable, "Disabled"), clEnumValEnd),
88 static cl::opt<DefaultOnOff>
89 SplitDwarf("split-dwarf", cl::Hidden,
90 cl::desc("Output DWARF5 split debug info."),
91 cl::values(clEnumVal(Default, "Default for platform"),
92 clEnumVal(Enable, "Enabled"),
93 clEnumVal(Disable, "Disabled"), clEnumValEnd),
96 static cl::opt<DefaultOnOff>
97 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
98 cl::desc("Generate DWARF pubnames and pubtypes sections"),
99 cl::values(clEnumVal(Default, "Default for platform"),
100 clEnumVal(Enable, "Enabled"),
101 clEnumVal(Disable, "Disabled"), clEnumValEnd),
104 static cl::opt<unsigned>
105 DwarfVersionNumber("dwarf-version", cl::Hidden,
106 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
109 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
110 cl::desc("Generate DW_AT_ranges for compile units"),
113 static const char *const DWARFGroupName = "DWARF Emission";
114 static const char *const DbgTimerName = "DWARF Debug Writer";
116 //===----------------------------------------------------------------------===//
120 /// resolve - Look in the DwarfDebug map for the MDNode that
121 /// corresponds to the reference.
122 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
123 return DD->resolve(Ref);
126 DIType DbgVariable::getType() const {
127 DIType Ty = Var.getType();
128 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
129 // addresses instead.
130 if (Var.isBlockByrefVariable()) {
131 /* Byref variables, in Blocks, are declared by the programmer as
132 "SomeType VarName;", but the compiler creates a
133 __Block_byref_x_VarName struct, and gives the variable VarName
134 either the struct, or a pointer to the struct, as its type. This
135 is necessary for various behind-the-scenes things the compiler
136 needs to do with by-reference variables in blocks.
138 However, as far as the original *programmer* is concerned, the
139 variable should still have type 'SomeType', as originally declared.
141 The following function dives into the __Block_byref_x_VarName
142 struct to find the original type of the variable. This will be
143 passed back to the code generating the type for the Debug
144 Information Entry for the variable 'VarName'. 'VarName' will then
145 have the original type 'SomeType' in its debug information.
147 The original type 'SomeType' will be the type of the field named
148 'VarName' inside the __Block_byref_x_VarName struct.
150 NOTE: In order for this to not completely fail on the debugger
151 side, the Debug Information Entry for the variable VarName needs to
152 have a DW_AT_location that tells the debugger how to unwind through
153 the pointers and __Block_byref_x_VarName struct to find the actual
154 value of the variable. The function addBlockByrefType does this. */
156 uint16_t tag = Ty.getTag();
158 if (tag == dwarf::DW_TAG_pointer_type)
159 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
161 DIArray Elements = DICompositeType(subType).getTypeArray();
162 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
163 DIDerivedType DT(Elements.getElement(i));
164 if (getName() == DT.getName())
165 return (resolve(DT.getTypeDerivedFrom()));
171 } // end llvm namespace
173 /// Return Dwarf Version by checking module flags.
174 static unsigned getDwarfVersionFromModule(const Module *M) {
175 Value *Val = M->getModuleFlag("Dwarf Version");
177 return dwarf::DWARF_VERSION;
178 return cast<ConstantInt>(Val)->getZExtValue();
181 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
182 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
183 PrevLabel(NULL), GlobalRangeCount(0),
184 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
185 UsedNonDefaultText(false),
186 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
188 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
189 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
190 DwarfAddrSectionSym = 0;
191 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
192 FunctionBeginSym = FunctionEndSym = 0;
196 // Turn on accelerator tables for Darwin by default, pubnames by
197 // default for non-Darwin, and handle split dwarf.
198 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
200 if (DwarfAccelTables == Default)
201 HasDwarfAccelTables = IsDarwin;
203 HasDwarfAccelTables = DwarfAccelTables == Enable;
205 if (SplitDwarf == Default)
206 HasSplitDwarf = false;
208 HasSplitDwarf = SplitDwarf == Enable;
210 if (DwarfPubSections == Default)
211 HasDwarfPubSections = !IsDarwin;
213 HasDwarfPubSections = DwarfPubSections == Enable;
215 DwarfVersion = DwarfVersionNumber
217 : getDwarfVersionFromModule(MMI->getModule());
220 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
225 // Switch to the specified MCSection and emit an assembler
226 // temporary label to it if SymbolStem is specified.
227 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
228 const char *SymbolStem = 0) {
229 Asm->OutStreamer.SwitchSection(Section);
233 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
234 Asm->OutStreamer.EmitLabel(TmpSym);
238 DwarfFile::~DwarfFile() {
239 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
244 MCSymbol *DwarfFile::getStringPoolSym() {
245 return Asm->GetTempSymbol(StringPref);
248 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
249 std::pair<MCSymbol *, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
254 Entry.second = NextStringPoolNumber++;
255 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
259 std::pair<MCSymbol *, unsigned> &Entry =
260 StringPool.GetOrCreateValue(Str).getValue();
264 Entry.second = NextStringPoolNumber++;
265 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
269 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
270 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
271 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
273 ++NextAddrPoolNumber;
274 return P.first->second.Number;
277 // Define a unique number for the abbreviation.
279 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
280 // Check the set for priors.
281 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
283 // If it's newly added.
284 if (InSet == &Abbrev) {
285 // Add to abbreviation list.
286 Abbreviations.push_back(&Abbrev);
288 // Assign the vector position + 1 as its number.
289 Abbrev.setNumber(Abbreviations.size());
291 // Assign existing abbreviation number.
292 Abbrev.setNumber(InSet->getNumber());
296 static bool isObjCClass(StringRef Name) {
297 return Name.startswith("+") || Name.startswith("-");
300 static bool hasObjCCategory(StringRef Name) {
301 if (!isObjCClass(Name))
304 return Name.find(") ") != StringRef::npos;
307 static void getObjCClassCategory(StringRef In, StringRef &Class,
308 StringRef &Category) {
309 if (!hasObjCCategory(In)) {
310 Class = In.slice(In.find('[') + 1, In.find(' '));
315 Class = In.slice(In.find('[') + 1, In.find('('));
316 Category = In.slice(In.find('[') + 1, In.find(' '));
320 static StringRef getObjCMethodName(StringRef In) {
321 return In.slice(In.find(' ') + 1, In.find(']'));
324 // Helper for sorting sections into a stable output order.
325 static bool SectionSort(const MCSection *A, const MCSection *B) {
326 std::string LA = (A ? A->getLabelBeginName() : "");
327 std::string LB = (B ? B->getLabelBeginName() : "");
331 // Add the various names to the Dwarf accelerator table names.
332 // TODO: Determine whether or not we should add names for programs
333 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
334 // is only slightly different than the lookup of non-standard ObjC names.
335 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
336 if (!SP.isDefinition())
338 TheU->addAccelName(SP.getName(), Die);
340 // If the linkage name is different than the name, go ahead and output
341 // that as well into the name table.
342 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
343 TheU->addAccelName(SP.getLinkageName(), Die);
345 // If this is an Objective-C selector name add it to the ObjC accelerator
347 if (isObjCClass(SP.getName())) {
348 StringRef Class, Category;
349 getObjCClassCategory(SP.getName(), Class, Category);
350 TheU->addAccelObjC(Class, Die);
352 TheU->addAccelObjC(Category, Die);
353 // Also add the base method name to the name table.
354 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
358 /// isSubprogramContext - Return true if Context is either a subprogram
359 /// or another context nested inside a subprogram.
360 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
363 DIDescriptor D(Context);
364 if (D.isSubprogram())
367 return isSubprogramContext(resolve(DIType(Context).getContext()));
371 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
372 // and DW_AT_high_pc attributes. If there are global variables in this
373 // scope then create and insert DIEs for these variables.
374 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
376 DIE *SPDie = SPCU->getDIE(SP);
378 assert(SPDie && "Unable to find subprogram DIE!");
380 // If we're updating an abstract DIE, then we will be adding the children and
381 // object pointer later on. But what we don't want to do is process the
382 // concrete DIE twice.
383 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
384 // Pick up abstract subprogram DIE.
386 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
387 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
389 DISubprogram SPDecl = SP.getFunctionDeclaration();
390 if (!SPDecl.isSubprogram()) {
391 // There is not any need to generate specification DIE for a function
392 // defined at compile unit level. If a function is defined inside another
393 // function then gdb prefers the definition at top level and but does not
394 // expect specification DIE in parent function. So avoid creating
395 // specification DIE for a function defined inside a function.
396 DIScope SPContext = resolve(SP.getContext());
397 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
398 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
399 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
402 DICompositeType SPTy = SP.getType();
403 DIArray Args = SPTy.getTypeArray();
404 uint16_t SPTag = SPTy.getTag();
405 if (SPTag == dwarf::DW_TAG_subroutine_type)
406 SPCU->constructSubprogramArguments(*SPDie, Args);
407 DIE *SPDeclDie = SPDie;
408 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
409 *SPCU->getUnitDie());
410 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
415 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
416 SPCU->addLabelDelta(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym,
419 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
420 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
421 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
423 // Add name to the name table, we do this here because we're guaranteed
424 // to have concrete versions of our DW_TAG_subprogram nodes.
425 addSubprogramNames(SPCU, SP, SPDie);
430 /// Check whether we should create a DIE for the given Scope, return true
431 /// if we don't create a DIE (the corresponding DIE is null).
432 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
433 if (Scope->isAbstractScope())
436 // We don't create a DIE if there is no Range.
437 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
441 if (Ranges.size() > 1)
444 // We don't create a DIE if we have a single Range and the end label
446 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
447 MCSymbol *End = getLabelAfterInsn(RI->second);
451 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
452 dwarf::Attribute A, const MCSymbol *L,
453 const MCSymbol *Sec) {
454 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
455 U->addSectionLabel(D, A, L);
457 U->addSectionDelta(D, A, L, Sec);
460 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
461 const SmallVectorImpl<InsnRange> &Range) {
462 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
463 // emitting it appropriately.
464 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
465 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
466 DwarfDebugRangeSectionSym);
468 RangeSpanList List(RangeSym);
469 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
472 RangeSpan Span(getLabelBeforeInsn(RI->first),
473 getLabelAfterInsn(RI->second));
474 List.addRange(std::move(Span));
477 // Add the range list to the set of ranges to be emitted.
478 TheCU->addRangeList(std::move(List));
481 // Construct new DW_TAG_lexical_block for this scope and attach
482 // DW_AT_low_pc/DW_AT_high_pc labels.
483 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
484 LexicalScope *Scope) {
485 if (isLexicalScopeDIENull(Scope))
488 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
489 if (Scope->isAbstractScope())
492 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
494 // If we have multiple ranges, emit them into the range section.
495 if (ScopeRanges.size() > 1) {
496 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
500 // Construct the address range for this DIE.
501 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
502 MCSymbol *Start = getLabelBeforeInsn(RI->first);
503 MCSymbol *End = getLabelAfterInsn(RI->second);
504 assert(End && "End label should not be null!");
506 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
507 assert(End->isDefined() && "Invalid end label for an inlined scope!");
509 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
510 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
515 // This scope represents inlined body of a function. Construct DIE to
516 // represent this concrete inlined copy of the function.
517 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
518 LexicalScope *Scope) {
519 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
520 assert(!ScopeRanges.empty() &&
521 "LexicalScope does not have instruction markers!");
523 if (!Scope->getScopeNode())
525 DIScope DS(Scope->getScopeNode());
526 DISubprogram InlinedSP = getDISubprogram(DS);
527 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
529 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
533 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
534 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
536 // If we have multiple ranges, emit them into the range section.
537 if (ScopeRanges.size() > 1)
538 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
540 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
541 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
542 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
544 if (StartLabel == 0 || EndLabel == 0)
545 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
547 assert(StartLabel->isDefined() &&
548 "Invalid starting label for an inlined scope!");
549 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
551 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
552 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
555 InlinedSubprogramDIEs.insert(OriginDIE);
557 // Add the call site information to the DIE.
558 DILocation DL(Scope->getInlinedAt());
559 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
560 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
561 TheCU->getUniqueID()));
562 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
564 // Add name to the name table, we do this here because we're guaranteed
565 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
566 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
571 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
573 SmallVectorImpl<DIE *> &Children) {
574 DIE *ObjectPointer = NULL;
576 // Collect arguments for current function.
577 if (LScopes.isCurrentFunctionScope(Scope)) {
578 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
579 if (DbgVariable *ArgDV = CurrentFnArguments[i])
581 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
582 Children.push_back(Arg);
583 if (ArgDV->isObjectPointer())
587 // If this is a variadic function, add an unspecified parameter.
588 DISubprogram SP(Scope->getScopeNode());
589 DIArray FnArgs = SP.getType().getTypeArray();
590 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
591 .isUnspecifiedParameter()) {
592 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
593 Children.push_back(Ellipsis);
597 // Collect lexical scope children first.
598 const SmallVectorImpl<DbgVariable *> &Variables =
599 ScopeVariables.lookup(Scope);
600 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
601 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
602 Scope->isAbstractScope())) {
603 Children.push_back(Variable);
604 if (Variables[i]->isObjectPointer())
605 ObjectPointer = Variable;
607 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
608 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
609 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
610 Children.push_back(Nested);
611 return ObjectPointer;
614 // Construct a DIE for this scope.
615 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
616 LexicalScope *Scope) {
617 if (!Scope || !Scope->getScopeNode())
620 DIScope DS(Scope->getScopeNode());
622 SmallVector<DIE *, 8> Children;
623 DIE *ObjectPointer = NULL;
624 bool ChildrenCreated = false;
626 // We try to create the scope DIE first, then the children DIEs. This will
627 // avoid creating un-used children then removing them later when we find out
628 // the scope DIE is null.
629 DIE *ScopeDIE = NULL;
630 if (Scope->getInlinedAt())
631 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
632 else if (DS.isSubprogram()) {
633 ProcessedSPNodes.insert(DS);
634 if (Scope->isAbstractScope()) {
635 ScopeDIE = TheCU->getDIE(DS);
636 // Note down abstract DIE.
638 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
640 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
642 // Early exit when we know the scope DIE is going to be null.
643 if (isLexicalScopeDIENull(Scope))
646 // We create children here when we know the scope DIE is not going to be
647 // null and the children will be added to the scope DIE.
648 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
649 ChildrenCreated = true;
651 // There is no need to emit empty lexical block DIE.
652 std::pair<ImportedEntityMap::const_iterator,
653 ImportedEntityMap::const_iterator> Range =
655 ScopesWithImportedEntities.begin(),
656 ScopesWithImportedEntities.end(),
657 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
659 if (Children.empty() && Range.first == Range.second)
661 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
662 assert(ScopeDIE && "Scope DIE should not be null.");
663 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
665 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
669 assert(Children.empty() &&
670 "We create children only when the scope DIE is not null.");
673 if (!ChildrenCreated)
674 // We create children when the scope DIE is not null.
675 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
678 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
681 ScopeDIE->addChild(*I);
683 if (DS.isSubprogram() && ObjectPointer != NULL)
684 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
689 // Look up the source id with the given directory and source file names.
690 // If none currently exists, create a new id and insert it in the
691 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
693 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
695 // If we print assembly, we can't separate .file entries according to
696 // compile units. Thus all files will belong to the default compile unit.
698 // FIXME: add a better feature test than hasRawTextSupport. Even better,
699 // extend .file to support this.
700 if (Asm->OutStreamer.hasRawTextSupport())
703 // If FE did not provide a file name, then assume stdin.
704 if (FileName.empty())
705 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
707 // TODO: this might not belong here. See if we can factor this better.
708 if (DirName == CompilationDir)
711 // FileIDCUMap stores the current ID for the given compile unit.
712 unsigned SrcId = FileIDCUMap[CUID] + 1;
714 // We look up the CUID/file/dir by concatenating them with a zero byte.
715 SmallString<128> NamePair;
716 NamePair += utostr(CUID);
719 NamePair += '\0'; // Zero bytes are not allowed in paths.
720 NamePair += FileName;
722 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
723 if (Ent.getValue() != SrcId)
724 return Ent.getValue();
726 FileIDCUMap[CUID] = SrcId;
727 // Print out a .file directive to specify files for .loc directives.
728 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
733 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
734 if (!GenerateGnuPubSections)
737 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
740 // Create new DwarfCompileUnit for the given metadata node with tag
741 // DW_TAG_compile_unit.
742 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
743 StringRef FN = DIUnit.getFilename();
744 CompilationDir = DIUnit.getDirectory();
746 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
747 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
748 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
749 InfoHolder.addUnit(NewCU);
751 FileIDCUMap[NewCU->getUniqueID()] = 0;
753 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
754 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
755 DIUnit.getLanguage());
756 NewCU->addString(Die, dwarf::DW_AT_name, FN);
758 if (!useSplitDwarf()) {
759 NewCU->initStmtList(DwarfLineSectionSym);
761 // If we're using split dwarf the compilation dir is going to be in the
762 // skeleton CU and so we don't need to duplicate it here.
763 if (!CompilationDir.empty())
764 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
766 addGnuPubAttributes(NewCU, Die);
769 if (DIUnit.isOptimized())
770 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
772 StringRef Flags = DIUnit.getFlags();
774 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
776 if (unsigned RVer = DIUnit.getRunTimeVersion())
777 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
778 dwarf::DW_FORM_data1, RVer);
783 if (useSplitDwarf()) {
784 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
785 DwarfInfoDWOSectionSym);
786 NewCU->setSkeleton(constructSkeletonCU(NewCU));
788 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
789 DwarfInfoSectionSym);
791 CUMap.insert(std::make_pair(DIUnit, NewCU));
792 CUDieMap.insert(std::make_pair(Die, NewCU));
796 // Construct subprogram DIE.
797 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
799 // FIXME: We should only call this routine once, however, during LTO if a
800 // program is defined in multiple CUs we could end up calling it out of
801 // beginModule as we walk the CUs.
803 DwarfCompileUnit *&CURef = SPMap[N];
809 if (!SP.isDefinition())
810 // This is a method declaration which will be handled while constructing
814 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
816 // Expose as a global name.
817 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
820 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
822 DIImportedEntity Module(N);
823 assert(Module.Verify());
824 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
825 constructImportedEntityDIE(TheCU, Module, D);
828 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
829 const MDNode *N, DIE *Context) {
830 DIImportedEntity Module(N);
831 assert(Module.Verify());
832 return constructImportedEntityDIE(TheCU, Module, Context);
835 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
836 const DIImportedEntity &Module,
838 assert(Module.Verify() &&
839 "Use one of the MDNode * overloads to handle invalid metadata");
840 assert(Context && "Should always have a context for an imported_module");
841 DIE *IMDie = new DIE(Module.getTag());
842 TheCU->insertDIE(Module, IMDie);
844 DIDescriptor Entity = Module.getEntity();
845 if (Entity.isNameSpace())
846 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
847 else if (Entity.isSubprogram())
848 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
849 else if (Entity.isType())
850 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
852 EntityDie = TheCU->getDIE(Entity);
853 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
854 Module.getContext().getDirectory(),
855 TheCU->getUniqueID());
856 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
857 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
858 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
859 StringRef Name = Module.getName();
861 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
862 Context->addChild(IMDie);
865 // Emit all Dwarf sections that should come prior to the content. Create
866 // global DIEs and emit initial debug info sections. This is invoked by
867 // the target AsmPrinter.
868 void DwarfDebug::beginModule() {
869 if (DisableDebugInfoPrinting)
872 const Module *M = MMI->getModule();
874 // If module has named metadata anchors then use them, otherwise scan the
875 // module using debug info finder to collect debug info.
876 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
879 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
881 // Emit initial sections so we can reference labels later.
884 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
885 DICompileUnit CUNode(CU_Nodes->getOperand(i));
886 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
887 DIArray ImportedEntities = CUNode.getImportedEntities();
888 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
889 ScopesWithImportedEntities.push_back(std::make_pair(
890 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
891 ImportedEntities.getElement(i)));
892 std::sort(ScopesWithImportedEntities.begin(),
893 ScopesWithImportedEntities.end(), less_first());
894 DIArray GVs = CUNode.getGlobalVariables();
895 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
896 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
897 DIArray SPs = CUNode.getSubprograms();
898 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
899 constructSubprogramDIE(CU, SPs.getElement(i));
900 DIArray EnumTypes = CUNode.getEnumTypes();
901 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
902 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
903 DIArray RetainedTypes = CUNode.getRetainedTypes();
904 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
905 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
906 // Emit imported_modules last so that the relevant context is already
908 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
909 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
912 // Tell MMI that we have debug info.
913 MMI->setDebugInfoAvailability(true);
915 // Prime section data.
916 SectionMap[Asm->getObjFileLowering().getTextSection()];
919 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
920 void DwarfDebug::computeInlinedDIEs() {
921 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
922 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
923 AE = InlinedSubprogramDIEs.end();
926 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
928 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
929 AE = AbstractSPDies.end();
931 DIE *ISP = AI->second;
932 if (InlinedSubprogramDIEs.count(ISP))
934 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
938 // Collect info for variables that were optimized out.
939 void DwarfDebug::collectDeadVariables() {
940 const Module *M = MMI->getModule();
942 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
943 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
944 DICompileUnit TheCU(CU_Nodes->getOperand(i));
945 DIArray Subprograms = TheCU.getSubprograms();
946 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
947 DISubprogram SP(Subprograms.getElement(i));
948 if (ProcessedSPNodes.count(SP) != 0)
950 if (!SP.isSubprogram())
952 if (!SP.isDefinition())
954 DIArray Variables = SP.getVariables();
955 if (Variables.getNumElements() == 0)
958 // Construct subprogram DIE and add variables DIEs.
959 DwarfCompileUnit *SPCU =
960 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
961 assert(SPCU && "Unable to find Compile Unit!");
962 // FIXME: See the comment in constructSubprogramDIE about duplicate
964 constructSubprogramDIE(SPCU, SP);
965 DIE *SPDIE = SPCU->getDIE(SP);
966 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
967 DIVariable DV(Variables.getElement(vi));
968 if (!DV.isVariable())
970 DbgVariable NewVar(DV, NULL, this);
971 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
972 SPDIE->addChild(VariableDIE);
979 void DwarfDebug::finalizeModuleInfo() {
980 // Collect info for variables that were optimized out.
981 collectDeadVariables();
983 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
984 computeInlinedDIEs();
986 // Handle anything that needs to be done on a per-unit basis after
987 // all other generation.
988 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
989 E = getUnits().end();
991 DwarfUnit *TheU = *I;
992 // Emit DW_AT_containing_type attribute to connect types with their
993 // vtable holding type.
994 TheU->constructContainingTypeDIEs();
996 // Add CU specific attributes if we need to add any.
997 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
998 // If we're splitting the dwarf out now that we've got the entire
999 // CU then add the dwo id to it.
1000 DwarfCompileUnit *SkCU =
1001 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1002 if (useSplitDwarf()) {
1003 // This should be a unique identifier when we want to build .dwp files.
1005 if (GenerateCUHash) {
1006 DIEHash CUHash(Asm);
1007 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1009 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1010 dwarf::DW_FORM_data8, ID);
1011 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1012 dwarf::DW_FORM_data8, ID);
1015 // If we have code split among multiple sections or we've requested
1016 // it then emit a DW_AT_ranges attribute on the unit that will remain
1017 // in the .o file, otherwise add a DW_AT_low_pc.
1018 // FIXME: Also add a high pc if we can.
1019 // FIXME: We should use ranges if we have multiple compile units or
1020 // allow reordering of code ala .subsections_via_symbols in mach-o.
1021 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1022 if (useCURanges() && TheU->getRanges().size()) {
1023 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1024 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1025 DwarfDebugRangeSectionSym);
1027 // A DW_AT_low_pc attribute may also be specified in combination with
1028 // DW_AT_ranges to specify the default base address for use in location
1029 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1030 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1033 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1038 // Compute DIE offsets and sizes.
1039 InfoHolder.computeSizeAndOffsets();
1040 if (useSplitDwarf())
1041 SkeletonHolder.computeSizeAndOffsets();
1044 void DwarfDebug::endSections() {
1045 // Filter labels by section.
1046 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1047 const SymbolCU &SCU = ArangeLabels[n];
1048 if (SCU.Sym->isInSection()) {
1049 // Make a note of this symbol and it's section.
1050 const MCSection *Section = &SCU.Sym->getSection();
1051 if (!Section->getKind().isMetadata())
1052 SectionMap[Section].push_back(SCU);
1054 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1055 // appear in the output. This sucks as we rely on sections to build
1056 // arange spans. We can do it without, but it's icky.
1057 SectionMap[NULL].push_back(SCU);
1061 // Build a list of sections used.
1062 std::vector<const MCSection *> Sections;
1063 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1065 const MCSection *Section = it->first;
1066 Sections.push_back(Section);
1069 // Sort the sections into order.
1070 // This is only done to ensure consistent output order across different runs.
1071 std::sort(Sections.begin(), Sections.end(), SectionSort);
1073 // Add terminating symbols for each section.
1074 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1075 const MCSection *Section = Sections[ID];
1076 MCSymbol *Sym = NULL;
1079 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1080 // if we know the section name up-front. For user-created sections, the
1081 // resulting label may not be valid to use as a label. (section names can
1082 // use a greater set of characters on some systems)
1083 Sym = Asm->GetTempSymbol("debug_end", ID);
1084 Asm->OutStreamer.SwitchSection(Section);
1085 Asm->OutStreamer.EmitLabel(Sym);
1088 // Insert a final terminator.
1089 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1092 // For now only turn on CU ranges if we've explicitly asked for it,
1093 // we have -ffunction-sections enabled, we've emitted a function
1094 // into a unique section, or we're using LTO. If we're using LTO then
1095 // we can't know that any particular function in the module is correlated
1096 // to a particular CU and so we need to be conservative. At this point all
1097 // sections should be finalized except for dwarf sections.
1098 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1099 TargetMachine::getFunctionSections();
1102 // Emit all Dwarf sections that should come after the content.
1103 void DwarfDebug::endModule() {
1110 // End any existing sections.
1111 // TODO: Does this need to happen?
1114 // Finalize the debug info for the module.
1115 finalizeModuleInfo();
1119 // Emit all the DIEs into a debug info section.
1122 // Corresponding abbreviations into a abbrev section.
1123 emitAbbreviations();
1125 // Emit info into a debug loc section.
1128 // Emit info into a debug aranges section.
1129 if (GenerateARangeSection)
1132 // Emit info into a debug ranges section.
1135 if (useSplitDwarf()) {
1138 emitDebugAbbrevDWO();
1139 // Emit DWO addresses.
1140 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1143 // Emit info into the dwarf accelerator table sections.
1144 if (useDwarfAccelTables()) {
1147 emitAccelNamespaces();
1151 // Emit the pubnames and pubtypes sections if requested.
1152 if (HasDwarfPubSections) {
1153 emitDebugPubNames(GenerateGnuPubSections);
1154 emitDebugPubTypes(GenerateGnuPubSections);
1160 // Reset these for the next Module if we have one.
1164 // Find abstract variable, if any, associated with Var.
1165 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1166 DebugLoc ScopeLoc) {
1167 LLVMContext &Ctx = DV->getContext();
1168 // More then one inlined variable corresponds to one abstract variable.
1169 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1170 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1172 return AbsDbgVariable;
1174 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1178 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1179 addScopeVariable(Scope, AbsDbgVariable);
1180 AbstractVariables[Var] = AbsDbgVariable;
1181 return AbsDbgVariable;
1184 // If Var is a current function argument then add it to CurrentFnArguments list.
1185 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1186 if (!LScopes.isCurrentFunctionScope(Scope))
1188 DIVariable DV = Var->getVariable();
1189 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1191 unsigned ArgNo = DV.getArgNumber();
1195 size_t Size = CurrentFnArguments.size();
1197 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1198 // llvm::Function argument size is not good indicator of how many
1199 // arguments does the function have at source level.
1201 CurrentFnArguments.resize(ArgNo * 2);
1202 CurrentFnArguments[ArgNo - 1] = Var;
1206 // Collect variable information from side table maintained by MMI.
1207 void DwarfDebug::collectVariableInfoFromMMITable(
1208 SmallPtrSet<const MDNode *, 16> &Processed) {
1209 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1210 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1213 const MDNode *Var = VI->first;
1216 Processed.insert(Var);
1218 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1220 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1222 // If variable scope is not found then skip this variable.
1226 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1227 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1228 RegVar->setFrameIndex(VP.first);
1229 if (!addCurrentFnArgument(RegVar, Scope))
1230 addScopeVariable(Scope, RegVar);
1232 AbsDbgVariable->setFrameIndex(VP.first);
1236 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1238 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1239 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1240 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1241 MI->getOperand(0).getReg() &&
1242 (MI->getOperand(1).isImm() ||
1243 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1246 // Get .debug_loc entry for the instruction range starting at MI.
1247 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1248 const MCSymbol *FLabel,
1249 const MCSymbol *SLabel,
1250 const MachineInstr *MI) {
1251 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1253 assert(MI->getNumOperands() == 3);
1254 if (MI->getOperand(0).isReg()) {
1255 MachineLocation MLoc;
1256 // If the second operand is an immediate, this is a
1257 // register-indirect address.
1258 if (!MI->getOperand(1).isImm())
1259 MLoc.set(MI->getOperand(0).getReg());
1261 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1262 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1264 if (MI->getOperand(0).isImm())
1265 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1266 if (MI->getOperand(0).isFPImm())
1267 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1268 if (MI->getOperand(0).isCImm())
1269 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1271 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1274 // Find variables for each lexical scope.
1276 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1278 // Grab the variable info that was squirreled away in the MMI side-table.
1279 collectVariableInfoFromMMITable(Processed);
1281 for (SmallVectorImpl<const MDNode *>::const_iterator
1282 UVI = UserVariables.begin(),
1283 UVE = UserVariables.end();
1284 UVI != UVE; ++UVI) {
1285 const MDNode *Var = *UVI;
1286 if (Processed.count(Var))
1289 // History contains relevant DBG_VALUE instructions for Var and instructions
1291 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1292 if (History.empty())
1294 const MachineInstr *MInsn = History.front();
1297 LexicalScope *Scope = NULL;
1298 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1299 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1300 Scope = LScopes.getCurrentFunctionScope();
1301 else if (MDNode *IA = DV.getInlinedAt())
1302 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1304 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1305 // If variable scope is not found then skip this variable.
1309 Processed.insert(DV);
1310 assert(MInsn->isDebugValue() && "History must begin with debug value");
1311 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1312 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1313 if (!addCurrentFnArgument(RegVar, Scope))
1314 addScopeVariable(Scope, RegVar);
1316 AbsVar->setMInsn(MInsn);
1318 // Simplify ranges that are fully coalesced.
1319 if (History.size() <= 1 ||
1320 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1321 RegVar->setMInsn(MInsn);
1325 // Handle multiple DBG_VALUE instructions describing one variable.
1326 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1328 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1329 HI = History.begin(),
1332 const MachineInstr *Begin = *HI;
1333 assert(Begin->isDebugValue() && "Invalid History entry");
1335 // Check if DBG_VALUE is truncating a range.
1336 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1337 !Begin->getOperand(0).getReg())
1340 // Compute the range for a register location.
1341 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1342 const MCSymbol *SLabel = 0;
1345 // If Begin is the last instruction in History then its value is valid
1346 // until the end of the function.
1347 SLabel = FunctionEndSym;
1349 const MachineInstr *End = HI[1];
1350 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1351 << "\t" << *Begin << "\t" << *End << "\n");
1352 if (End->isDebugValue())
1353 SLabel = getLabelBeforeInsn(End);
1355 // End is a normal instruction clobbering the range.
1356 SLabel = getLabelAfterInsn(End);
1357 assert(SLabel && "Forgot label after clobber instruction");
1362 // The value is valid until the next DBG_VALUE or clobber.
1363 DotDebugLocEntries.push_back(
1364 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1366 DotDebugLocEntries.push_back(DotDebugLocEntry());
1369 // Collect info for variables that were optimized out.
1370 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1371 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1372 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1373 DIVariable DV(Variables.getElement(i));
1374 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1376 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1377 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1381 // Return Label preceding the instruction.
1382 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1383 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1384 assert(Label && "Didn't insert label before instruction");
1388 // Return Label immediately following the instruction.
1389 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1390 return LabelsAfterInsn.lookup(MI);
1393 // Process beginning of an instruction.
1394 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1397 // Check if source location changes, but ignore DBG_VALUE locations.
1398 if (!MI->isDebugValue()) {
1399 DebugLoc DL = MI->getDebugLoc();
1400 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1403 if (DL == PrologEndLoc) {
1404 Flags |= DWARF2_FLAG_PROLOGUE_END;
1405 PrologEndLoc = DebugLoc();
1407 if (PrologEndLoc.isUnknown())
1408 Flags |= DWARF2_FLAG_IS_STMT;
1410 if (!DL.isUnknown()) {
1411 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1412 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1414 recordSourceLine(0, 0, 0, 0);
1418 // Insert labels where requested.
1419 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1420 LabelsBeforeInsn.find(MI);
1423 if (I == LabelsBeforeInsn.end())
1426 // Label already assigned.
1431 PrevLabel = MMI->getContext().CreateTempSymbol();
1432 Asm->OutStreamer.EmitLabel(PrevLabel);
1434 I->second = PrevLabel;
1437 // Process end of an instruction.
1438 void DwarfDebug::endInstruction() {
1440 // Don't create a new label after DBG_VALUE instructions.
1441 // They don't generate code.
1442 if (!CurMI->isDebugValue())
1445 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1446 LabelsAfterInsn.find(CurMI);
1450 if (I == LabelsAfterInsn.end())
1453 // Label already assigned.
1457 // We need a label after this instruction.
1459 PrevLabel = MMI->getContext().CreateTempSymbol();
1460 Asm->OutStreamer.EmitLabel(PrevLabel);
1462 I->second = PrevLabel;
1465 // Each LexicalScope has first instruction and last instruction to mark
1466 // beginning and end of a scope respectively. Create an inverse map that list
1467 // scopes starts (and ends) with an instruction. One instruction may start (or
1468 // end) multiple scopes. Ignore scopes that are not reachable.
1469 void DwarfDebug::identifyScopeMarkers() {
1470 SmallVector<LexicalScope *, 4> WorkList;
1471 WorkList.push_back(LScopes.getCurrentFunctionScope());
1472 while (!WorkList.empty()) {
1473 LexicalScope *S = WorkList.pop_back_val();
1475 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1476 if (!Children.empty())
1477 for (SmallVectorImpl<LexicalScope *>::const_iterator
1478 SI = Children.begin(),
1479 SE = Children.end();
1481 WorkList.push_back(*SI);
1483 if (S->isAbstractScope())
1486 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1489 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1492 assert(RI->first && "InsnRange does not have first instruction!");
1493 assert(RI->second && "InsnRange does not have second instruction!");
1494 requestLabelBeforeInsn(RI->first);
1495 requestLabelAfterInsn(RI->second);
1500 // Gather pre-function debug information. Assumes being called immediately
1501 // after the function entry point has been emitted.
1502 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1505 // If there's no debug info for the function we're not going to do anything.
1506 if (!MMI->hasDebugInfo())
1509 // Grab the lexical scopes for the function, if we don't have any of those
1510 // then we're not going to be able to do anything.
1511 LScopes.initialize(*MF);
1512 if (LScopes.empty())
1515 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1517 // Make sure that each lexical scope will have a begin/end label.
1518 identifyScopeMarkers();
1520 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1521 // belongs to so that we add to the correct per-cu line table in the
1523 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1524 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1525 assert(TheCU && "Unable to find compile unit!");
1526 if (Asm->OutStreamer.hasRawTextSupport())
1527 // Use a single line table if we are generating assembly.
1528 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1530 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1532 // Check the current section against the standard text section. If different
1533 // keep track so that we will know when we're emitting functions into multiple
1535 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1536 UsedNonDefaultText = true;
1538 // Emit a label for the function so that we have a beginning address.
1539 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1540 // Assumes in correct section after the entry point.
1541 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1543 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1544 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1545 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1547 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1549 bool AtBlockEntry = true;
1550 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1552 const MachineInstr *MI = II;
1554 if (MI->isDebugValue()) {
1555 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1557 // Keep track of user variables.
1559 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1561 // Variable is in a register, we need to check for clobbers.
1562 if (isDbgValueInDefinedReg(MI))
1563 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1565 // Check the history of this variable.
1566 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1567 if (History.empty()) {
1568 UserVariables.push_back(Var);
1569 // The first mention of a function argument gets the FunctionBeginSym
1570 // label, so arguments are visible when breaking at function entry.
1572 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1573 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1574 LabelsBeforeInsn[MI] = FunctionBeginSym;
1576 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1577 const MachineInstr *Prev = History.back();
1578 if (Prev->isDebugValue()) {
1579 // Coalesce identical entries at the end of History.
1580 if (History.size() >= 2 &&
1581 Prev->isIdenticalTo(History[History.size() - 2])) {
1582 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1583 << "\t" << *Prev << "\t"
1584 << *History[History.size() - 2] << "\n");
1588 // Terminate old register assignments that don't reach MI;
1589 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1590 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1591 isDbgValueInDefinedReg(Prev)) {
1592 // Previous register assignment needs to terminate at the end of
1594 MachineBasicBlock::const_iterator LastMI =
1595 PrevMBB->getLastNonDebugInstr();
1596 if (LastMI == PrevMBB->end()) {
1597 // Drop DBG_VALUE for empty range.
1598 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1599 << "\t" << *Prev << "\n");
1601 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1602 // Terminate after LastMI.
1603 History.push_back(LastMI);
1607 History.push_back(MI);
1609 // Not a DBG_VALUE instruction.
1611 AtBlockEntry = false;
1613 // First known non-DBG_VALUE and non-frame setup location marks
1614 // the beginning of the function body.
1615 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1616 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1617 PrologEndLoc = MI->getDebugLoc();
1619 // Check if the instruction clobbers any registers with debug vars.
1620 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1621 MOE = MI->operands_end();
1622 MOI != MOE; ++MOI) {
1623 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1625 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1628 const MDNode *Var = LiveUserVar[Reg];
1631 // Reg is now clobbered.
1632 LiveUserVar[Reg] = 0;
1634 // Was MD last defined by a DBG_VALUE referring to Reg?
1635 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1636 if (HistI == DbgValues.end())
1638 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1639 if (History.empty())
1641 const MachineInstr *Prev = History.back();
1642 // Sanity-check: Register assignments are terminated at the end of
1644 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1646 // Is the variable still in Reg?
1647 if (!isDbgValueInDefinedReg(Prev) ||
1648 Prev->getOperand(0).getReg() != Reg)
1650 // Var is clobbered. Make sure the next instruction gets a label.
1651 History.push_back(MI);
1658 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1660 SmallVectorImpl<const MachineInstr *> &History = I->second;
1661 if (History.empty())
1664 // Make sure the final register assignments are terminated.
1665 const MachineInstr *Prev = History.back();
1666 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1667 const MachineBasicBlock *PrevMBB = Prev->getParent();
1668 MachineBasicBlock::const_iterator LastMI =
1669 PrevMBB->getLastNonDebugInstr();
1670 if (LastMI == PrevMBB->end())
1671 // Drop DBG_VALUE for empty range.
1673 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1674 // Terminate after LastMI.
1675 History.push_back(LastMI);
1678 // Request labels for the full history.
1679 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1680 const MachineInstr *MI = History[i];
1681 if (MI->isDebugValue())
1682 requestLabelBeforeInsn(MI);
1684 requestLabelAfterInsn(MI);
1688 PrevInstLoc = DebugLoc();
1689 PrevLabel = FunctionBeginSym;
1691 // Record beginning of function.
1692 if (!PrologEndLoc.isUnknown()) {
1693 DebugLoc FnStartDL =
1694 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1696 FnStartDL.getLine(), FnStartDL.getCol(),
1697 FnStartDL.getScope(MF->getFunction()->getContext()),
1698 // We'd like to list the prologue as "not statements" but GDB behaves
1699 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1700 DWARF2_FLAG_IS_STMT);
1704 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1705 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1706 DIVariable DV = Var->getVariable();
1707 // Variables with positive arg numbers are parameters.
1708 if (unsigned ArgNum = DV.getArgNumber()) {
1709 // Keep all parameters in order at the start of the variable list to ensure
1710 // function types are correct (no out-of-order parameters)
1712 // This could be improved by only doing it for optimized builds (unoptimized
1713 // builds have the right order to begin with), searching from the back (this
1714 // would catch the unoptimized case quickly), or doing a binary search
1715 // rather than linear search.
1716 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1717 while (I != Vars.end()) {
1718 unsigned CurNum = (*I)->getVariable().getArgNumber();
1719 // A local (non-parameter) variable has been found, insert immediately
1723 // A later indexed parameter has been found, insert immediately before it.
1724 if (CurNum > ArgNum)
1728 Vars.insert(I, Var);
1732 Vars.push_back(Var);
1735 // Gather and emit post-function debug information.
1736 void DwarfDebug::endFunction(const MachineFunction *MF) {
1737 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1738 // though the beginFunction may not be called at all.
1739 // We should handle both cases.
1743 assert(CurFn == MF);
1746 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1751 // Define end label for subprogram.
1752 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1753 // Assumes in correct section after the entry point.
1754 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1756 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1757 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1759 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1760 collectVariableInfo(ProcessedVars);
1762 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1763 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1764 assert(TheCU && "Unable to find compile unit!");
1766 // Construct abstract scopes.
1767 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1768 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1769 LexicalScope *AScope = AList[i];
1770 DISubprogram SP(AScope->getScopeNode());
1771 if (SP.isSubprogram()) {
1772 // Collect info for variables that were optimized out.
1773 DIArray Variables = SP.getVariables();
1774 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1775 DIVariable DV(Variables.getElement(i));
1776 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1778 // Check that DbgVariable for DV wasn't created earlier, when
1779 // findAbstractVariable() was called for inlined instance of DV.
1780 LLVMContext &Ctx = DV->getContext();
1781 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1782 if (AbstractVariables.lookup(CleanDV))
1784 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1785 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1788 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1789 constructScopeDIE(TheCU, AScope);
1792 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1793 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1794 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1796 // Add the range of this function to the list of ranges for the CU.
1797 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1798 TheCU->addRange(std::move(Span));
1801 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1802 E = ScopeVariables.end();
1804 DeleteContainerPointers(I->second);
1805 ScopeVariables.clear();
1806 DeleteContainerPointers(CurrentFnArguments);
1807 UserVariables.clear();
1809 AbstractVariables.clear();
1810 LabelsBeforeInsn.clear();
1811 LabelsAfterInsn.clear();
1816 // Register a source line with debug info. Returns the unique label that was
1817 // emitted and which provides correspondence to the source line list.
1818 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1823 unsigned Discriminator = 0;
1825 DIDescriptor Scope(S);
1827 if (Scope.isCompileUnit()) {
1828 DICompileUnit CU(S);
1829 Fn = CU.getFilename();
1830 Dir = CU.getDirectory();
1831 } else if (Scope.isFile()) {
1833 Fn = F.getFilename();
1834 Dir = F.getDirectory();
1835 } else if (Scope.isSubprogram()) {
1837 Fn = SP.getFilename();
1838 Dir = SP.getDirectory();
1839 } else if (Scope.isLexicalBlockFile()) {
1840 DILexicalBlockFile DBF(S);
1841 Fn = DBF.getFilename();
1842 Dir = DBF.getDirectory();
1843 } else if (Scope.isLexicalBlock()) {
1844 DILexicalBlock DB(S);
1845 Fn = DB.getFilename();
1846 Dir = DB.getDirectory();
1847 Discriminator = DB.getDiscriminator();
1849 llvm_unreachable("Unexpected scope info");
1851 Src = getOrCreateSourceID(
1852 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1854 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1858 //===----------------------------------------------------------------------===//
1860 //===----------------------------------------------------------------------===//
1862 // Compute the size and offset of a DIE. The offset is relative to start of the
1863 // CU. It returns the offset after laying out the DIE.
1864 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1865 // Get the children.
1866 const std::vector<DIE *> &Children = Die->getChildren();
1868 // Record the abbreviation.
1869 assignAbbrevNumber(Die->getAbbrev());
1871 // Get the abbreviation for this DIE.
1872 const DIEAbbrev &Abbrev = Die->getAbbrev();
1875 Die->setOffset(Offset);
1877 // Start the size with the size of abbreviation code.
1878 Offset += getULEB128Size(Die->getAbbrevNumber());
1880 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1881 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1883 // Size the DIE attribute values.
1884 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1885 // Size attribute value.
1886 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1888 // Size the DIE children if any.
1889 if (!Children.empty()) {
1890 assert(Abbrev.hasChildren() && "Children flag not set");
1892 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1893 Offset = computeSizeAndOffset(Children[j], Offset);
1895 // End of children marker.
1896 Offset += sizeof(int8_t);
1899 Die->setSize(Offset - Die->getOffset());
1903 // Compute the size and offset for each DIE.
1904 void DwarfFile::computeSizeAndOffsets() {
1905 // Offset from the first CU in the debug info section is 0 initially.
1906 unsigned SecOffset = 0;
1908 // Iterate over each compile unit and set the size and offsets for each
1909 // DIE within each compile unit. All offsets are CU relative.
1910 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1913 (*I)->setDebugInfoOffset(SecOffset);
1915 // CU-relative offset is reset to 0 here.
1916 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1917 (*I)->getHeaderSize(); // Unit-specific headers
1919 // EndOffset here is CU-relative, after laying out
1920 // all of the CU DIE.
1921 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1922 SecOffset += EndOffset;
1926 // Emit initial Dwarf sections with a label at the start of each one.
1927 void DwarfDebug::emitSectionLabels() {
1928 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1930 // Dwarf sections base addresses.
1931 DwarfInfoSectionSym =
1932 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1933 if (useSplitDwarf())
1934 DwarfInfoDWOSectionSym =
1935 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1936 DwarfAbbrevSectionSym =
1937 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1938 if (useSplitDwarf())
1939 DwarfAbbrevDWOSectionSym = emitSectionSym(
1940 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1941 if (GenerateARangeSection)
1942 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1944 DwarfLineSectionSym =
1945 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1946 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1947 if (GenerateGnuPubSections) {
1948 DwarfGnuPubNamesSectionSym =
1949 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1950 DwarfGnuPubTypesSectionSym =
1951 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1952 } else if (HasDwarfPubSections) {
1953 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1954 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1957 DwarfStrSectionSym =
1958 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1959 if (useSplitDwarf()) {
1960 DwarfStrDWOSectionSym =
1961 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1962 DwarfAddrSectionSym =
1963 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1965 DwarfDebugRangeSectionSym =
1966 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1968 DwarfDebugLocSectionSym =
1969 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1972 // Recursively emits a debug information entry.
1973 void DwarfDebug::emitDIE(DIE *Die) {
1974 // Get the abbreviation for this DIE.
1975 const DIEAbbrev &Abbrev = Die->getAbbrev();
1977 // Emit the code (index) for the abbreviation.
1978 if (Asm->isVerbose())
1979 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1980 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1981 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1982 dwarf::TagString(Abbrev.getTag()));
1983 Asm->EmitULEB128(Abbrev.getNumber());
1985 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1986 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1988 // Emit the DIE attribute values.
1989 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1990 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1991 dwarf::Form Form = AbbrevData[i].getForm();
1992 assert(Form && "Too many attributes for DIE (check abbreviation)");
1994 if (Asm->isVerbose()) {
1995 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1996 if (Attr == dwarf::DW_AT_accessibility)
1997 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1998 cast<DIEInteger>(Values[i])->getValue()));
2001 // Emit an attribute using the defined form.
2002 Values[i]->EmitValue(Asm, Form);
2005 // Emit the DIE children if any.
2006 if (Abbrev.hasChildren()) {
2007 const std::vector<DIE *> &Children = Die->getChildren();
2009 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2010 emitDIE(Children[j]);
2012 Asm->OutStreamer.AddComment("End Of Children Mark");
2017 // Emit the various dwarf units to the unit section USection with
2018 // the abbreviations going into ASection.
2019 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2020 const MCSymbol *ASectionSym) {
2021 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2023 DwarfUnit *TheU = *I;
2024 DIE *Die = TheU->getUnitDie();
2025 const MCSection *USection = TheU->getSection();
2026 Asm->OutStreamer.SwitchSection(USection);
2028 // Emit the compile units header.
2029 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2031 // Emit size of content not including length itself
2032 Asm->OutStreamer.AddComment("Length of Unit");
2033 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2035 TheU->emitHeader(ASection, ASectionSym);
2038 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2042 // Emit the debug info section.
2043 void DwarfDebug::emitDebugInfo() {
2044 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2046 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2047 DwarfAbbrevSectionSym);
2050 // Emit the abbreviation section.
2051 void DwarfDebug::emitAbbreviations() {
2052 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2054 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2057 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2058 // Check to see if it is worth the effort.
2059 if (!Abbreviations.empty()) {
2060 // Start the debug abbrev section.
2061 Asm->OutStreamer.SwitchSection(Section);
2063 // For each abbrevation.
2064 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2065 // Get abbreviation data
2066 const DIEAbbrev *Abbrev = Abbreviations[i];
2068 // Emit the abbrevations code (base 1 index.)
2069 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2071 // Emit the abbreviations data.
2075 // Mark end of abbreviations.
2076 Asm->EmitULEB128(0, "EOM(3)");
2080 // Emit the last address of the section and the end of the line matrix.
2081 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2082 // Define last address of section.
2083 Asm->OutStreamer.AddComment("Extended Op");
2086 Asm->OutStreamer.AddComment("Op size");
2087 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2088 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2089 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2091 Asm->OutStreamer.AddComment("Section end label");
2093 Asm->OutStreamer.EmitSymbolValue(
2094 Asm->GetTempSymbol("section_end", SectionEnd),
2095 Asm->getDataLayout().getPointerSize());
2097 // Mark end of matrix.
2098 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2104 // Emit visible names into a hashed accelerator table section.
2105 void DwarfDebug::emitAccelNames() {
2107 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2108 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2109 E = getUnits().end();
2111 DwarfUnit *TheU = *I;
2112 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2113 for (StringMap<std::vector<const DIE *> >::const_iterator
2117 StringRef Name = GI->getKey();
2118 const std::vector<const DIE *> &Entities = GI->second;
2119 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2120 DE = Entities.end();
2122 AT.AddName(Name, *DI);
2126 AT.FinalizeTable(Asm, "Names");
2127 Asm->OutStreamer.SwitchSection(
2128 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2129 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2130 Asm->OutStreamer.EmitLabel(SectionBegin);
2132 // Emit the full data.
2133 AT.Emit(Asm, SectionBegin, &InfoHolder);
2136 // Emit objective C classes and categories into a hashed accelerator table
2138 void DwarfDebug::emitAccelObjC() {
2140 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2141 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2142 E = getUnits().end();
2144 DwarfUnit *TheU = *I;
2145 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2146 for (StringMap<std::vector<const DIE *> >::const_iterator
2150 StringRef Name = GI->getKey();
2151 const std::vector<const DIE *> &Entities = GI->second;
2152 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2153 DE = Entities.end();
2155 AT.AddName(Name, *DI);
2159 AT.FinalizeTable(Asm, "ObjC");
2160 Asm->OutStreamer.SwitchSection(
2161 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2162 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2163 Asm->OutStreamer.EmitLabel(SectionBegin);
2165 // Emit the full data.
2166 AT.Emit(Asm, SectionBegin, &InfoHolder);
2169 // Emit namespace dies into a hashed accelerator table.
2170 void DwarfDebug::emitAccelNamespaces() {
2172 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2173 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2174 E = getUnits().end();
2176 DwarfUnit *TheU = *I;
2177 const StringMap<std::vector<const DIE *> > &Names =
2178 TheU->getAccelNamespace();
2179 for (StringMap<std::vector<const DIE *> >::const_iterator
2183 StringRef Name = GI->getKey();
2184 const std::vector<const DIE *> &Entities = GI->second;
2185 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2186 DE = Entities.end();
2188 AT.AddName(Name, *DI);
2192 AT.FinalizeTable(Asm, "namespac");
2193 Asm->OutStreamer.SwitchSection(
2194 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2195 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2196 Asm->OutStreamer.EmitLabel(SectionBegin);
2198 // Emit the full data.
2199 AT.Emit(Asm, SectionBegin, &InfoHolder);
2202 // Emit type dies into a hashed accelerator table.
2203 void DwarfDebug::emitAccelTypes() {
2204 std::vector<DwarfAccelTable::Atom> Atoms;
2206 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2208 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2210 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2211 DwarfAccelTable AT(Atoms);
2212 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2213 E = getUnits().end();
2215 DwarfUnit *TheU = *I;
2216 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2217 TheU->getAccelTypes();
2219 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2223 StringRef Name = GI->getKey();
2224 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2226 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2227 DI = Entities.begin(),
2228 DE = Entities.end();
2230 AT.AddName(Name, DI->first, DI->second);
2234 AT.FinalizeTable(Asm, "types");
2235 Asm->OutStreamer.SwitchSection(
2236 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2237 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2238 Asm->OutStreamer.EmitLabel(SectionBegin);
2240 // Emit the full data.
2241 AT.Emit(Asm, SectionBegin, &InfoHolder);
2244 // Public name handling.
2245 // The format for the various pubnames:
2247 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2248 // for the DIE that is named.
2250 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2251 // into the CU and the index value is computed according to the type of value
2252 // for the DIE that is named.
2254 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2255 // it's the offset within the debug_info/debug_types dwo section, however, the
2256 // reference in the pubname header doesn't change.
2258 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2259 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2261 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2263 // We could have a specification DIE that has our most of our knowledge,
2264 // look for that now.
2265 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2267 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2268 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2269 Linkage = dwarf::GIEL_EXTERNAL;
2270 } else if (Die->findAttribute(dwarf::DW_AT_external))
2271 Linkage = dwarf::GIEL_EXTERNAL;
2273 switch (Die->getTag()) {
2274 case dwarf::DW_TAG_class_type:
2275 case dwarf::DW_TAG_structure_type:
2276 case dwarf::DW_TAG_union_type:
2277 case dwarf::DW_TAG_enumeration_type:
2278 return dwarf::PubIndexEntryDescriptor(
2279 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2280 ? dwarf::GIEL_STATIC
2281 : dwarf::GIEL_EXTERNAL);
2282 case dwarf::DW_TAG_typedef:
2283 case dwarf::DW_TAG_base_type:
2284 case dwarf::DW_TAG_subrange_type:
2285 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2286 case dwarf::DW_TAG_namespace:
2287 return dwarf::GIEK_TYPE;
2288 case dwarf::DW_TAG_subprogram:
2289 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2290 case dwarf::DW_TAG_constant:
2291 case dwarf::DW_TAG_variable:
2292 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2293 case dwarf::DW_TAG_enumerator:
2294 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2295 dwarf::GIEL_STATIC);
2297 return dwarf::GIEK_NONE;
2301 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2303 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2304 const MCSection *PSec =
2305 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2306 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2308 for (const auto &NU : CUMap) {
2309 DwarfCompileUnit *TheU = NU.second;
2310 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2312 unsigned ID = TheU->getUniqueID();
2314 // Start the dwarf pubnames section.
2315 Asm->OutStreamer.SwitchSection(PSec);
2317 // Emit a label so we can reference the beginning of this pubname section.
2319 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2322 Asm->OutStreamer.AddComment("Length of Public Names Info");
2323 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2324 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2325 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2327 Asm->OutStreamer.EmitLabel(BeginLabel);
2329 Asm->OutStreamer.AddComment("DWARF Version");
2330 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2332 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2333 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2335 Asm->OutStreamer.AddComment("Compilation Unit Length");
2336 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2338 // Emit the pubnames for this compilation unit.
2339 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2340 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2343 const char *Name = GI->getKeyData();
2344 const DIE *Entity = GI->second;
2346 Asm->OutStreamer.AddComment("DIE offset");
2347 Asm->EmitInt32(Entity->getOffset());
2350 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2351 Asm->OutStreamer.AddComment(
2352 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2353 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2354 Asm->EmitInt8(Desc.toBits());
2357 Asm->OutStreamer.AddComment("External Name");
2358 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2361 Asm->OutStreamer.AddComment("End Mark");
2363 Asm->OutStreamer.EmitLabel(EndLabel);
2367 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2368 const MCSection *PSec =
2369 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2370 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2372 for (const auto &NU : CUMap) {
2373 DwarfCompileUnit *TheU = NU.second;
2374 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2376 unsigned ID = TheU->getUniqueID();
2378 // Start the dwarf pubtypes section.
2379 Asm->OutStreamer.SwitchSection(PSec);
2381 // Emit a label so we can reference the beginning of this pubtype section.
2383 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2386 Asm->OutStreamer.AddComment("Length of Public Types Info");
2387 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2388 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2389 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2391 Asm->OutStreamer.EmitLabel(BeginLabel);
2393 Asm->OutStreamer.AddComment("DWARF Version");
2394 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2396 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2397 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2399 Asm->OutStreamer.AddComment("Compilation Unit Length");
2400 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2402 // Emit the pubtypes.
2403 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2404 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2407 const char *Name = GI->getKeyData();
2408 const DIE *Entity = GI->second;
2410 Asm->OutStreamer.AddComment("DIE offset");
2411 Asm->EmitInt32(Entity->getOffset());
2414 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2415 Asm->OutStreamer.AddComment(
2416 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2417 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2418 Asm->EmitInt8(Desc.toBits());
2421 Asm->OutStreamer.AddComment("External Name");
2423 // Emit the name with a terminating null byte.
2424 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2427 Asm->OutStreamer.AddComment("End Mark");
2429 Asm->OutStreamer.EmitLabel(EndLabel);
2433 // Emit strings into a string section.
2434 void DwarfFile::emitStrings(const MCSection *StrSection,
2435 const MCSection *OffsetSection = NULL,
2436 const MCSymbol *StrSecSym = NULL) {
2438 if (StringPool.empty())
2441 // Start the dwarf str section.
2442 Asm->OutStreamer.SwitchSection(StrSection);
2444 // Get all of the string pool entries and put them in an array by their ID so
2445 // we can sort them.
2447 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2450 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2451 I = StringPool.begin(),
2452 E = StringPool.end();
2454 Entries.push_back(std::make_pair(I->second.second, &*I));
2456 array_pod_sort(Entries.begin(), Entries.end());
2458 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2459 // Emit a label for reference from debug information entries.
2460 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2462 // Emit the string itself with a terminating null byte.
2463 Asm->OutStreamer.EmitBytes(
2464 StringRef(Entries[i].second->getKeyData(),
2465 Entries[i].second->getKeyLength() + 1));
2468 // If we've got an offset section go ahead and emit that now as well.
2469 if (OffsetSection) {
2470 Asm->OutStreamer.SwitchSection(OffsetSection);
2471 unsigned offset = 0;
2472 unsigned size = 4; // FIXME: DWARF64 is 8.
2473 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2474 Asm->OutStreamer.EmitIntValue(offset, size);
2475 offset += Entries[i].second->getKeyLength() + 1;
2480 // Emit addresses into the section given.
2481 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2483 if (AddressPool.empty())
2486 // Start the dwarf addr section.
2487 Asm->OutStreamer.SwitchSection(AddrSection);
2489 // Order the address pool entries by ID
2490 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2492 for (AddrPool::iterator I = AddressPool.begin(), E = AddressPool.end();
2494 Entries[I->second.Number] =
2496 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I->first)
2497 : MCSymbolRefExpr::Create(I->first, Asm->OutContext);
2499 for (unsigned i = 0, e = Entries.size(); i != e; ++i)
2500 Asm->OutStreamer.EmitValue(Entries[i],
2501 Asm->getDataLayout().getPointerSize());
2504 // Emit visible names into a debug str section.
2505 void DwarfDebug::emitDebugStr() {
2506 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2507 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2510 // Emit locations into the debug loc section.
2511 void DwarfDebug::emitDebugLoc() {
2512 if (DotDebugLocEntries.empty())
2515 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2516 I = DotDebugLocEntries.begin(),
2517 E = DotDebugLocEntries.end();
2519 DotDebugLocEntry &Entry = *I;
2520 if (I + 1 != DotDebugLocEntries.end())
2524 // Start the dwarf loc section.
2525 Asm->OutStreamer.SwitchSection(
2526 Asm->getObjFileLowering().getDwarfLocSection());
2527 unsigned char Size = Asm->getDataLayout().getPointerSize();
2528 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2530 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2531 I = DotDebugLocEntries.begin(),
2532 E = DotDebugLocEntries.end();
2533 I != E; ++I, ++index) {
2534 const DotDebugLocEntry &Entry = *I;
2535 if (Entry.isMerged())
2537 if (Entry.isEmpty()) {
2538 Asm->OutStreamer.EmitIntValue(0, Size);
2539 Asm->OutStreamer.EmitIntValue(0, Size);
2540 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2542 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2543 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2544 DIVariable DV(Entry.getVariable());
2545 Asm->OutStreamer.AddComment("Loc expr size");
2546 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2547 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2548 Asm->EmitLabelDifference(end, begin, 2);
2549 Asm->OutStreamer.EmitLabel(begin);
2550 if (Entry.isInt()) {
2551 DIBasicType BTy(DV.getType());
2552 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2553 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2554 Asm->OutStreamer.AddComment("DW_OP_consts");
2555 Asm->EmitInt8(dwarf::DW_OP_consts);
2556 Asm->EmitSLEB128(Entry.getInt());
2558 Asm->OutStreamer.AddComment("DW_OP_constu");
2559 Asm->EmitInt8(dwarf::DW_OP_constu);
2560 Asm->EmitULEB128(Entry.getInt());
2562 } else if (Entry.isLocation()) {
2563 MachineLocation Loc = Entry.getLoc();
2564 if (!DV.hasComplexAddress())
2566 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2568 // Complex address entry.
2569 unsigned N = DV.getNumAddrElements();
2571 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2572 if (Loc.getOffset()) {
2574 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2575 Asm->OutStreamer.AddComment("DW_OP_deref");
2576 Asm->EmitInt8(dwarf::DW_OP_deref);
2577 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2578 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2579 Asm->EmitSLEB128(DV.getAddrElement(1));
2581 // If first address element is OpPlus then emit
2582 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2583 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2584 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2588 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2591 // Emit remaining complex address elements.
2592 for (; i < N; ++i) {
2593 uint64_t Element = DV.getAddrElement(i);
2594 if (Element == DIBuilder::OpPlus) {
2595 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2596 Asm->EmitULEB128(DV.getAddrElement(++i));
2597 } else if (Element == DIBuilder::OpDeref) {
2599 Asm->EmitInt8(dwarf::DW_OP_deref);
2601 llvm_unreachable("unknown Opcode found in complex address");
2605 // else ... ignore constant fp. There is not any good way to
2606 // to represent them here in dwarf.
2607 Asm->OutStreamer.EmitLabel(end);
2612 struct SymbolCUSorter {
2613 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2614 const MCStreamer &Streamer;
2616 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2617 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2618 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2620 // Symbols with no order assigned should be placed at the end.
2621 // (e.g. section end labels)
2623 IA = (unsigned)(-1);
2625 IB = (unsigned)(-1);
2630 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2631 return (A->getUniqueID() < B->getUniqueID());
2635 const MCSymbol *Start, *End;
2638 // Emit a debug aranges section, containing a CU lookup for any
2639 // address we can tie back to a CU.
2640 void DwarfDebug::emitDebugARanges() {
2641 // Start the dwarf aranges section.
2642 Asm->OutStreamer.SwitchSection(
2643 Asm->getObjFileLowering().getDwarfARangesSection());
2645 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2649 // Build a list of sections used.
2650 std::vector<const MCSection *> Sections;
2651 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2653 const MCSection *Section = it->first;
2654 Sections.push_back(Section);
2657 // Sort the sections into order.
2658 // This is only done to ensure consistent output order across different runs.
2659 std::sort(Sections.begin(), Sections.end(), SectionSort);
2661 // Build a set of address spans, sorted by CU.
2662 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2663 const MCSection *Section = Sections[SecIdx];
2664 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2665 if (List.size() < 2)
2668 // Sort the symbols by offset within the section.
2669 SymbolCUSorter sorter(Asm->OutStreamer);
2670 std::sort(List.begin(), List.end(), sorter);
2672 // If we have no section (e.g. common), just write out
2673 // individual spans for each symbol.
2674 if (Section == NULL) {
2675 for (size_t n = 0; n < List.size(); n++) {
2676 const SymbolCU &Cur = List[n];
2679 Span.Start = Cur.Sym;
2682 Spans[Cur.CU].push_back(Span);
2685 // Build spans between each label.
2686 const MCSymbol *StartSym = List[0].Sym;
2687 for (size_t n = 1; n < List.size(); n++) {
2688 const SymbolCU &Prev = List[n - 1];
2689 const SymbolCU &Cur = List[n];
2691 // Try and build the longest span we can within the same CU.
2692 if (Cur.CU != Prev.CU) {
2694 Span.Start = StartSym;
2696 Spans[Prev.CU].push_back(Span);
2703 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2705 // Build a list of CUs used.
2706 std::vector<DwarfCompileUnit *> CUs;
2707 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2708 DwarfCompileUnit *CU = it->first;
2712 // Sort the CU list (again, to ensure consistent output order).
2713 std::sort(CUs.begin(), CUs.end(), CUSort);
2715 // Emit an arange table for each CU we used.
2716 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2717 DwarfCompileUnit *CU = CUs[CUIdx];
2718 std::vector<ArangeSpan> &List = Spans[CU];
2720 // Emit size of content not including length itself.
2721 unsigned ContentSize =
2722 sizeof(int16_t) + // DWARF ARange version number
2723 sizeof(int32_t) + // Offset of CU in the .debug_info section
2724 sizeof(int8_t) + // Pointer Size (in bytes)
2725 sizeof(int8_t); // Segment Size (in bytes)
2727 unsigned TupleSize = PtrSize * 2;
2729 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2731 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2733 ContentSize += Padding;
2734 ContentSize += (List.size() + 1) * TupleSize;
2736 // For each compile unit, write the list of spans it covers.
2737 Asm->OutStreamer.AddComment("Length of ARange Set");
2738 Asm->EmitInt32(ContentSize);
2739 Asm->OutStreamer.AddComment("DWARF Arange version number");
2740 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2741 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2742 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2743 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2744 Asm->EmitInt8(PtrSize);
2745 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2748 Asm->OutStreamer.EmitFill(Padding, 0xff);
2750 for (unsigned n = 0; n < List.size(); n++) {
2751 const ArangeSpan &Span = List[n];
2752 Asm->EmitLabelReference(Span.Start, PtrSize);
2754 // Calculate the size as being from the span start to it's end.
2756 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2758 // For symbols without an end marker (e.g. common), we
2759 // write a single arange entry containing just that one symbol.
2760 uint64_t Size = SymSize[Span.Start];
2764 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2768 Asm->OutStreamer.AddComment("ARange terminator");
2769 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2770 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2774 // Emit visible names into a debug ranges section.
2775 void DwarfDebug::emitDebugRanges() {
2776 // Start the dwarf ranges section.
2777 Asm->OutStreamer.SwitchSection(
2778 Asm->getObjFileLowering().getDwarfRangesSection());
2780 // Size for our labels.
2781 unsigned char Size = Asm->getDataLayout().getPointerSize();
2783 // Grab the specific ranges for the compile units in the module.
2784 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2788 DwarfCompileUnit *TheCU = I->second;
2790 // Emit a symbol so we can find the beginning of our ranges.
2791 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2793 // Iterate over the misc ranges for the compile units in the module.
2794 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2795 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2796 E = RangeLists.end();
2798 const RangeSpanList &List = *I;
2800 // Emit our symbol so we can find the beginning of the range.
2801 Asm->OutStreamer.EmitLabel(List.getSym());
2803 for (SmallVectorImpl<RangeSpan>::const_iterator
2804 RI = List.getRanges().begin(),
2805 RE = List.getRanges().end();
2807 const RangeSpan &Range = *RI;
2808 const MCSymbol *Begin = Range.getStart();
2809 const MCSymbol *End = Range.getEnd();
2810 assert(Begin && "Range without a begin symbol?");
2811 assert(End && "Range without an end symbol?");
2812 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2813 Asm->OutStreamer.EmitSymbolValue(End, Size);
2816 // And terminate the list with two 0 values.
2817 Asm->OutStreamer.EmitIntValue(0, Size);
2818 Asm->OutStreamer.EmitIntValue(0, Size);
2821 // Now emit a range for the CU itself.
2822 if (useCURanges() && TheCU->getRanges().size()) {
2823 Asm->OutStreamer.EmitLabel(
2824 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2825 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2826 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2827 RangeSpan Range = Ranges[i];
2828 const MCSymbol *Begin = Range.getStart();
2829 const MCSymbol *End = Range.getEnd();
2830 assert(Begin && "Range without a begin symbol?");
2831 assert(End && "Range without an end symbol?");
2832 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2833 Asm->OutStreamer.EmitSymbolValue(End, Size);
2835 // And terminate the list with two 0 values.
2836 Asm->OutStreamer.EmitIntValue(0, Size);
2837 Asm->OutStreamer.EmitIntValue(0, Size);
2842 // DWARF5 Experimental Separate Dwarf emitters.
2844 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2846 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2847 U->getCUNode().getSplitDebugFilename());
2849 // Relocate to the beginning of the addr_base section, else 0 for the
2850 // beginning of the one for this compile unit.
2851 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2852 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2854 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2856 if (!CompilationDir.empty())
2857 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2859 addGnuPubAttributes(NewU, Die);
2861 SkeletonHolder.addUnit(NewU);
2864 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2865 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2866 // DW_AT_ranges_base, DW_AT_addr_base.
2867 // TODO: Implement DW_AT_ranges_base.
2868 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2870 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2871 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2872 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2873 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2874 DwarfInfoSectionSym);
2876 NewCU->initStmtList(DwarfLineSectionSym);
2878 initSkeletonUnit(CU, Die, NewCU);
2883 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2885 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2886 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2887 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2889 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2890 DwarfTypeUnit *NewTU =
2891 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2892 NewTU->setTypeSignature(TU->getTypeSignature());
2893 NewTU->setType(NULL);
2895 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2896 CU.applyStmtList(*Die);
2898 initSkeletonUnit(TU, Die, NewTU);
2902 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2903 // compile units that would normally be in debug_info.
2904 void DwarfDebug::emitDebugInfoDWO() {
2905 assert(useSplitDwarf() && "No split dwarf debug info?");
2906 InfoHolder.emitUnits(this,
2907 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2908 DwarfAbbrevDWOSectionSym);
2911 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2912 // abbreviations for the .debug_info.dwo section.
2913 void DwarfDebug::emitDebugAbbrevDWO() {
2914 assert(useSplitDwarf() && "No split dwarf?");
2915 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2918 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2919 // string section and is identical in format to traditional .debug_str
2921 void DwarfDebug::emitDebugStrDWO() {
2922 assert(useSplitDwarf() && "No split dwarf?");
2923 const MCSection *OffSec =
2924 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2925 const MCSymbol *StrSym = DwarfStrSectionSym;
2926 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2930 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2931 StringRef Identifier, DIE *RefDie,
2932 DICompositeType CTy) {
2933 // Flag the type unit reference as a declaration so that if it contains
2934 // members (implicit special members, static data member definitions, member
2935 // declarations for definitions in this CU, etc) consumers don't get confused
2936 // and think this is a full definition.
2937 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2939 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2941 CU.addDIETypeSignature(RefDie, *TU);
2945 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2946 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2947 UnitDie, CU, Asm, this, &InfoHolder);
2949 InfoHolder.addUnit(NewTU);
2951 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2955 Hash.update(Identifier);
2956 // ... take the least significant 8 bytes and return those. Our MD5
2957 // implementation always returns its results in little endian, swap bytes
2959 MD5::MD5Result Result;
2961 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2962 NewTU->setTypeSignature(Signature);
2963 if (useSplitDwarf())
2964 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2966 CU.applyStmtList(*UnitDie);
2968 NewTU->setType(NewTU->createTypeDIE(CTy));
2972 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2973 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2975 CU.addDIETypeSignature(RefDie, *NewTU);