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/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
61 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
62 cl::desc("Add the CU hash as the dwo_id."),
66 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
67 cl::desc("Generate GNU-style pubnames and pubtypes"),
70 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
72 cl::desc("Generate dwarf aranges"),
76 enum DefaultOnOff { Default, Enable, Disable };
79 static cl::opt<DefaultOnOff>
80 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
81 cl::desc("Output prototype dwarf accelerator tables."),
82 cl::values(clEnumVal(Default, "Default for platform"),
83 clEnumVal(Enable, "Enabled"),
84 clEnumVal(Disable, "Disabled"), clEnumValEnd),
87 static cl::opt<DefaultOnOff>
88 SplitDwarf("split-dwarf", cl::Hidden,
89 cl::desc("Output DWARF5 split debug info."),
90 cl::values(clEnumVal(Default, "Default for platform"),
91 clEnumVal(Enable, "Enabled"),
92 clEnumVal(Disable, "Disabled"), clEnumValEnd),
95 static cl::opt<DefaultOnOff>
96 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
97 cl::desc("Generate DWARF pubnames and pubtypes sections"),
98 cl::values(clEnumVal(Default, "Default for platform"),
99 clEnumVal(Enable, "Enabled"),
100 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 static cl::opt<unsigned>
104 DwarfVersionNumber("dwarf-version", cl::Hidden,
105 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
108 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
109 cl::desc("Generate DW_AT_ranges for compile units"),
112 static const char *const DWARFGroupName = "DWARF Emission";
113 static const char *const DbgTimerName = "DWARF Debug Writer";
115 //===----------------------------------------------------------------------===//
119 /// resolve - Look in the DwarfDebug map for the MDNode that
120 /// corresponds to the reference.
121 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
122 return DD->resolve(Ref);
125 DIType DbgVariable::getType() const {
126 DIType Ty = Var.getType();
127 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
128 // addresses instead.
129 if (Var.isBlockByrefVariable()) {
130 /* Byref variables, in Blocks, are declared by the programmer as
131 "SomeType VarName;", but the compiler creates a
132 __Block_byref_x_VarName struct, and gives the variable VarName
133 either the struct, or a pointer to the struct, as its type. This
134 is necessary for various behind-the-scenes things the compiler
135 needs to do with by-reference variables in blocks.
137 However, as far as the original *programmer* is concerned, the
138 variable should still have type 'SomeType', as originally declared.
140 The following function dives into the __Block_byref_x_VarName
141 struct to find the original type of the variable. This will be
142 passed back to the code generating the type for the Debug
143 Information Entry for the variable 'VarName'. 'VarName' will then
144 have the original type 'SomeType' in its debug information.
146 The original type 'SomeType' will be the type of the field named
147 'VarName' inside the __Block_byref_x_VarName struct.
149 NOTE: In order for this to not completely fail on the debugger
150 side, the Debug Information Entry for the variable VarName needs to
151 have a DW_AT_location that tells the debugger how to unwind through
152 the pointers and __Block_byref_x_VarName struct to find the actual
153 value of the variable. The function addBlockByrefType does this. */
155 uint16_t tag = Ty.getTag();
157 if (tag == dwarf::DW_TAG_pointer_type)
158 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
160 DIArray Elements = DICompositeType(subType).getTypeArray();
161 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
162 DIDerivedType DT(Elements.getElement(i));
163 if (getName() == DT.getName())
164 return (resolve(DT.getTypeDerivedFrom()));
170 } // end llvm namespace
172 /// Return Dwarf Version by checking module flags.
173 static unsigned getDwarfVersionFromModule(const Module *M) {
174 Value *Val = M->getModuleFlag("Dwarf Version");
176 return dwarf::DWARF_VERSION;
177 return cast<ConstantInt>(Val)->getZExtValue();
180 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
181 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
182 PrevLabel(NULL), GlobalRangeCount(0),
183 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
184 UsedNonDefaultText(false),
185 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
187 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
188 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
189 DwarfAddrSectionSym = 0;
190 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
191 FunctionBeginSym = FunctionEndSym = 0;
195 // Turn on accelerator tables for Darwin by default, pubnames by
196 // default for non-Darwin, and handle split dwarf.
197 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
199 if (DwarfAccelTables == Default)
200 HasDwarfAccelTables = IsDarwin;
202 HasDwarfAccelTables = DwarfAccelTables == Enable;
204 if (SplitDwarf == Default)
205 HasSplitDwarf = false;
207 HasSplitDwarf = SplitDwarf == Enable;
209 if (DwarfPubSections == Default)
210 HasDwarfPubSections = !IsDarwin;
212 HasDwarfPubSections = DwarfPubSections == Enable;
214 DwarfVersion = DwarfVersionNumber
216 : getDwarfVersionFromModule(MMI->getModule());
219 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
224 // Switch to the specified MCSection and emit an assembler
225 // temporary label to it if SymbolStem is specified.
226 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
227 const char *SymbolStem = 0) {
228 Asm->OutStreamer.SwitchSection(Section);
232 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
233 Asm->OutStreamer.EmitLabel(TmpSym);
237 DwarfFile::~DwarfFile() {
238 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
243 MCSymbol *DwarfFile::getStringPoolSym() {
244 return Asm->GetTempSymbol(StringPref);
247 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
248 std::pair<MCSymbol *, unsigned> &Entry =
249 StringPool.GetOrCreateValue(Str).getValue();
253 Entry.second = NextStringPoolNumber++;
254 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
257 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
258 std::pair<MCSymbol *, unsigned> &Entry =
259 StringPool.GetOrCreateValue(Str).getValue();
263 Entry.second = NextStringPoolNumber++;
264 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
268 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
269 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
272 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
273 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
274 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
276 ++NextAddrPoolNumber;
277 return P.first->second;
280 // Define a unique number for the abbreviation.
282 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
283 // Check the set for priors.
284 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
286 // If it's newly added.
287 if (InSet == &Abbrev) {
288 // Add to abbreviation list.
289 Abbreviations.push_back(&Abbrev);
291 // Assign the vector position + 1 as its number.
292 Abbrev.setNumber(Abbreviations.size());
294 // Assign existing abbreviation number.
295 Abbrev.setNumber(InSet->getNumber());
299 static bool isObjCClass(StringRef Name) {
300 return Name.startswith("+") || Name.startswith("-");
303 static bool hasObjCCategory(StringRef Name) {
304 if (!isObjCClass(Name))
307 return Name.find(") ") != StringRef::npos;
310 static void getObjCClassCategory(StringRef In, StringRef &Class,
311 StringRef &Category) {
312 if (!hasObjCCategory(In)) {
313 Class = In.slice(In.find('[') + 1, In.find(' '));
318 Class = In.slice(In.find('[') + 1, In.find('('));
319 Category = In.slice(In.find('[') + 1, In.find(' '));
323 static StringRef getObjCMethodName(StringRef In) {
324 return In.slice(In.find(' ') + 1, In.find(']'));
327 // Helper for sorting sections into a stable output order.
328 static bool SectionSort(const MCSection *A, const MCSection *B) {
329 std::string LA = (A ? A->getLabelBeginName() : "");
330 std::string LB = (B ? B->getLabelBeginName() : "");
334 // Add the various names to the Dwarf accelerator table names.
335 // TODO: Determine whether or not we should add names for programs
336 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
337 // is only slightly different than the lookup of non-standard ObjC names.
338 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
339 if (!SP.isDefinition())
341 TheU->addAccelName(SP.getName(), Die);
343 // If the linkage name is different than the name, go ahead and output
344 // that as well into the name table.
345 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
346 TheU->addAccelName(SP.getLinkageName(), Die);
348 // If this is an Objective-C selector name add it to the ObjC accelerator
350 if (isObjCClass(SP.getName())) {
351 StringRef Class, Category;
352 getObjCClassCategory(SP.getName(), Class, Category);
353 TheU->addAccelObjC(Class, Die);
355 TheU->addAccelObjC(Category, Die);
356 // Also add the base method name to the name table.
357 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
361 /// isSubprogramContext - Return true if Context is either a subprogram
362 /// or another context nested inside a subprogram.
363 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
366 DIDescriptor D(Context);
367 if (D.isSubprogram())
370 return isSubprogramContext(resolve(DIType(Context).getContext()));
374 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
375 // and DW_AT_high_pc attributes. If there are global variables in this
376 // scope then create and insert DIEs for these variables.
377 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
379 DIE *SPDie = SPCU->getDIE(SP);
381 assert(SPDie && "Unable to find subprogram DIE!");
383 // If we're updating an abstract DIE, then we will be adding the children and
384 // object pointer later on. But what we don't want to do is process the
385 // concrete DIE twice.
386 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
387 // Pick up abstract subprogram DIE.
389 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
390 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
392 DISubprogram SPDecl = SP.getFunctionDeclaration();
393 if (!SPDecl.isSubprogram()) {
394 // There is not any need to generate specification DIE for a function
395 // defined at compile unit level. If a function is defined inside another
396 // function then gdb prefers the definition at top level and but does not
397 // expect specification DIE in parent function. So avoid creating
398 // specification DIE for a function defined inside a function.
399 DIScope SPContext = resolve(SP.getContext());
400 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
401 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
402 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
405 DICompositeType SPTy = SP.getType();
406 DIArray Args = SPTy.getTypeArray();
407 uint16_t SPTag = SPTy.getTag();
408 if (SPTag == dwarf::DW_TAG_subroutine_type)
409 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
411 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
412 DIType ATy(Args.getElement(i));
413 SPCU->addType(Arg, ATy);
414 if (ATy.isArtificial())
415 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
416 if (ATy.isObjectPointer())
417 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
419 DIE *SPDeclDie = SPDie;
420 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
421 *SPCU->getUnitDie());
422 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
427 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
428 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
430 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
431 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
432 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
434 // Add name to the name table, we do this here because we're guaranteed
435 // to have concrete versions of our DW_TAG_subprogram nodes.
436 addSubprogramNames(SPCU, SP, SPDie);
441 /// Check whether we should create a DIE for the given Scope, return true
442 /// if we don't create a DIE (the corresponding DIE is null).
443 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
444 if (Scope->isAbstractScope())
447 // We don't create a DIE if there is no Range.
448 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
452 if (Ranges.size() > 1)
455 // We don't create a DIE if we have a single Range and the end label
457 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
458 MCSymbol *End = getLabelAfterInsn(RI->second);
462 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
463 dwarf::Attribute A, const MCSymbol *L,
464 const MCSymbol *Sec) {
465 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
466 U->addSectionLabel(D, A, L);
468 U->addSectionDelta(D, A, L, Sec);
471 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
472 const SmallVectorImpl<InsnRange> &Range) {
473 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
474 // emitting it appropriately.
475 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
476 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
477 DwarfDebugRangeSectionSym);
479 RangeSpanList List(RangeSym);
480 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
483 RangeSpan Span(getLabelBeforeInsn(RI->first),
484 getLabelAfterInsn(RI->second));
485 List.addRange(llvm_move(Span));
488 // Add the range list to the set of ranges to be emitted.
489 TheCU->addRangeList(llvm_move(List));
492 // Construct new DW_TAG_lexical_block for this scope and attach
493 // DW_AT_low_pc/DW_AT_high_pc labels.
494 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
495 LexicalScope *Scope) {
496 if (isLexicalScopeDIENull(Scope))
499 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
500 if (Scope->isAbstractScope())
503 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
505 // If we have multiple ranges, emit them into the range section.
506 if (ScopeRanges.size() > 1) {
507 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
511 // Construct the address range for this DIE.
512 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
513 MCSymbol *Start = getLabelBeforeInsn(RI->first);
514 MCSymbol *End = getLabelAfterInsn(RI->second);
515 assert(End && "End label should not be null!");
517 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
518 assert(End->isDefined() && "Invalid end label for an inlined scope!");
520 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
521 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
526 // This scope represents inlined body of a function. Construct DIE to
527 // represent this concrete inlined copy of the function.
528 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
529 LexicalScope *Scope) {
530 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
531 assert(!ScopeRanges.empty() &&
532 "LexicalScope does not have instruction markers!");
534 if (!Scope->getScopeNode())
536 DIScope DS(Scope->getScopeNode());
537 DISubprogram InlinedSP = getDISubprogram(DS);
538 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
540 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
544 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
545 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
547 // If we have multiple ranges, emit them into the range section.
548 if (ScopeRanges.size() > 1)
549 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
551 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
552 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
553 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
555 if (StartLabel == 0 || EndLabel == 0)
556 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
558 assert(StartLabel->isDefined() &&
559 "Invalid starting label for an inlined scope!");
560 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
562 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
563 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
566 InlinedSubprogramDIEs.insert(OriginDIE);
568 // Add the call site information to the DIE.
569 DILocation DL(Scope->getInlinedAt());
570 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
571 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
572 TheCU->getUniqueID()));
573 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
575 // Add name to the name table, we do this here because we're guaranteed
576 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
577 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
582 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
584 SmallVectorImpl<DIE *> &Children) {
585 DIE *ObjectPointer = NULL;
587 // Collect arguments for current function.
588 if (LScopes.isCurrentFunctionScope(Scope))
589 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
590 if (DbgVariable *ArgDV = CurrentFnArguments[i])
592 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
593 Children.push_back(Arg);
594 if (ArgDV->isObjectPointer())
598 // Collect lexical scope children first.
599 const SmallVectorImpl<DbgVariable *> &Variables =
600 ScopeVariables.lookup(Scope);
601 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
602 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
603 Scope->isAbstractScope())) {
604 Children.push_back(Variable);
605 if (Variables[i]->isObjectPointer())
606 ObjectPointer = Variable;
608 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
609 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
610 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
611 Children.push_back(Nested);
612 return ObjectPointer;
615 // Construct a DIE for this scope.
616 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
617 LexicalScope *Scope) {
618 if (!Scope || !Scope->getScopeNode())
621 DIScope DS(Scope->getScopeNode());
623 SmallVector<DIE *, 8> Children;
624 DIE *ObjectPointer = NULL;
625 bool ChildrenCreated = false;
627 // We try to create the scope DIE first, then the children DIEs. This will
628 // avoid creating un-used children then removing them later when we find out
629 // the scope DIE is null.
630 DIE *ScopeDIE = NULL;
631 if (Scope->getInlinedAt())
632 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
633 else if (DS.isSubprogram()) {
634 ProcessedSPNodes.insert(DS);
635 if (Scope->isAbstractScope()) {
636 ScopeDIE = TheCU->getDIE(DS);
637 // Note down abstract DIE.
639 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
641 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
643 // Early exit when we know the scope DIE is going to be null.
644 if (isLexicalScopeDIENull(Scope))
647 // We create children here when we know the scope DIE is not going to be
648 // null and the children will be added to the scope DIE.
649 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
650 ChildrenCreated = true;
652 // There is no need to emit empty lexical block DIE.
653 std::pair<ImportedEntityMap::const_iterator,
654 ImportedEntityMap::const_iterator> Range =
656 ScopesWithImportedEntities.begin(),
657 ScopesWithImportedEntities.end(),
658 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
660 if (Children.empty() && Range.first == Range.second)
662 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
663 assert(ScopeDIE && "Scope DIE should not be null.");
664 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
666 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
670 assert(Children.empty() &&
671 "We create children only when the scope DIE is not null.");
674 if (!ChildrenCreated)
675 // We create children when the scope DIE is not null.
676 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
679 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
682 ScopeDIE->addChild(*I);
684 if (DS.isSubprogram() && ObjectPointer != NULL)
685 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
690 // Look up the source id with the given directory and source file names.
691 // If none currently exists, create a new id and insert it in the
692 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
694 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
696 // If we print assembly, we can't separate .file entries according to
697 // compile units. Thus all files will belong to the default compile unit.
699 // FIXME: add a better feature test than hasRawTextSupport. Even better,
700 // extend .file to support this.
701 if (Asm->OutStreamer.hasRawTextSupport())
704 // If FE did not provide a file name, then assume stdin.
705 if (FileName.empty())
706 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
708 // TODO: this might not belong here. See if we can factor this better.
709 if (DirName == CompilationDir)
712 // FileIDCUMap stores the current ID for the given compile unit.
713 unsigned SrcId = FileIDCUMap[CUID] + 1;
715 // We look up the CUID/file/dir by concatenating them with a zero byte.
716 SmallString<128> NamePair;
717 NamePair += utostr(CUID);
720 NamePair += '\0'; // Zero bytes are not allowed in paths.
721 NamePair += FileName;
723 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
724 if (Ent.getValue() != SrcId)
725 return Ent.getValue();
727 FileIDCUMap[CUID] = SrcId;
728 // Print out a .file directive to specify files for .loc directives.
729 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
734 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
735 if (!GenerateGnuPubSections)
738 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
739 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
740 DwarfGnuPubNamesSectionSym);
742 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
743 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
744 DwarfGnuPubTypesSectionSym);
747 // Create new DwarfCompileUnit for the given metadata node with tag
748 // DW_TAG_compile_unit.
749 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
750 StringRef FN = DIUnit.getFilename();
751 CompilationDir = DIUnit.getDirectory();
753 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
754 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
755 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
756 InfoHolder.addUnit(NewCU);
758 FileIDCUMap[NewCU->getUniqueID()] = 0;
760 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
761 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
762 DIUnit.getLanguage());
763 NewCU->addString(Die, dwarf::DW_AT_name, FN);
766 if (!useSplitDwarf()) {
767 NewCU->initStmtList(DwarfLineSectionSym);
769 // If we're using split dwarf the compilation dir is going to be in the
770 // skeleton CU and so we don't need to duplicate it here.
771 if (!CompilationDir.empty())
772 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
774 addGnuPubAttributes(NewCU, Die);
777 if (DIUnit.isOptimized())
778 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
780 StringRef Flags = DIUnit.getFlags();
782 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
784 if (unsigned RVer = DIUnit.getRunTimeVersion())
785 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
786 dwarf::DW_FORM_data1, RVer);
791 if (useSplitDwarf()) {
792 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
793 DwarfInfoDWOSectionSym);
794 NewCU->setSkeleton(constructSkeletonCU(NewCU));
796 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
797 DwarfInfoSectionSym);
799 CUMap.insert(std::make_pair(DIUnit, NewCU));
800 CUDieMap.insert(std::make_pair(Die, NewCU));
804 // Construct subprogram DIE.
805 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
807 // FIXME: We should only call this routine once, however, during LTO if a
808 // program is defined in multiple CUs we could end up calling it out of
809 // beginModule as we walk the CUs.
811 DwarfCompileUnit *&CURef = SPMap[N];
817 if (!SP.isDefinition())
818 // This is a method declaration which will be handled while constructing
822 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
824 // Expose as a global name.
825 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
828 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
830 DIImportedEntity Module(N);
831 assert(Module.Verify());
832 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
833 constructImportedEntityDIE(TheCU, Module, D);
836 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
837 const MDNode *N, DIE *Context) {
838 DIImportedEntity Module(N);
839 assert(Module.Verify());
840 return constructImportedEntityDIE(TheCU, Module, Context);
843 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
844 const DIImportedEntity &Module,
846 assert(Module.Verify() &&
847 "Use one of the MDNode * overloads to handle invalid metadata");
848 assert(Context && "Should always have a context for an imported_module");
849 DIE *IMDie = new DIE(Module.getTag());
850 TheCU->insertDIE(Module, IMDie);
852 DIDescriptor Entity = Module.getEntity();
853 if (Entity.isNameSpace())
854 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
855 else if (Entity.isSubprogram())
856 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
857 else if (Entity.isType())
858 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
860 EntityDie = TheCU->getDIE(Entity);
861 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
862 Module.getContext().getDirectory(),
863 TheCU->getUniqueID());
864 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
865 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
866 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
867 StringRef Name = Module.getName();
869 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
870 Context->addChild(IMDie);
873 // Emit all Dwarf sections that should come prior to the content. Create
874 // global DIEs and emit initial debug info sections. This is invoked by
875 // the target AsmPrinter.
876 void DwarfDebug::beginModule() {
877 if (DisableDebugInfoPrinting)
880 const Module *M = MMI->getModule();
882 // If module has named metadata anchors then use them, otherwise scan the
883 // module using debug info finder to collect debug info.
884 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
887 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
889 // Emit initial sections so we can reference labels later.
892 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
893 DICompileUnit CUNode(CU_Nodes->getOperand(i));
894 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
895 DIArray ImportedEntities = CUNode.getImportedEntities();
896 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
897 ScopesWithImportedEntities.push_back(std::make_pair(
898 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
899 ImportedEntities.getElement(i)));
900 std::sort(ScopesWithImportedEntities.begin(),
901 ScopesWithImportedEntities.end(), less_first());
902 DIArray GVs = CUNode.getGlobalVariables();
903 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
904 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
905 DIArray SPs = CUNode.getSubprograms();
906 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
907 constructSubprogramDIE(CU, SPs.getElement(i));
908 DIArray EnumTypes = CUNode.getEnumTypes();
909 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
910 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
911 DIArray RetainedTypes = CUNode.getRetainedTypes();
912 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
913 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
914 // Emit imported_modules last so that the relevant context is already
916 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
917 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
920 // Tell MMI that we have debug info.
921 MMI->setDebugInfoAvailability(true);
923 // Prime section data.
924 SectionMap[Asm->getObjFileLowering().getTextSection()];
927 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
928 void DwarfDebug::computeInlinedDIEs() {
929 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
930 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
931 AE = InlinedSubprogramDIEs.end();
934 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
936 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
937 AE = AbstractSPDies.end();
939 DIE *ISP = AI->second;
940 if (InlinedSubprogramDIEs.count(ISP))
942 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
946 // Collect info for variables that were optimized out.
947 void DwarfDebug::collectDeadVariables() {
948 const Module *M = MMI->getModule();
950 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
951 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
952 DICompileUnit TheCU(CU_Nodes->getOperand(i));
953 DIArray Subprograms = TheCU.getSubprograms();
954 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
955 DISubprogram SP(Subprograms.getElement(i));
956 if (ProcessedSPNodes.count(SP) != 0)
958 if (!SP.isSubprogram())
960 if (!SP.isDefinition())
962 DIArray Variables = SP.getVariables();
963 if (Variables.getNumElements() == 0)
966 // Construct subprogram DIE and add variables DIEs.
967 DwarfCompileUnit *SPCU =
968 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
969 assert(SPCU && "Unable to find Compile Unit!");
970 // FIXME: See the comment in constructSubprogramDIE about duplicate
972 constructSubprogramDIE(SPCU, SP);
973 DIE *SPDIE = SPCU->getDIE(SP);
974 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
975 DIVariable DV(Variables.getElement(vi));
976 if (!DV.isVariable())
978 DbgVariable NewVar(DV, NULL, this);
979 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
980 SPDIE->addChild(VariableDIE);
987 void DwarfDebug::finalizeModuleInfo() {
988 // Collect info for variables that were optimized out.
989 collectDeadVariables();
991 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
992 computeInlinedDIEs();
994 // Handle anything that needs to be done on a per-unit basis after
995 // all other generation.
996 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
997 E = getUnits().end();
999 DwarfUnit *TheU = *I;
1000 // Emit DW_AT_containing_type attribute to connect types with their
1001 // vtable holding type.
1002 TheU->constructContainingTypeDIEs();
1004 // Add CU specific attributes if we need to add any.
1005 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1006 // If we're splitting the dwarf out now that we've got the entire
1007 // CU then add the dwo id to it.
1008 DwarfCompileUnit *SkCU =
1009 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1010 if (useSplitDwarf()) {
1011 // This should be a unique identifier when we want to build .dwp files.
1013 if (GenerateCUHash) {
1015 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1017 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1018 dwarf::DW_FORM_data8, ID);
1019 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1020 dwarf::DW_FORM_data8, ID);
1023 // If we have code split among multiple sections or we've requested
1024 // it then emit a DW_AT_ranges attribute on the unit that will remain
1025 // in the .o file, otherwise add a DW_AT_low_pc.
1026 // FIXME: Also add a high pc if we can.
1027 // FIXME: We should use ranges if we have multiple compile units or
1028 // allow reordering of code ala .subsections_via_symbols in mach-o.
1029 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1030 if (useCURanges() && TheU->getRanges().size()) {
1031 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1032 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1033 DwarfDebugRangeSectionSym);
1035 // A DW_AT_low_pc attribute may also be specified in combination with
1036 // DW_AT_ranges to specify the default base address for use in location
1037 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1038 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1041 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1046 // Compute DIE offsets and sizes.
1047 InfoHolder.computeSizeAndOffsets();
1048 if (useSplitDwarf())
1049 SkeletonHolder.computeSizeAndOffsets();
1052 void DwarfDebug::endSections() {
1053 // Filter labels by section.
1054 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1055 const SymbolCU &SCU = ArangeLabels[n];
1056 if (SCU.Sym->isInSection()) {
1057 // Make a note of this symbol and it's section.
1058 const MCSection *Section = &SCU.Sym->getSection();
1059 if (!Section->getKind().isMetadata())
1060 SectionMap[Section].push_back(SCU);
1062 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1063 // appear in the output. This sucks as we rely on sections to build
1064 // arange spans. We can do it without, but it's icky.
1065 SectionMap[NULL].push_back(SCU);
1069 // Build a list of sections used.
1070 std::vector<const MCSection *> Sections;
1071 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1073 const MCSection *Section = it->first;
1074 Sections.push_back(Section);
1077 // Sort the sections into order.
1078 // This is only done to ensure consistent output order across different runs.
1079 std::sort(Sections.begin(), Sections.end(), SectionSort);
1081 // Add terminating symbols for each section.
1082 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1083 const MCSection *Section = Sections[ID];
1084 MCSymbol *Sym = NULL;
1087 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1088 // if we know the section name up-front. For user-created sections, the
1089 // resulting label may not be valid to use as a label. (section names can
1090 // use a greater set of characters on some systems)
1091 Sym = Asm->GetTempSymbol("debug_end", ID);
1092 Asm->OutStreamer.SwitchSection(Section);
1093 Asm->OutStreamer.EmitLabel(Sym);
1096 // Insert a final terminator.
1097 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1100 // For now only turn on CU ranges if we've explicitly asked for it,
1101 // we have -ffunction-sections enabled, we've emitted a function
1102 // into a unique section, or we're using LTO. If we're using LTO then
1103 // we can't know that any particular function in the module is correlated
1104 // to a particular CU and so we need to be conservative. At this point all
1105 // sections should be finalized except for dwarf sections.
1106 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1107 TargetMachine::getFunctionSections();
1110 // Emit all Dwarf sections that should come after the content.
1111 void DwarfDebug::endModule() {
1118 // End any existing sections.
1119 // TODO: Does this need to happen?
1122 // Finalize the debug info for the module.
1123 finalizeModuleInfo();
1127 // Emit all the DIEs into a debug info section.
1130 // Corresponding abbreviations into a abbrev section.
1131 emitAbbreviations();
1133 // Emit info into a debug loc section.
1136 // Emit info into a debug aranges section.
1137 if (GenerateARangeSection)
1140 // Emit info into a debug ranges section.
1143 if (useSplitDwarf()) {
1146 emitDebugAbbrevDWO();
1147 // Emit DWO addresses.
1148 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1151 // Emit info into the dwarf accelerator table sections.
1152 if (useDwarfAccelTables()) {
1155 emitAccelNamespaces();
1159 // Emit the pubnames and pubtypes sections if requested.
1160 if (HasDwarfPubSections) {
1161 emitDebugPubNames(GenerateGnuPubSections);
1162 emitDebugPubTypes(GenerateGnuPubSections);
1168 // Reset these for the next Module if we have one.
1172 // Find abstract variable, if any, associated with Var.
1173 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1174 DebugLoc ScopeLoc) {
1175 LLVMContext &Ctx = DV->getContext();
1176 // More then one inlined variable corresponds to one abstract variable.
1177 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1178 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1180 return AbsDbgVariable;
1182 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1186 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1187 addScopeVariable(Scope, AbsDbgVariable);
1188 AbstractVariables[Var] = AbsDbgVariable;
1189 return AbsDbgVariable;
1192 // If Var is a current function argument then add it to CurrentFnArguments list.
1193 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1194 if (!LScopes.isCurrentFunctionScope(Scope))
1196 DIVariable DV = Var->getVariable();
1197 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1199 unsigned ArgNo = DV.getArgNumber();
1203 size_t Size = CurrentFnArguments.size();
1205 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1206 // llvm::Function argument size is not good indicator of how many
1207 // arguments does the function have at source level.
1209 CurrentFnArguments.resize(ArgNo * 2);
1210 CurrentFnArguments[ArgNo - 1] = Var;
1214 // Collect variable information from side table maintained by MMI.
1215 void DwarfDebug::collectVariableInfoFromMMITable(
1216 SmallPtrSet<const MDNode *, 16> &Processed) {
1217 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1218 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1221 const MDNode *Var = VI->first;
1224 Processed.insert(Var);
1226 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1228 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1230 // If variable scope is not found then skip this variable.
1234 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1235 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1236 RegVar->setFrameIndex(VP.first);
1237 if (!addCurrentFnArgument(RegVar, Scope))
1238 addScopeVariable(Scope, RegVar);
1240 AbsDbgVariable->setFrameIndex(VP.first);
1244 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1246 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1247 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1248 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1249 MI->getOperand(0).getReg() &&
1250 (MI->getOperand(1).isImm() ||
1251 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1254 // Get .debug_loc entry for the instruction range starting at MI.
1255 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1256 const MCSymbol *FLabel,
1257 const MCSymbol *SLabel,
1258 const MachineInstr *MI) {
1259 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1261 assert(MI->getNumOperands() == 3);
1262 if (MI->getOperand(0).isReg()) {
1263 MachineLocation MLoc;
1264 // If the second operand is an immediate, this is a
1265 // register-indirect address.
1266 if (!MI->getOperand(1).isImm())
1267 MLoc.set(MI->getOperand(0).getReg());
1269 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1270 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1272 if (MI->getOperand(0).isImm())
1273 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1274 if (MI->getOperand(0).isFPImm())
1275 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1276 if (MI->getOperand(0).isCImm())
1277 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1279 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1282 // Find variables for each lexical scope.
1284 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1286 // Grab the variable info that was squirreled away in the MMI side-table.
1287 collectVariableInfoFromMMITable(Processed);
1289 for (SmallVectorImpl<const MDNode *>::const_iterator
1290 UVI = UserVariables.begin(),
1291 UVE = UserVariables.end();
1292 UVI != UVE; ++UVI) {
1293 const MDNode *Var = *UVI;
1294 if (Processed.count(Var))
1297 // History contains relevant DBG_VALUE instructions for Var and instructions
1299 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1300 if (History.empty())
1302 const MachineInstr *MInsn = History.front();
1305 LexicalScope *Scope = NULL;
1306 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1307 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1308 Scope = LScopes.getCurrentFunctionScope();
1309 else if (MDNode *IA = DV.getInlinedAt())
1310 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1312 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1313 // If variable scope is not found then skip this variable.
1317 Processed.insert(DV);
1318 assert(MInsn->isDebugValue() && "History must begin with debug value");
1319 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1320 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1321 if (!addCurrentFnArgument(RegVar, Scope))
1322 addScopeVariable(Scope, RegVar);
1324 AbsVar->setMInsn(MInsn);
1326 // Simplify ranges that are fully coalesced.
1327 if (History.size() <= 1 ||
1328 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1329 RegVar->setMInsn(MInsn);
1333 // Handle multiple DBG_VALUE instructions describing one variable.
1334 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1336 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1337 HI = History.begin(),
1340 const MachineInstr *Begin = *HI;
1341 assert(Begin->isDebugValue() && "Invalid History entry");
1343 // Check if DBG_VALUE is truncating a range.
1344 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1345 !Begin->getOperand(0).getReg())
1348 // Compute the range for a register location.
1349 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1350 const MCSymbol *SLabel = 0;
1353 // If Begin is the last instruction in History then its value is valid
1354 // until the end of the function.
1355 SLabel = FunctionEndSym;
1357 const MachineInstr *End = HI[1];
1358 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1359 << "\t" << *Begin << "\t" << *End << "\n");
1360 if (End->isDebugValue())
1361 SLabel = getLabelBeforeInsn(End);
1363 // End is a normal instruction clobbering the range.
1364 SLabel = getLabelAfterInsn(End);
1365 assert(SLabel && "Forgot label after clobber instruction");
1370 // The value is valid until the next DBG_VALUE or clobber.
1371 DotDebugLocEntries.push_back(
1372 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1374 DotDebugLocEntries.push_back(DotDebugLocEntry());
1377 // Collect info for variables that were optimized out.
1378 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1379 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1380 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1381 DIVariable DV(Variables.getElement(i));
1382 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1384 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1385 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1389 // Return Label preceding the instruction.
1390 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1391 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1392 assert(Label && "Didn't insert label before instruction");
1396 // Return Label immediately following the instruction.
1397 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1398 return LabelsAfterInsn.lookup(MI);
1401 // Process beginning of an instruction.
1402 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1405 // Check if source location changes, but ignore DBG_VALUE locations.
1406 if (!MI->isDebugValue()) {
1407 DebugLoc DL = MI->getDebugLoc();
1408 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1411 if (DL == PrologEndLoc) {
1412 Flags |= DWARF2_FLAG_PROLOGUE_END;
1413 PrologEndLoc = DebugLoc();
1415 if (PrologEndLoc.isUnknown())
1416 Flags |= DWARF2_FLAG_IS_STMT;
1418 if (!DL.isUnknown()) {
1419 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1420 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1422 recordSourceLine(0, 0, 0, 0);
1426 // Insert labels where requested.
1427 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1428 LabelsBeforeInsn.find(MI);
1431 if (I == LabelsBeforeInsn.end())
1434 // Label already assigned.
1439 PrevLabel = MMI->getContext().CreateTempSymbol();
1440 Asm->OutStreamer.EmitLabel(PrevLabel);
1442 I->second = PrevLabel;
1445 // Process end of an instruction.
1446 void DwarfDebug::endInstruction() {
1448 // Don't create a new label after DBG_VALUE instructions.
1449 // They don't generate code.
1450 if (!CurMI->isDebugValue())
1453 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1454 LabelsAfterInsn.find(CurMI);
1458 if (I == LabelsAfterInsn.end())
1461 // Label already assigned.
1465 // We need a label after this instruction.
1467 PrevLabel = MMI->getContext().CreateTempSymbol();
1468 Asm->OutStreamer.EmitLabel(PrevLabel);
1470 I->second = PrevLabel;
1473 // Each LexicalScope has first instruction and last instruction to mark
1474 // beginning and end of a scope respectively. Create an inverse map that list
1475 // scopes starts (and ends) with an instruction. One instruction may start (or
1476 // end) multiple scopes. Ignore scopes that are not reachable.
1477 void DwarfDebug::identifyScopeMarkers() {
1478 SmallVector<LexicalScope *, 4> WorkList;
1479 WorkList.push_back(LScopes.getCurrentFunctionScope());
1480 while (!WorkList.empty()) {
1481 LexicalScope *S = WorkList.pop_back_val();
1483 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1484 if (!Children.empty())
1485 for (SmallVectorImpl<LexicalScope *>::const_iterator
1486 SI = Children.begin(),
1487 SE = Children.end();
1489 WorkList.push_back(*SI);
1491 if (S->isAbstractScope())
1494 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1497 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1500 assert(RI->first && "InsnRange does not have first instruction!");
1501 assert(RI->second && "InsnRange does not have second instruction!");
1502 requestLabelBeforeInsn(RI->first);
1503 requestLabelAfterInsn(RI->second);
1508 // Gather pre-function debug information. Assumes being called immediately
1509 // after the function entry point has been emitted.
1510 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1513 // If there's no debug info for the function we're not going to do anything.
1514 if (!MMI->hasDebugInfo())
1517 // Grab the lexical scopes for the function, if we don't have any of those
1518 // then we're not going to be able to do anything.
1519 LScopes.initialize(*MF);
1520 if (LScopes.empty())
1523 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1525 // Make sure that each lexical scope will have a begin/end label.
1526 identifyScopeMarkers();
1528 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1529 // belongs to so that we add to the correct per-cu line table in the
1531 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1532 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1533 assert(TheCU && "Unable to find compile unit!");
1534 if (Asm->OutStreamer.hasRawTextSupport())
1535 // Use a single line table if we are generating assembly.
1536 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1538 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1540 // Check the current section against the standard text section. If different
1541 // keep track so that we will know when we're emitting functions into multiple
1543 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1544 UsedNonDefaultText = true;
1546 // Emit a label for the function so that we have a beginning address.
1547 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1548 // Assumes in correct section after the entry point.
1549 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1551 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1552 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1553 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1555 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1557 bool AtBlockEntry = true;
1558 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1560 const MachineInstr *MI = II;
1562 if (MI->isDebugValue()) {
1563 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1565 // Keep track of user variables.
1567 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1569 // Variable is in a register, we need to check for clobbers.
1570 if (isDbgValueInDefinedReg(MI))
1571 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1573 // Check the history of this variable.
1574 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1575 if (History.empty()) {
1576 UserVariables.push_back(Var);
1577 // The first mention of a function argument gets the FunctionBeginSym
1578 // label, so arguments are visible when breaking at function entry.
1580 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1581 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1582 LabelsBeforeInsn[MI] = FunctionBeginSym;
1584 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1585 const MachineInstr *Prev = History.back();
1586 if (Prev->isDebugValue()) {
1587 // Coalesce identical entries at the end of History.
1588 if (History.size() >= 2 &&
1589 Prev->isIdenticalTo(History[History.size() - 2])) {
1590 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1591 << "\t" << *Prev << "\t"
1592 << *History[History.size() - 2] << "\n");
1596 // Terminate old register assignments that don't reach MI;
1597 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1598 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1599 isDbgValueInDefinedReg(Prev)) {
1600 // Previous register assignment needs to terminate at the end of
1602 MachineBasicBlock::const_iterator LastMI =
1603 PrevMBB->getLastNonDebugInstr();
1604 if (LastMI == PrevMBB->end()) {
1605 // Drop DBG_VALUE for empty range.
1606 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1607 << "\t" << *Prev << "\n");
1609 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1610 // Terminate after LastMI.
1611 History.push_back(LastMI);
1615 History.push_back(MI);
1617 // Not a DBG_VALUE instruction.
1619 AtBlockEntry = false;
1621 // First known non-DBG_VALUE and non-frame setup location marks
1622 // the beginning of the function body.
1623 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1624 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1625 PrologEndLoc = MI->getDebugLoc();
1627 // Check if the instruction clobbers any registers with debug vars.
1628 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1629 MOE = MI->operands_end();
1630 MOI != MOE; ++MOI) {
1631 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1633 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1636 const MDNode *Var = LiveUserVar[Reg];
1639 // Reg is now clobbered.
1640 LiveUserVar[Reg] = 0;
1642 // Was MD last defined by a DBG_VALUE referring to Reg?
1643 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1644 if (HistI == DbgValues.end())
1646 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1647 if (History.empty())
1649 const MachineInstr *Prev = History.back();
1650 // Sanity-check: Register assignments are terminated at the end of
1652 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1654 // Is the variable still in Reg?
1655 if (!isDbgValueInDefinedReg(Prev) ||
1656 Prev->getOperand(0).getReg() != Reg)
1658 // Var is clobbered. Make sure the next instruction gets a label.
1659 History.push_back(MI);
1666 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1668 SmallVectorImpl<const MachineInstr *> &History = I->second;
1669 if (History.empty())
1672 // Make sure the final register assignments are terminated.
1673 const MachineInstr *Prev = History.back();
1674 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1675 const MachineBasicBlock *PrevMBB = Prev->getParent();
1676 MachineBasicBlock::const_iterator LastMI =
1677 PrevMBB->getLastNonDebugInstr();
1678 if (LastMI == PrevMBB->end())
1679 // Drop DBG_VALUE for empty range.
1681 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1682 // Terminate after LastMI.
1683 History.push_back(LastMI);
1686 // Request labels for the full history.
1687 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1688 const MachineInstr *MI = History[i];
1689 if (MI->isDebugValue())
1690 requestLabelBeforeInsn(MI);
1692 requestLabelAfterInsn(MI);
1696 PrevInstLoc = DebugLoc();
1697 PrevLabel = FunctionBeginSym;
1699 // Record beginning of function.
1700 if (!PrologEndLoc.isUnknown()) {
1701 DebugLoc FnStartDL =
1702 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1704 FnStartDL.getLine(), FnStartDL.getCol(),
1705 FnStartDL.getScope(MF->getFunction()->getContext()),
1706 // We'd like to list the prologue as "not statements" but GDB behaves
1707 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1708 DWARF2_FLAG_IS_STMT);
1712 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1713 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1714 DIVariable DV = Var->getVariable();
1715 // Variables with positive arg numbers are parameters.
1716 if (unsigned ArgNum = DV.getArgNumber()) {
1717 // Keep all parameters in order at the start of the variable list to ensure
1718 // function types are correct (no out-of-order parameters)
1720 // This could be improved by only doing it for optimized builds (unoptimized
1721 // builds have the right order to begin with), searching from the back (this
1722 // would catch the unoptimized case quickly), or doing a binary search
1723 // rather than linear search.
1724 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1725 while (I != Vars.end()) {
1726 unsigned CurNum = (*I)->getVariable().getArgNumber();
1727 // A local (non-parameter) variable has been found, insert immediately
1731 // A later indexed parameter has been found, insert immediately before it.
1732 if (CurNum > ArgNum)
1736 Vars.insert(I, Var);
1740 Vars.push_back(Var);
1743 // Gather and emit post-function debug information.
1744 void DwarfDebug::endFunction(const MachineFunction *MF) {
1745 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1746 // though the beginFunction may not be called at all.
1747 // We should handle both cases.
1751 assert(CurFn == MF);
1754 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1759 // Define end label for subprogram.
1760 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1761 // Assumes in correct section after the entry point.
1762 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1764 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1765 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1767 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1768 collectVariableInfo(ProcessedVars);
1770 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1771 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1772 assert(TheCU && "Unable to find compile unit!");
1774 // Construct abstract scopes.
1775 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1776 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1777 LexicalScope *AScope = AList[i];
1778 DISubprogram SP(AScope->getScopeNode());
1779 if (SP.isSubprogram()) {
1780 // Collect info for variables that were optimized out.
1781 DIArray Variables = SP.getVariables();
1782 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1783 DIVariable DV(Variables.getElement(i));
1784 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1786 // Check that DbgVariable for DV wasn't created earlier, when
1787 // findAbstractVariable() was called for inlined instance of DV.
1788 LLVMContext &Ctx = DV->getContext();
1789 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1790 if (AbstractVariables.lookup(CleanDV))
1792 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1793 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1796 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1797 constructScopeDIE(TheCU, AScope);
1800 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1801 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1802 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1804 // Add the range of this function to the list of ranges for the CU.
1805 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1806 TheCU->addRange(llvm_move(Span));
1809 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1810 E = ScopeVariables.end();
1812 DeleteContainerPointers(I->second);
1813 ScopeVariables.clear();
1814 DeleteContainerPointers(CurrentFnArguments);
1815 UserVariables.clear();
1817 AbstractVariables.clear();
1818 LabelsBeforeInsn.clear();
1819 LabelsAfterInsn.clear();
1824 // Register a source line with debug info. Returns the unique label that was
1825 // emitted and which provides correspondence to the source line list.
1826 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1832 DIDescriptor Scope(S);
1834 if (Scope.isCompileUnit()) {
1835 DICompileUnit CU(S);
1836 Fn = CU.getFilename();
1837 Dir = CU.getDirectory();
1838 } else if (Scope.isFile()) {
1840 Fn = F.getFilename();
1841 Dir = F.getDirectory();
1842 } else if (Scope.isSubprogram()) {
1844 Fn = SP.getFilename();
1845 Dir = SP.getDirectory();
1846 } else if (Scope.isLexicalBlockFile()) {
1847 DILexicalBlockFile DBF(S);
1848 Fn = DBF.getFilename();
1849 Dir = DBF.getDirectory();
1850 } else if (Scope.isLexicalBlock()) {
1851 DILexicalBlock DB(S);
1852 Fn = DB.getFilename();
1853 Dir = DB.getDirectory();
1855 llvm_unreachable("Unexpected scope info");
1857 Src = getOrCreateSourceID(
1858 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1860 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1863 //===----------------------------------------------------------------------===//
1865 //===----------------------------------------------------------------------===//
1867 // Compute the size and offset of a DIE. The offset is relative to start of the
1868 // CU. It returns the offset after laying out the DIE.
1869 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1870 // Get the children.
1871 const std::vector<DIE *> &Children = Die->getChildren();
1873 // Record the abbreviation.
1874 assignAbbrevNumber(Die->getAbbrev());
1876 // Get the abbreviation for this DIE.
1877 const DIEAbbrev &Abbrev = Die->getAbbrev();
1880 Die->setOffset(Offset);
1882 // Start the size with the size of abbreviation code.
1883 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1885 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1886 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1888 // Size the DIE attribute values.
1889 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1890 // Size attribute value.
1891 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1893 // Size the DIE children if any.
1894 if (!Children.empty()) {
1895 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1896 "Children flag not set");
1898 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1899 Offset = computeSizeAndOffset(Children[j], Offset);
1901 // End of children marker.
1902 Offset += sizeof(int8_t);
1905 Die->setSize(Offset - Die->getOffset());
1909 // Compute the size and offset for each DIE.
1910 void DwarfFile::computeSizeAndOffsets() {
1911 // Offset from the first CU in the debug info section is 0 initially.
1912 unsigned SecOffset = 0;
1914 // Iterate over each compile unit and set the size and offsets for each
1915 // DIE within each compile unit. All offsets are CU relative.
1916 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1919 (*I)->setDebugInfoOffset(SecOffset);
1921 // CU-relative offset is reset to 0 here.
1922 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1923 (*I)->getHeaderSize(); // Unit-specific headers
1925 // EndOffset here is CU-relative, after laying out
1926 // all of the CU DIE.
1927 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1928 SecOffset += EndOffset;
1932 // Emit initial Dwarf sections with a label at the start of each one.
1933 void DwarfDebug::emitSectionLabels() {
1934 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1936 // Dwarf sections base addresses.
1937 DwarfInfoSectionSym =
1938 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1939 if (useSplitDwarf())
1940 DwarfInfoDWOSectionSym =
1941 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1942 DwarfAbbrevSectionSym =
1943 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1944 if (useSplitDwarf())
1945 DwarfAbbrevDWOSectionSym = emitSectionSym(
1946 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1947 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1949 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1950 emitSectionSym(Asm, MacroInfo);
1952 DwarfLineSectionSym =
1953 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1954 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1955 if (GenerateGnuPubSections) {
1956 DwarfGnuPubNamesSectionSym =
1957 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1958 DwarfGnuPubTypesSectionSym =
1959 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1960 } else if (HasDwarfPubSections) {
1961 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1962 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1965 DwarfStrSectionSym =
1966 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1967 if (useSplitDwarf()) {
1968 DwarfStrDWOSectionSym =
1969 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1970 DwarfAddrSectionSym =
1971 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1973 DwarfDebugRangeSectionSym =
1974 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1976 DwarfDebugLocSectionSym =
1977 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1980 // Recursively emits a debug information entry.
1981 void DwarfDebug::emitDIE(DIE *Die) {
1982 // Get the abbreviation for this DIE.
1983 const DIEAbbrev &Abbrev = Die->getAbbrev();
1985 // Emit the code (index) for the abbreviation.
1986 if (Asm->isVerbose())
1987 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1988 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1989 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1990 dwarf::TagString(Abbrev.getTag()));
1991 Asm->EmitULEB128(Abbrev.getNumber());
1993 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1994 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1996 // Emit the DIE attribute values.
1997 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1998 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1999 dwarf::Form Form = AbbrevData[i].getForm();
2000 assert(Form && "Too many attributes for DIE (check abbreviation)");
2002 if (Asm->isVerbose())
2003 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2006 case dwarf::DW_AT_abstract_origin:
2007 case dwarf::DW_AT_type:
2008 case dwarf::DW_AT_friend:
2009 case dwarf::DW_AT_specification:
2010 case dwarf::DW_AT_import:
2011 case dwarf::DW_AT_containing_type: {
2012 DIEEntry *E = cast<DIEEntry>(Values[i]);
2013 DIE *Origin = E->getEntry();
2014 unsigned Addr = Origin->getOffset();
2015 if (Form == dwarf::DW_FORM_ref_addr) {
2016 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2017 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2018 // section. Origin->getOffset() returns the offset from start of the
2020 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2021 assert(CU && "CUDie should belong to a CU.");
2022 Addr += CU->getDebugInfoOffset();
2023 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2024 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2025 DIEEntry::getRefAddrSize(Asm));
2027 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2028 CU->getSectionSym(),
2029 DIEEntry::getRefAddrSize(Asm));
2031 // Make sure Origin belong to the same CU.
2032 assert(Die->getUnit() == Origin->getUnit() &&
2033 "The referenced DIE should belong to the same CU in ref4");
2034 Asm->EmitInt32(Addr);
2038 case dwarf::DW_AT_location: {
2039 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2040 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2041 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2043 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2045 Values[i]->EmitValue(Asm, Form);
2049 case dwarf::DW_AT_accessibility: {
2050 if (Asm->isVerbose()) {
2051 DIEInteger *V = cast<DIEInteger>(Values[i]);
2052 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2054 Values[i]->EmitValue(Asm, Form);
2058 // Emit an attribute using the defined form.
2059 Values[i]->EmitValue(Asm, Form);
2064 // Emit the DIE children if any.
2065 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2066 const std::vector<DIE *> &Children = Die->getChildren();
2068 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2069 emitDIE(Children[j]);
2071 Asm->OutStreamer.AddComment("End Of Children Mark");
2076 // Emit the various dwarf units to the unit section USection with
2077 // the abbreviations going into ASection.
2078 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2079 const MCSymbol *ASectionSym) {
2080 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2082 DwarfUnit *TheU = *I;
2083 DIE *Die = TheU->getUnitDie();
2084 const MCSection *USection = TheU->getSection();
2085 Asm->OutStreamer.SwitchSection(USection);
2087 // Emit the compile units header.
2088 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2090 // Emit size of content not including length itself
2091 Asm->OutStreamer.AddComment("Length of Unit");
2092 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2094 TheU->emitHeader(ASection, ASectionSym);
2097 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2101 // Emit the debug info section.
2102 void DwarfDebug::emitDebugInfo() {
2103 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2105 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2106 DwarfAbbrevSectionSym);
2109 // Emit the abbreviation section.
2110 void DwarfDebug::emitAbbreviations() {
2111 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2113 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2116 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2117 // Check to see if it is worth the effort.
2118 if (!Abbreviations.empty()) {
2119 // Start the debug abbrev section.
2120 Asm->OutStreamer.SwitchSection(Section);
2122 // For each abbrevation.
2123 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2124 // Get abbreviation data
2125 const DIEAbbrev *Abbrev = Abbreviations[i];
2127 // Emit the abbrevations code (base 1 index.)
2128 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2130 // Emit the abbreviations data.
2134 // Mark end of abbreviations.
2135 Asm->EmitULEB128(0, "EOM(3)");
2139 // Emit the last address of the section and the end of the line matrix.
2140 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2141 // Define last address of section.
2142 Asm->OutStreamer.AddComment("Extended Op");
2145 Asm->OutStreamer.AddComment("Op size");
2146 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2147 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2148 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2150 Asm->OutStreamer.AddComment("Section end label");
2152 Asm->OutStreamer.EmitSymbolValue(
2153 Asm->GetTempSymbol("section_end", SectionEnd),
2154 Asm->getDataLayout().getPointerSize());
2156 // Mark end of matrix.
2157 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2163 // Emit visible names into a hashed accelerator table section.
2164 void DwarfDebug::emitAccelNames() {
2166 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2167 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2168 E = getUnits().end();
2170 DwarfUnit *TheU = *I;
2171 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2172 for (StringMap<std::vector<const DIE *> >::const_iterator
2176 StringRef Name = GI->getKey();
2177 const std::vector<const DIE *> &Entities = GI->second;
2178 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2179 DE = Entities.end();
2181 AT.AddName(Name, *DI);
2185 AT.FinalizeTable(Asm, "Names");
2186 Asm->OutStreamer.SwitchSection(
2187 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2188 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2189 Asm->OutStreamer.EmitLabel(SectionBegin);
2191 // Emit the full data.
2192 AT.Emit(Asm, SectionBegin, &InfoHolder);
2195 // Emit objective C classes and categories into a hashed accelerator table
2197 void DwarfDebug::emitAccelObjC() {
2199 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2200 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2201 E = getUnits().end();
2203 DwarfUnit *TheU = *I;
2204 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2205 for (StringMap<std::vector<const DIE *> >::const_iterator
2209 StringRef Name = GI->getKey();
2210 const std::vector<const DIE *> &Entities = GI->second;
2211 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2212 DE = Entities.end();
2214 AT.AddName(Name, *DI);
2218 AT.FinalizeTable(Asm, "ObjC");
2219 Asm->OutStreamer.SwitchSection(
2220 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2221 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2222 Asm->OutStreamer.EmitLabel(SectionBegin);
2224 // Emit the full data.
2225 AT.Emit(Asm, SectionBegin, &InfoHolder);
2228 // Emit namespace dies into a hashed accelerator table.
2229 void DwarfDebug::emitAccelNamespaces() {
2231 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2232 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2233 E = getUnits().end();
2235 DwarfUnit *TheU = *I;
2236 const StringMap<std::vector<const DIE *> > &Names =
2237 TheU->getAccelNamespace();
2238 for (StringMap<std::vector<const DIE *> >::const_iterator
2242 StringRef Name = GI->getKey();
2243 const std::vector<const DIE *> &Entities = GI->second;
2244 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2245 DE = Entities.end();
2247 AT.AddName(Name, *DI);
2251 AT.FinalizeTable(Asm, "namespac");
2252 Asm->OutStreamer.SwitchSection(
2253 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2254 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2255 Asm->OutStreamer.EmitLabel(SectionBegin);
2257 // Emit the full data.
2258 AT.Emit(Asm, SectionBegin, &InfoHolder);
2261 // Emit type dies into a hashed accelerator table.
2262 void DwarfDebug::emitAccelTypes() {
2263 std::vector<DwarfAccelTable::Atom> Atoms;
2265 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2267 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2269 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2270 DwarfAccelTable AT(Atoms);
2271 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2272 E = getUnits().end();
2274 DwarfUnit *TheU = *I;
2275 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2276 TheU->getAccelTypes();
2278 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2282 StringRef Name = GI->getKey();
2283 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2285 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2286 DI = Entities.begin(),
2287 DE = Entities.end();
2289 AT.AddName(Name, DI->first, DI->second);
2293 AT.FinalizeTable(Asm, "types");
2294 Asm->OutStreamer.SwitchSection(
2295 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2296 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2297 Asm->OutStreamer.EmitLabel(SectionBegin);
2299 // Emit the full data.
2300 AT.Emit(Asm, SectionBegin, &InfoHolder);
2303 // Public name handling.
2304 // The format for the various pubnames:
2306 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2307 // for the DIE that is named.
2309 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2310 // into the CU and the index value is computed according to the type of value
2311 // for the DIE that is named.
2313 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2314 // it's the offset within the debug_info/debug_types dwo section, however, the
2315 // reference in the pubname header doesn't change.
2317 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2318 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2320 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2322 // We could have a specification DIE that has our most of our knowledge,
2323 // look for that now.
2324 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2326 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2327 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2328 Linkage = dwarf::GIEL_EXTERNAL;
2329 } else if (Die->findAttribute(dwarf::DW_AT_external))
2330 Linkage = dwarf::GIEL_EXTERNAL;
2332 switch (Die->getTag()) {
2333 case dwarf::DW_TAG_class_type:
2334 case dwarf::DW_TAG_structure_type:
2335 case dwarf::DW_TAG_union_type:
2336 case dwarf::DW_TAG_enumeration_type:
2337 return dwarf::PubIndexEntryDescriptor(
2338 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2339 ? dwarf::GIEL_STATIC
2340 : dwarf::GIEL_EXTERNAL);
2341 case dwarf::DW_TAG_typedef:
2342 case dwarf::DW_TAG_base_type:
2343 case dwarf::DW_TAG_subrange_type:
2344 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2345 case dwarf::DW_TAG_namespace:
2346 return dwarf::GIEK_TYPE;
2347 case dwarf::DW_TAG_subprogram:
2348 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2349 case dwarf::DW_TAG_constant:
2350 case dwarf::DW_TAG_variable:
2351 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2352 case dwarf::DW_TAG_enumerator:
2353 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2354 dwarf::GIEL_STATIC);
2356 return dwarf::GIEK_NONE;
2360 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2362 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2363 const MCSection *PSec =
2364 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2365 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2367 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2368 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2369 for (unsigned i = 0; i != Units.size(); ++i) {
2370 DwarfUnit *TheU = Units[i];
2371 unsigned ID = TheU->getUniqueID();
2373 // Start the dwarf pubnames section.
2374 Asm->OutStreamer.SwitchSection(PSec);
2376 // Emit a label so we can reference the beginning of this pubname section.
2378 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2381 Asm->OutStreamer.AddComment("Length of Public Names Info");
2382 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2383 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2384 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2386 Asm->OutStreamer.EmitLabel(BeginLabel);
2388 Asm->OutStreamer.AddComment("DWARF Version");
2389 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2391 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2392 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2394 Asm->OutStreamer.AddComment("Compilation Unit Length");
2395 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2397 // Emit the pubnames for this compilation unit.
2398 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2399 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2402 const char *Name = GI->getKeyData();
2403 const DIE *Entity = GI->second;
2405 Asm->OutStreamer.AddComment("DIE offset");
2406 Asm->EmitInt32(Entity->getOffset());
2409 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2410 Asm->OutStreamer.AddComment(
2411 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2412 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2413 Asm->EmitInt8(Desc.toBits());
2416 Asm->OutStreamer.AddComment("External Name");
2417 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2420 Asm->OutStreamer.AddComment("End Mark");
2422 Asm->OutStreamer.EmitLabel(EndLabel);
2426 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2427 const MCSection *PSec =
2428 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2429 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2431 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2432 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2433 for (unsigned i = 0; i != Units.size(); ++i) {
2434 DwarfUnit *TheU = Units[i];
2435 unsigned ID = TheU->getUniqueID();
2437 // Start the dwarf pubtypes section.
2438 Asm->OutStreamer.SwitchSection(PSec);
2440 // Emit a label so we can reference the beginning of this pubtype section.
2442 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2445 Asm->OutStreamer.AddComment("Length of Public Types Info");
2446 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2447 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2448 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2450 Asm->OutStreamer.EmitLabel(BeginLabel);
2452 Asm->OutStreamer.AddComment("DWARF Version");
2453 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2455 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2456 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2458 Asm->OutStreamer.AddComment("Compilation Unit Length");
2459 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2461 // Emit the pubtypes.
2462 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2463 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2466 const char *Name = GI->getKeyData();
2467 const DIE *Entity = GI->second;
2469 Asm->OutStreamer.AddComment("DIE offset");
2470 Asm->EmitInt32(Entity->getOffset());
2473 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2474 Asm->OutStreamer.AddComment(
2475 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2476 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2477 Asm->EmitInt8(Desc.toBits());
2480 Asm->OutStreamer.AddComment("External Name");
2482 // Emit the name with a terminating null byte.
2483 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2486 Asm->OutStreamer.AddComment("End Mark");
2488 Asm->OutStreamer.EmitLabel(EndLabel);
2492 // Emit strings into a string section.
2493 void DwarfFile::emitStrings(const MCSection *StrSection,
2494 const MCSection *OffsetSection = NULL,
2495 const MCSymbol *StrSecSym = NULL) {
2497 if (StringPool.empty())
2500 // Start the dwarf str section.
2501 Asm->OutStreamer.SwitchSection(StrSection);
2503 // Get all of the string pool entries and put them in an array by their ID so
2504 // we can sort them.
2506 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2509 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2510 I = StringPool.begin(),
2511 E = StringPool.end();
2513 Entries.push_back(std::make_pair(I->second.second, &*I));
2515 array_pod_sort(Entries.begin(), Entries.end());
2517 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2518 // Emit a label for reference from debug information entries.
2519 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2521 // Emit the string itself with a terminating null byte.
2522 Asm->OutStreamer.EmitBytes(
2523 StringRef(Entries[i].second->getKeyData(),
2524 Entries[i].second->getKeyLength() + 1));
2527 // If we've got an offset section go ahead and emit that now as well.
2528 if (OffsetSection) {
2529 Asm->OutStreamer.SwitchSection(OffsetSection);
2530 unsigned offset = 0;
2531 unsigned size = 4; // FIXME: DWARF64 is 8.
2532 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2533 Asm->OutStreamer.EmitIntValue(offset, size);
2534 offset += Entries[i].second->getKeyLength() + 1;
2539 // Emit addresses into the section given.
2540 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2542 if (AddressPool.empty())
2545 // Start the dwarf addr section.
2546 Asm->OutStreamer.SwitchSection(AddrSection);
2548 // Order the address pool entries by ID
2549 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2551 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2552 E = AddressPool.end();
2554 Entries[I->second] = I->first;
2556 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2557 // Emit an expression for reference from debug information entries.
2558 if (const MCExpr *Expr = Entries[i])
2559 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2561 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2565 // Emit visible names into a debug str section.
2566 void DwarfDebug::emitDebugStr() {
2567 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2568 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2571 // Emit locations into the debug loc section.
2572 void DwarfDebug::emitDebugLoc() {
2573 if (DotDebugLocEntries.empty())
2576 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2577 I = DotDebugLocEntries.begin(),
2578 E = DotDebugLocEntries.end();
2580 DotDebugLocEntry &Entry = *I;
2581 if (I + 1 != DotDebugLocEntries.end())
2585 // Start the dwarf loc section.
2586 Asm->OutStreamer.SwitchSection(
2587 Asm->getObjFileLowering().getDwarfLocSection());
2588 unsigned char Size = Asm->getDataLayout().getPointerSize();
2589 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2591 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2592 I = DotDebugLocEntries.begin(),
2593 E = DotDebugLocEntries.end();
2594 I != E; ++I, ++index) {
2595 DotDebugLocEntry &Entry = *I;
2596 if (Entry.isMerged())
2598 if (Entry.isEmpty()) {
2599 Asm->OutStreamer.EmitIntValue(0, Size);
2600 Asm->OutStreamer.EmitIntValue(0, Size);
2601 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2603 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2604 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2605 DIVariable DV(Entry.getVariable());
2606 Asm->OutStreamer.AddComment("Loc expr size");
2607 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2608 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2609 Asm->EmitLabelDifference(end, begin, 2);
2610 Asm->OutStreamer.EmitLabel(begin);
2611 if (Entry.isInt()) {
2612 DIBasicType BTy(DV.getType());
2613 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2614 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2615 Asm->OutStreamer.AddComment("DW_OP_consts");
2616 Asm->EmitInt8(dwarf::DW_OP_consts);
2617 Asm->EmitSLEB128(Entry.getInt());
2619 Asm->OutStreamer.AddComment("DW_OP_constu");
2620 Asm->EmitInt8(dwarf::DW_OP_constu);
2621 Asm->EmitULEB128(Entry.getInt());
2623 } else if (Entry.isLocation()) {
2624 MachineLocation Loc = Entry.getLoc();
2625 if (!DV.hasComplexAddress())
2627 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2629 // Complex address entry.
2630 unsigned N = DV.getNumAddrElements();
2632 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2633 if (Loc.getOffset()) {
2635 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2636 Asm->OutStreamer.AddComment("DW_OP_deref");
2637 Asm->EmitInt8(dwarf::DW_OP_deref);
2638 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2639 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2640 Asm->EmitSLEB128(DV.getAddrElement(1));
2642 // If first address element is OpPlus then emit
2643 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2644 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2645 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2649 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2652 // Emit remaining complex address elements.
2653 for (; i < N; ++i) {
2654 uint64_t Element = DV.getAddrElement(i);
2655 if (Element == DIBuilder::OpPlus) {
2656 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2657 Asm->EmitULEB128(DV.getAddrElement(++i));
2658 } else if (Element == DIBuilder::OpDeref) {
2660 Asm->EmitInt8(dwarf::DW_OP_deref);
2662 llvm_unreachable("unknown Opcode found in complex address");
2666 // else ... ignore constant fp. There is not any good way to
2667 // to represent them here in dwarf.
2668 Asm->OutStreamer.EmitLabel(end);
2673 struct SymbolCUSorter {
2674 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2675 const MCStreamer &Streamer;
2677 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2678 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2679 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2681 // Symbols with no order assigned should be placed at the end.
2682 // (e.g. section end labels)
2684 IA = (unsigned)(-1);
2686 IB = (unsigned)(-1);
2691 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2692 return (A->getUniqueID() < B->getUniqueID());
2696 const MCSymbol *Start, *End;
2699 // Emit a debug aranges section, containing a CU lookup for any
2700 // address we can tie back to a CU.
2701 void DwarfDebug::emitDebugARanges() {
2702 // Start the dwarf aranges section.
2703 Asm->OutStreamer.SwitchSection(
2704 Asm->getObjFileLowering().getDwarfARangesSection());
2706 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2710 // Build a list of sections used.
2711 std::vector<const MCSection *> Sections;
2712 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2714 const MCSection *Section = it->first;
2715 Sections.push_back(Section);
2718 // Sort the sections into order.
2719 // This is only done to ensure consistent output order across different runs.
2720 std::sort(Sections.begin(), Sections.end(), SectionSort);
2722 // Build a set of address spans, sorted by CU.
2723 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2724 const MCSection *Section = Sections[SecIdx];
2725 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2726 if (List.size() < 2)
2729 // Sort the symbols by offset within the section.
2730 SymbolCUSorter sorter(Asm->OutStreamer);
2731 std::sort(List.begin(), List.end(), sorter);
2733 // If we have no section (e.g. common), just write out
2734 // individual spans for each symbol.
2735 if (Section == NULL) {
2736 for (size_t n = 0; n < List.size(); n++) {
2737 const SymbolCU &Cur = List[n];
2740 Span.Start = Cur.Sym;
2743 Spans[Cur.CU].push_back(Span);
2746 // Build spans between each label.
2747 const MCSymbol *StartSym = List[0].Sym;
2748 for (size_t n = 1; n < List.size(); n++) {
2749 const SymbolCU &Prev = List[n - 1];
2750 const SymbolCU &Cur = List[n];
2752 // Try and build the longest span we can within the same CU.
2753 if (Cur.CU != Prev.CU) {
2755 Span.Start = StartSym;
2757 Spans[Prev.CU].push_back(Span);
2764 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2766 // Build a list of CUs used.
2767 std::vector<DwarfCompileUnit *> CUs;
2768 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2769 DwarfCompileUnit *CU = it->first;
2773 // Sort the CU list (again, to ensure consistent output order).
2774 std::sort(CUs.begin(), CUs.end(), CUSort);
2776 // Emit an arange table for each CU we used.
2777 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2778 DwarfCompileUnit *CU = CUs[CUIdx];
2779 std::vector<ArangeSpan> &List = Spans[CU];
2781 // Emit size of content not including length itself.
2782 unsigned ContentSize =
2783 sizeof(int16_t) + // DWARF ARange version number
2784 sizeof(int32_t) + // Offset of CU in the .debug_info section
2785 sizeof(int8_t) + // Pointer Size (in bytes)
2786 sizeof(int8_t); // Segment Size (in bytes)
2788 unsigned TupleSize = PtrSize * 2;
2790 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2792 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2794 ContentSize += Padding;
2795 ContentSize += (List.size() + 1) * TupleSize;
2797 // For each compile unit, write the list of spans it covers.
2798 Asm->OutStreamer.AddComment("Length of ARange Set");
2799 Asm->EmitInt32(ContentSize);
2800 Asm->OutStreamer.AddComment("DWARF Arange version number");
2801 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2802 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2803 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2804 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2805 Asm->EmitInt8(PtrSize);
2806 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2809 Asm->OutStreamer.EmitFill(Padding, 0xff);
2811 for (unsigned n = 0; n < List.size(); n++) {
2812 const ArangeSpan &Span = List[n];
2813 Asm->EmitLabelReference(Span.Start, PtrSize);
2815 // Calculate the size as being from the span start to it's end.
2817 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2819 // For symbols without an end marker (e.g. common), we
2820 // write a single arange entry containing just that one symbol.
2821 uint64_t Size = SymSize[Span.Start];
2825 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2829 Asm->OutStreamer.AddComment("ARange terminator");
2830 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2831 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2835 // Emit visible names into a debug ranges section.
2836 void DwarfDebug::emitDebugRanges() {
2837 // Start the dwarf ranges section.
2838 Asm->OutStreamer.SwitchSection(
2839 Asm->getObjFileLowering().getDwarfRangesSection());
2841 // Size for our labels.
2842 unsigned char Size = Asm->getDataLayout().getPointerSize();
2844 // Grab the specific ranges for the compile units in the module.
2845 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2849 DwarfCompileUnit *TheCU = I->second;
2851 // Emit a symbol so we can find the beginning of our ranges.
2852 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2854 // Iterate over the misc ranges for the compile units in the module.
2855 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2856 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2857 E = RangeLists.end();
2859 const RangeSpanList &List = *I;
2861 // Emit our symbol so we can find the beginning of the range.
2862 Asm->OutStreamer.EmitLabel(List.getSym());
2864 for (SmallVectorImpl<RangeSpan>::const_iterator
2865 RI = List.getRanges().begin(),
2866 RE = List.getRanges().end();
2868 const RangeSpan &Range = *RI;
2869 const MCSymbol *Begin = Range.getStart();
2870 const MCSymbol *End = Range.getEnd();
2871 assert(Begin && "Range without a begin symbol?");
2872 assert(End && "Range without an end symbol?");
2873 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2874 Asm->OutStreamer.EmitSymbolValue(End, Size);
2877 // And terminate the list with two 0 values.
2878 Asm->OutStreamer.EmitIntValue(0, Size);
2879 Asm->OutStreamer.EmitIntValue(0, Size);
2882 // Now emit a range for the CU itself.
2883 if (useCURanges()) {
2884 Asm->OutStreamer.EmitLabel(
2885 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2886 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2887 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2888 RangeSpan Range = Ranges[i];
2889 const MCSymbol *Begin = Range.getStart();
2890 const MCSymbol *End = Range.getEnd();
2891 assert(Begin && "Range without a begin symbol?");
2892 assert(End && "Range without an end symbol?");
2893 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2894 Asm->OutStreamer.EmitSymbolValue(End, Size);
2896 // And terminate the list with two 0 values.
2897 Asm->OutStreamer.EmitIntValue(0, Size);
2898 Asm->OutStreamer.EmitIntValue(0, Size);
2903 // DWARF5 Experimental Separate Dwarf emitters.
2905 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2907 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2908 U->getCUNode().getSplitDebugFilename());
2910 // Relocate to the beginning of the addr_base section, else 0 for the
2911 // beginning of the one for this compile unit.
2912 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2913 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2915 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2917 if (!CompilationDir.empty())
2918 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2920 addGnuPubAttributes(NewU, Die);
2922 SkeletonHolder.addUnit(NewU);
2925 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2926 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2927 // DW_AT_ranges_base, DW_AT_addr_base.
2928 // TODO: Implement DW_AT_ranges_base.
2929 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2931 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2932 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2933 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2934 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2935 DwarfInfoSectionSym);
2937 NewCU->initStmtList(DwarfLineSectionSym);
2939 initSkeletonUnit(CU, Die, NewCU);
2944 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2946 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2948 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2949 DwarfTypeUnit *NewTU = new DwarfTypeUnit(TU->getUniqueID(), Die, TU->getCU(),
2950 Asm, this, &SkeletonHolder);
2951 NewTU->setTypeSignature(TU->getTypeSignature());
2952 NewTU->setType(NULL);
2954 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2956 initSkeletonUnit(TU, Die, NewTU);
2960 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2961 // compile units that would normally be in debug_info.
2962 void DwarfDebug::emitDebugInfoDWO() {
2963 assert(useSplitDwarf() && "No split dwarf debug info?");
2964 InfoHolder.emitUnits(this,
2965 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2966 DwarfAbbrevDWOSectionSym);
2969 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2970 // abbreviations for the .debug_info.dwo section.
2971 void DwarfDebug::emitDebugAbbrevDWO() {
2972 assert(useSplitDwarf() && "No split dwarf?");
2973 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2976 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2977 // string section and is identical in format to traditional .debug_str
2979 void DwarfDebug::emitDebugStrDWO() {
2980 assert(useSplitDwarf() && "No split dwarf?");
2981 const MCSection *OffSec =
2982 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2983 const MCSymbol *StrSym = DwarfStrSectionSym;
2984 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2988 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2989 StringRef Identifier, DIE *RefDie,
2990 DICompositeType CTy) {
2991 // Flag the type unit reference as a declaration so that if it contains
2992 // members (implicit special members, static data member definitions, member
2993 // declarations for definitions in this CU, etc) consumers don't get confused
2994 // and think this is a full definition.
2995 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2997 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2999 CU.addDIETypeSignature(RefDie, *TU);
3003 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3004 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
3005 UnitDie, CU, Asm, this, &InfoHolder);
3007 InfoHolder.addUnit(NewTU);
3009 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3013 Hash.update(Identifier);
3014 // ... take the least significant 8 bytes and return those. Our MD5
3015 // implementation always returns its results in little endian, swap bytes
3017 MD5::MD5Result Result;
3019 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3020 NewTU->setTypeSignature(Signature);
3021 if (useSplitDwarf())
3022 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3024 NewTU->setType(NewTU->createTypeDIE(CTy));
3028 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3029 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3031 CU.addDIETypeSignature(RefDie, *NewTU);