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, bool TLS) {
269 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
270 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
272 ++NextAddrPoolNumber;
273 return P.first->second.Number;
276 // Define a unique number for the abbreviation.
278 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
279 // Check the set for priors.
280 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
282 // If it's newly added.
283 if (InSet == &Abbrev) {
284 // Add to abbreviation list.
285 Abbreviations.push_back(&Abbrev);
287 // Assign the vector position + 1 as its number.
288 Abbrev.setNumber(Abbreviations.size());
290 // Assign existing abbreviation number.
291 Abbrev.setNumber(InSet->getNumber());
295 static bool isObjCClass(StringRef Name) {
296 return Name.startswith("+") || Name.startswith("-");
299 static bool hasObjCCategory(StringRef Name) {
300 if (!isObjCClass(Name))
303 return Name.find(") ") != StringRef::npos;
306 static void getObjCClassCategory(StringRef In, StringRef &Class,
307 StringRef &Category) {
308 if (!hasObjCCategory(In)) {
309 Class = In.slice(In.find('[') + 1, In.find(' '));
314 Class = In.slice(In.find('[') + 1, In.find('('));
315 Category = In.slice(In.find('[') + 1, In.find(' '));
319 static StringRef getObjCMethodName(StringRef In) {
320 return In.slice(In.find(' ') + 1, In.find(']'));
323 // Helper for sorting sections into a stable output order.
324 static bool SectionSort(const MCSection *A, const MCSection *B) {
325 std::string LA = (A ? A->getLabelBeginName() : "");
326 std::string LB = (B ? B->getLabelBeginName() : "");
330 // Add the various names to the Dwarf accelerator table names.
331 // TODO: Determine whether or not we should add names for programs
332 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
333 // is only slightly different than the lookup of non-standard ObjC names.
334 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
335 if (!SP.isDefinition())
337 TheU->addAccelName(SP.getName(), Die);
339 // If the linkage name is different than the name, go ahead and output
340 // that as well into the name table.
341 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
342 TheU->addAccelName(SP.getLinkageName(), Die);
344 // If this is an Objective-C selector name add it to the ObjC accelerator
346 if (isObjCClass(SP.getName())) {
347 StringRef Class, Category;
348 getObjCClassCategory(SP.getName(), Class, Category);
349 TheU->addAccelObjC(Class, Die);
351 TheU->addAccelObjC(Category, Die);
352 // Also add the base method name to the name table.
353 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
357 /// isSubprogramContext - Return true if Context is either a subprogram
358 /// or another context nested inside a subprogram.
359 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
362 DIDescriptor D(Context);
363 if (D.isSubprogram())
366 return isSubprogramContext(resolve(DIType(Context).getContext()));
370 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
371 // and DW_AT_high_pc attributes. If there are global variables in this
372 // scope then create and insert DIEs for these variables.
373 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
375 DIE *SPDie = SPCU->getDIE(SP);
377 assert(SPDie && "Unable to find subprogram DIE!");
379 // If we're updating an abstract DIE, then we will be adding the children and
380 // object pointer later on. But what we don't want to do is process the
381 // concrete DIE twice.
382 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
383 // Pick up abstract subprogram DIE.
385 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
386 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
388 DISubprogram SPDecl = SP.getFunctionDeclaration();
389 if (!SPDecl.isSubprogram()) {
390 // There is not any need to generate specification DIE for a function
391 // defined at compile unit level. If a function is defined inside another
392 // function then gdb prefers the definition at top level and but does not
393 // expect specification DIE in parent function. So avoid creating
394 // specification DIE for a function defined inside a function.
395 DIScope SPContext = resolve(SP.getContext());
396 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
397 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
398 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
401 DICompositeType SPTy = SP.getType();
402 DIArray Args = SPTy.getTypeArray();
403 uint16_t SPTag = SPTy.getTag();
404 if (SPTag == dwarf::DW_TAG_subroutine_type)
405 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
407 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
408 DIType ATy(Args.getElement(i));
409 SPCU->addType(Arg, ATy);
410 if (ATy.isArtificial())
411 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
412 if (ATy.isObjectPointer())
413 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
415 DIE *SPDeclDie = SPDie;
416 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
417 *SPCU->getUnitDie());
418 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
423 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
424 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
426 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
427 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
428 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
430 // Add name to the name table, we do this here because we're guaranteed
431 // to have concrete versions of our DW_TAG_subprogram nodes.
432 addSubprogramNames(SPCU, SP, SPDie);
437 /// Check whether we should create a DIE for the given Scope, return true
438 /// if we don't create a DIE (the corresponding DIE is null).
439 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
440 if (Scope->isAbstractScope())
443 // We don't create a DIE if there is no Range.
444 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
448 if (Ranges.size() > 1)
451 // We don't create a DIE if we have a single Range and the end label
453 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
454 MCSymbol *End = getLabelAfterInsn(RI->second);
458 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
459 dwarf::Attribute A, const MCSymbol *L,
460 const MCSymbol *Sec) {
461 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
462 U->addSectionLabel(D, A, L);
464 U->addSectionDelta(D, A, L, Sec);
467 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
468 const SmallVectorImpl<InsnRange> &Range) {
469 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
470 // emitting it appropriately.
471 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
472 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
473 DwarfDebugRangeSectionSym);
475 RangeSpanList List(RangeSym);
476 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
479 RangeSpan Span(getLabelBeforeInsn(RI->first),
480 getLabelAfterInsn(RI->second));
481 List.addRange(llvm_move(Span));
484 // Add the range list to the set of ranges to be emitted.
485 TheCU->addRangeList(llvm_move(List));
488 // Construct new DW_TAG_lexical_block for this scope and attach
489 // DW_AT_low_pc/DW_AT_high_pc labels.
490 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
491 LexicalScope *Scope) {
492 if (isLexicalScopeDIENull(Scope))
495 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
496 if (Scope->isAbstractScope())
499 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
501 // If we have multiple ranges, emit them into the range section.
502 if (ScopeRanges.size() > 1) {
503 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
507 // Construct the address range for this DIE.
508 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
509 MCSymbol *Start = getLabelBeforeInsn(RI->first);
510 MCSymbol *End = getLabelAfterInsn(RI->second);
511 assert(End && "End label should not be null!");
513 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
514 assert(End->isDefined() && "Invalid end label for an inlined scope!");
516 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
517 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
522 // This scope represents inlined body of a function. Construct DIE to
523 // represent this concrete inlined copy of the function.
524 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
525 LexicalScope *Scope) {
526 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
527 assert(!ScopeRanges.empty() &&
528 "LexicalScope does not have instruction markers!");
530 if (!Scope->getScopeNode())
532 DIScope DS(Scope->getScopeNode());
533 DISubprogram InlinedSP = getDISubprogram(DS);
534 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
536 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
540 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
541 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
543 // If we have multiple ranges, emit them into the range section.
544 if (ScopeRanges.size() > 1)
545 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
547 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
548 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
549 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
551 if (StartLabel == 0 || EndLabel == 0)
552 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
554 assert(StartLabel->isDefined() &&
555 "Invalid starting label for an inlined scope!");
556 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
558 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
559 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
562 InlinedSubprogramDIEs.insert(OriginDIE);
564 // Add the call site information to the DIE.
565 DILocation DL(Scope->getInlinedAt());
566 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
567 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
568 TheCU->getUniqueID()));
569 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
571 // Add name to the name table, we do this here because we're guaranteed
572 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
573 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
578 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
580 SmallVectorImpl<DIE *> &Children) {
581 DIE *ObjectPointer = NULL;
583 // Collect arguments for current function.
584 if (LScopes.isCurrentFunctionScope(Scope))
585 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
586 if (DbgVariable *ArgDV = CurrentFnArguments[i])
588 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
589 Children.push_back(Arg);
590 if (ArgDV->isObjectPointer())
594 // Collect lexical scope children first.
595 const SmallVectorImpl<DbgVariable *> &Variables =
596 ScopeVariables.lookup(Scope);
597 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
598 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
599 Scope->isAbstractScope())) {
600 Children.push_back(Variable);
601 if (Variables[i]->isObjectPointer())
602 ObjectPointer = Variable;
604 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
605 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
606 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
607 Children.push_back(Nested);
608 return ObjectPointer;
611 // Construct a DIE for this scope.
612 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
613 LexicalScope *Scope) {
614 if (!Scope || !Scope->getScopeNode())
617 DIScope DS(Scope->getScopeNode());
619 SmallVector<DIE *, 8> Children;
620 DIE *ObjectPointer = NULL;
621 bool ChildrenCreated = false;
623 // We try to create the scope DIE first, then the children DIEs. This will
624 // avoid creating un-used children then removing them later when we find out
625 // the scope DIE is null.
626 DIE *ScopeDIE = NULL;
627 if (Scope->getInlinedAt())
628 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
629 else if (DS.isSubprogram()) {
630 ProcessedSPNodes.insert(DS);
631 if (Scope->isAbstractScope()) {
632 ScopeDIE = TheCU->getDIE(DS);
633 // Note down abstract DIE.
635 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
637 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
639 // Early exit when we know the scope DIE is going to be null.
640 if (isLexicalScopeDIENull(Scope))
643 // We create children here when we know the scope DIE is not going to be
644 // null and the children will be added to the scope DIE.
645 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
646 ChildrenCreated = true;
648 // There is no need to emit empty lexical block DIE.
649 std::pair<ImportedEntityMap::const_iterator,
650 ImportedEntityMap::const_iterator> Range =
652 ScopesWithImportedEntities.begin(),
653 ScopesWithImportedEntities.end(),
654 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
656 if (Children.empty() && Range.first == Range.second)
658 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
659 assert(ScopeDIE && "Scope DIE should not be null.");
660 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
662 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
666 assert(Children.empty() &&
667 "We create children only when the scope DIE is not null.");
670 if (!ChildrenCreated)
671 // We create children when the scope DIE is not null.
672 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
675 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
678 ScopeDIE->addChild(*I);
680 if (DS.isSubprogram() && ObjectPointer != NULL)
681 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
686 // Look up the source id with the given directory and source file names.
687 // If none currently exists, create a new id and insert it in the
688 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
690 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
692 // If we print assembly, we can't separate .file entries according to
693 // compile units. Thus all files will belong to the default compile unit.
695 // FIXME: add a better feature test than hasRawTextSupport. Even better,
696 // extend .file to support this.
697 if (Asm->OutStreamer.hasRawTextSupport())
700 // If FE did not provide a file name, then assume stdin.
701 if (FileName.empty())
702 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
704 // TODO: this might not belong here. See if we can factor this better.
705 if (DirName == CompilationDir)
708 // FileIDCUMap stores the current ID for the given compile unit.
709 unsigned SrcId = FileIDCUMap[CUID] + 1;
711 // We look up the CUID/file/dir by concatenating them with a zero byte.
712 SmallString<128> NamePair;
713 NamePair += utostr(CUID);
716 NamePair += '\0'; // Zero bytes are not allowed in paths.
717 NamePair += FileName;
719 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
720 if (Ent.getValue() != SrcId)
721 return Ent.getValue();
723 FileIDCUMap[CUID] = SrcId;
724 // Print out a .file directive to specify files for .loc directives.
725 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
730 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
731 if (!GenerateGnuPubSections)
734 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
735 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
736 DwarfGnuPubNamesSectionSym);
738 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
739 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
740 DwarfGnuPubTypesSectionSym);
743 // Create new DwarfCompileUnit for the given metadata node with tag
744 // DW_TAG_compile_unit.
745 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
746 StringRef FN = DIUnit.getFilename();
747 CompilationDir = DIUnit.getDirectory();
749 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
750 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
751 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
752 InfoHolder.addUnit(NewCU);
754 FileIDCUMap[NewCU->getUniqueID()] = 0;
756 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
757 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
758 DIUnit.getLanguage());
759 NewCU->addString(Die, dwarf::DW_AT_name, FN);
762 if (!useSplitDwarf()) {
763 NewCU->initStmtList(DwarfLineSectionSym);
765 // If we're using split dwarf the compilation dir is going to be in the
766 // skeleton CU and so we don't need to duplicate it here.
767 if (!CompilationDir.empty())
768 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
770 addGnuPubAttributes(NewCU, Die);
773 if (DIUnit.isOptimized())
774 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
776 StringRef Flags = DIUnit.getFlags();
778 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
780 if (unsigned RVer = DIUnit.getRunTimeVersion())
781 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
782 dwarf::DW_FORM_data1, RVer);
787 if (useSplitDwarf()) {
788 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
789 DwarfInfoDWOSectionSym);
790 NewCU->setSkeleton(constructSkeletonCU(NewCU));
792 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
793 DwarfInfoSectionSym);
795 CUMap.insert(std::make_pair(DIUnit, NewCU));
796 CUDieMap.insert(std::make_pair(Die, NewCU));
800 // Construct subprogram DIE.
801 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
803 // FIXME: We should only call this routine once, however, during LTO if a
804 // program is defined in multiple CUs we could end up calling it out of
805 // beginModule as we walk the CUs.
807 DwarfCompileUnit *&CURef = SPMap[N];
813 if (!SP.isDefinition())
814 // This is a method declaration which will be handled while constructing
818 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
820 // Expose as a global name.
821 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
824 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
826 DIImportedEntity Module(N);
827 assert(Module.Verify());
828 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
829 constructImportedEntityDIE(TheCU, Module, D);
832 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
833 const MDNode *N, DIE *Context) {
834 DIImportedEntity Module(N);
835 assert(Module.Verify());
836 return constructImportedEntityDIE(TheCU, Module, Context);
839 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
840 const DIImportedEntity &Module,
842 assert(Module.Verify() &&
843 "Use one of the MDNode * overloads to handle invalid metadata");
844 assert(Context && "Should always have a context for an imported_module");
845 DIE *IMDie = new DIE(Module.getTag());
846 TheCU->insertDIE(Module, IMDie);
848 DIDescriptor Entity = Module.getEntity();
849 if (Entity.isNameSpace())
850 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
851 else if (Entity.isSubprogram())
852 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
853 else if (Entity.isType())
854 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
856 EntityDie = TheCU->getDIE(Entity);
857 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
858 Module.getContext().getDirectory(),
859 TheCU->getUniqueID());
860 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
861 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
862 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
863 StringRef Name = Module.getName();
865 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
866 Context->addChild(IMDie);
869 // Emit all Dwarf sections that should come prior to the content. Create
870 // global DIEs and emit initial debug info sections. This is invoked by
871 // the target AsmPrinter.
872 void DwarfDebug::beginModule() {
873 if (DisableDebugInfoPrinting)
876 const Module *M = MMI->getModule();
878 // If module has named metadata anchors then use them, otherwise scan the
879 // module using debug info finder to collect debug info.
880 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
883 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
885 // Emit initial sections so we can reference labels later.
888 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
889 DICompileUnit CUNode(CU_Nodes->getOperand(i));
890 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
891 DIArray ImportedEntities = CUNode.getImportedEntities();
892 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
893 ScopesWithImportedEntities.push_back(std::make_pair(
894 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
895 ImportedEntities.getElement(i)));
896 std::sort(ScopesWithImportedEntities.begin(),
897 ScopesWithImportedEntities.end(), less_first());
898 DIArray GVs = CUNode.getGlobalVariables();
899 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
900 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
901 DIArray SPs = CUNode.getSubprograms();
902 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
903 constructSubprogramDIE(CU, SPs.getElement(i));
904 DIArray EnumTypes = CUNode.getEnumTypes();
905 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
906 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
907 DIArray RetainedTypes = CUNode.getRetainedTypes();
908 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
909 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
910 // Emit imported_modules last so that the relevant context is already
912 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
913 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
916 // Tell MMI that we have debug info.
917 MMI->setDebugInfoAvailability(true);
919 // Prime section data.
920 SectionMap[Asm->getObjFileLowering().getTextSection()];
923 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
924 void DwarfDebug::computeInlinedDIEs() {
925 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
926 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
927 AE = InlinedSubprogramDIEs.end();
930 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
932 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
933 AE = AbstractSPDies.end();
935 DIE *ISP = AI->second;
936 if (InlinedSubprogramDIEs.count(ISP))
938 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
942 // Collect info for variables that were optimized out.
943 void DwarfDebug::collectDeadVariables() {
944 const Module *M = MMI->getModule();
946 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
947 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
948 DICompileUnit TheCU(CU_Nodes->getOperand(i));
949 DIArray Subprograms = TheCU.getSubprograms();
950 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
951 DISubprogram SP(Subprograms.getElement(i));
952 if (ProcessedSPNodes.count(SP) != 0)
954 if (!SP.isSubprogram())
956 if (!SP.isDefinition())
958 DIArray Variables = SP.getVariables();
959 if (Variables.getNumElements() == 0)
962 // Construct subprogram DIE and add variables DIEs.
963 DwarfCompileUnit *SPCU =
964 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
965 assert(SPCU && "Unable to find Compile Unit!");
966 // FIXME: See the comment in constructSubprogramDIE about duplicate
968 constructSubprogramDIE(SPCU, SP);
969 DIE *SPDIE = SPCU->getDIE(SP);
970 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
971 DIVariable DV(Variables.getElement(vi));
972 if (!DV.isVariable())
974 DbgVariable NewVar(DV, NULL, this);
975 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
976 SPDIE->addChild(VariableDIE);
983 void DwarfDebug::finalizeModuleInfo() {
984 // Collect info for variables that were optimized out.
985 collectDeadVariables();
987 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
988 computeInlinedDIEs();
990 // Handle anything that needs to be done on a per-unit basis after
991 // all other generation.
992 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
993 E = getUnits().end();
995 DwarfUnit *TheU = *I;
996 // Emit DW_AT_containing_type attribute to connect types with their
997 // vtable holding type.
998 TheU->constructContainingTypeDIEs();
1000 // Add CU specific attributes if we need to add any.
1001 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1002 // If we're splitting the dwarf out now that we've got the entire
1003 // CU then add the dwo id to it.
1004 DwarfCompileUnit *SkCU =
1005 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1006 if (useSplitDwarf()) {
1007 // This should be a unique identifier when we want to build .dwp files.
1009 if (GenerateCUHash) {
1010 DIEHash CUHash(Asm);
1011 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1013 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1014 dwarf::DW_FORM_data8, ID);
1015 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1016 dwarf::DW_FORM_data8, ID);
1019 // If we have code split among multiple sections or we've requested
1020 // it then emit a DW_AT_ranges attribute on the unit that will remain
1021 // in the .o file, otherwise add a DW_AT_low_pc.
1022 // FIXME: Also add a high pc if we can.
1023 // FIXME: We should use ranges if we have multiple compile units or
1024 // allow reordering of code ala .subsections_via_symbols in mach-o.
1025 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1026 if (useCURanges() && TheU->getRanges().size()) {
1027 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1028 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1029 DwarfDebugRangeSectionSym);
1031 // A DW_AT_low_pc attribute may also be specified in combination with
1032 // DW_AT_ranges to specify the default base address for use in location
1033 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1034 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1037 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1042 // Compute DIE offsets and sizes.
1043 InfoHolder.computeSizeAndOffsets();
1044 if (useSplitDwarf())
1045 SkeletonHolder.computeSizeAndOffsets();
1048 void DwarfDebug::endSections() {
1049 // Filter labels by section.
1050 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1051 const SymbolCU &SCU = ArangeLabels[n];
1052 if (SCU.Sym->isInSection()) {
1053 // Make a note of this symbol and it's section.
1054 const MCSection *Section = &SCU.Sym->getSection();
1055 if (!Section->getKind().isMetadata())
1056 SectionMap[Section].push_back(SCU);
1058 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1059 // appear in the output. This sucks as we rely on sections to build
1060 // arange spans. We can do it without, but it's icky.
1061 SectionMap[NULL].push_back(SCU);
1065 // Build a list of sections used.
1066 std::vector<const MCSection *> Sections;
1067 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1069 const MCSection *Section = it->first;
1070 Sections.push_back(Section);
1073 // Sort the sections into order.
1074 // This is only done to ensure consistent output order across different runs.
1075 std::sort(Sections.begin(), Sections.end(), SectionSort);
1077 // Add terminating symbols for each section.
1078 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1079 const MCSection *Section = Sections[ID];
1080 MCSymbol *Sym = NULL;
1083 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1084 // if we know the section name up-front. For user-created sections, the
1085 // resulting label may not be valid to use as a label. (section names can
1086 // use a greater set of characters on some systems)
1087 Sym = Asm->GetTempSymbol("debug_end", ID);
1088 Asm->OutStreamer.SwitchSection(Section);
1089 Asm->OutStreamer.EmitLabel(Sym);
1092 // Insert a final terminator.
1093 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1096 // For now only turn on CU ranges if we've explicitly asked for it,
1097 // we have -ffunction-sections enabled, we've emitted a function
1098 // into a unique section, or we're using LTO. If we're using LTO then
1099 // we can't know that any particular function in the module is correlated
1100 // to a particular CU and so we need to be conservative. At this point all
1101 // sections should be finalized except for dwarf sections.
1102 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1103 TargetMachine::getFunctionSections();
1106 // Emit all Dwarf sections that should come after the content.
1107 void DwarfDebug::endModule() {
1114 // End any existing sections.
1115 // TODO: Does this need to happen?
1118 // Finalize the debug info for the module.
1119 finalizeModuleInfo();
1123 // Emit all the DIEs into a debug info section.
1126 // Corresponding abbreviations into a abbrev section.
1127 emitAbbreviations();
1129 // Emit info into a debug loc section.
1132 // Emit info into a debug aranges section.
1133 if (GenerateARangeSection)
1136 // Emit info into a debug ranges section.
1139 if (useSplitDwarf()) {
1142 emitDebugAbbrevDWO();
1143 // Emit DWO addresses.
1144 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1147 // Emit info into the dwarf accelerator table sections.
1148 if (useDwarfAccelTables()) {
1151 emitAccelNamespaces();
1155 // Emit the pubnames and pubtypes sections if requested.
1156 if (HasDwarfPubSections) {
1157 emitDebugPubNames(GenerateGnuPubSections);
1158 emitDebugPubTypes(GenerateGnuPubSections);
1164 // Reset these for the next Module if we have one.
1168 // Find abstract variable, if any, associated with Var.
1169 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1170 DebugLoc ScopeLoc) {
1171 LLVMContext &Ctx = DV->getContext();
1172 // More then one inlined variable corresponds to one abstract variable.
1173 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1174 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1176 return AbsDbgVariable;
1178 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1182 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1183 addScopeVariable(Scope, AbsDbgVariable);
1184 AbstractVariables[Var] = AbsDbgVariable;
1185 return AbsDbgVariable;
1188 // If Var is a current function argument then add it to CurrentFnArguments list.
1189 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1190 if (!LScopes.isCurrentFunctionScope(Scope))
1192 DIVariable DV = Var->getVariable();
1193 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1195 unsigned ArgNo = DV.getArgNumber();
1199 size_t Size = CurrentFnArguments.size();
1201 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1202 // llvm::Function argument size is not good indicator of how many
1203 // arguments does the function have at source level.
1205 CurrentFnArguments.resize(ArgNo * 2);
1206 CurrentFnArguments[ArgNo - 1] = Var;
1210 // Collect variable information from side table maintained by MMI.
1211 void DwarfDebug::collectVariableInfoFromMMITable(
1212 SmallPtrSet<const MDNode *, 16> &Processed) {
1213 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1214 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1217 const MDNode *Var = VI->first;
1220 Processed.insert(Var);
1222 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1224 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1226 // If variable scope is not found then skip this variable.
1230 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1231 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1232 RegVar->setFrameIndex(VP.first);
1233 if (!addCurrentFnArgument(RegVar, Scope))
1234 addScopeVariable(Scope, RegVar);
1236 AbsDbgVariable->setFrameIndex(VP.first);
1240 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1242 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1243 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1244 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1245 MI->getOperand(0).getReg() &&
1246 (MI->getOperand(1).isImm() ||
1247 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1250 // Get .debug_loc entry for the instruction range starting at MI.
1251 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1252 const MCSymbol *FLabel,
1253 const MCSymbol *SLabel,
1254 const MachineInstr *MI) {
1255 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1257 assert(MI->getNumOperands() == 3);
1258 if (MI->getOperand(0).isReg()) {
1259 MachineLocation MLoc;
1260 // If the second operand is an immediate, this is a
1261 // register-indirect address.
1262 if (!MI->getOperand(1).isImm())
1263 MLoc.set(MI->getOperand(0).getReg());
1265 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1266 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1268 if (MI->getOperand(0).isImm())
1269 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1270 if (MI->getOperand(0).isFPImm())
1271 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1272 if (MI->getOperand(0).isCImm())
1273 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1275 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1278 // Find variables for each lexical scope.
1280 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1282 // Grab the variable info that was squirreled away in the MMI side-table.
1283 collectVariableInfoFromMMITable(Processed);
1285 for (SmallVectorImpl<const MDNode *>::const_iterator
1286 UVI = UserVariables.begin(),
1287 UVE = UserVariables.end();
1288 UVI != UVE; ++UVI) {
1289 const MDNode *Var = *UVI;
1290 if (Processed.count(Var))
1293 // History contains relevant DBG_VALUE instructions for Var and instructions
1295 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1296 if (History.empty())
1298 const MachineInstr *MInsn = History.front();
1301 LexicalScope *Scope = NULL;
1302 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1303 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1304 Scope = LScopes.getCurrentFunctionScope();
1305 else if (MDNode *IA = DV.getInlinedAt())
1306 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1308 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1309 // If variable scope is not found then skip this variable.
1313 Processed.insert(DV);
1314 assert(MInsn->isDebugValue() && "History must begin with debug value");
1315 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1316 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1317 if (!addCurrentFnArgument(RegVar, Scope))
1318 addScopeVariable(Scope, RegVar);
1320 AbsVar->setMInsn(MInsn);
1322 // Simplify ranges that are fully coalesced.
1323 if (History.size() <= 1 ||
1324 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1325 RegVar->setMInsn(MInsn);
1329 // Handle multiple DBG_VALUE instructions describing one variable.
1330 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1332 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1333 HI = History.begin(),
1336 const MachineInstr *Begin = *HI;
1337 assert(Begin->isDebugValue() && "Invalid History entry");
1339 // Check if DBG_VALUE is truncating a range.
1340 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1341 !Begin->getOperand(0).getReg())
1344 // Compute the range for a register location.
1345 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1346 const MCSymbol *SLabel = 0;
1349 // If Begin is the last instruction in History then its value is valid
1350 // until the end of the function.
1351 SLabel = FunctionEndSym;
1353 const MachineInstr *End = HI[1];
1354 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1355 << "\t" << *Begin << "\t" << *End << "\n");
1356 if (End->isDebugValue())
1357 SLabel = getLabelBeforeInsn(End);
1359 // End is a normal instruction clobbering the range.
1360 SLabel = getLabelAfterInsn(End);
1361 assert(SLabel && "Forgot label after clobber instruction");
1366 // The value is valid until the next DBG_VALUE or clobber.
1367 DotDebugLocEntries.push_back(
1368 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1370 DotDebugLocEntries.push_back(DotDebugLocEntry());
1373 // Collect info for variables that were optimized out.
1374 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1375 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1376 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1377 DIVariable DV(Variables.getElement(i));
1378 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1380 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1381 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1385 // Return Label preceding the instruction.
1386 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1387 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1388 assert(Label && "Didn't insert label before instruction");
1392 // Return Label immediately following the instruction.
1393 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1394 return LabelsAfterInsn.lookup(MI);
1397 // Process beginning of an instruction.
1398 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1401 // Check if source location changes, but ignore DBG_VALUE locations.
1402 if (!MI->isDebugValue()) {
1403 DebugLoc DL = MI->getDebugLoc();
1404 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1407 if (DL == PrologEndLoc) {
1408 Flags |= DWARF2_FLAG_PROLOGUE_END;
1409 PrologEndLoc = DebugLoc();
1411 if (PrologEndLoc.isUnknown())
1412 Flags |= DWARF2_FLAG_IS_STMT;
1414 if (!DL.isUnknown()) {
1415 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1416 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1418 recordSourceLine(0, 0, 0, 0);
1422 // Insert labels where requested.
1423 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1424 LabelsBeforeInsn.find(MI);
1427 if (I == LabelsBeforeInsn.end())
1430 // Label already assigned.
1435 PrevLabel = MMI->getContext().CreateTempSymbol();
1436 Asm->OutStreamer.EmitLabel(PrevLabel);
1438 I->second = PrevLabel;
1441 // Process end of an instruction.
1442 void DwarfDebug::endInstruction() {
1444 // Don't create a new label after DBG_VALUE instructions.
1445 // They don't generate code.
1446 if (!CurMI->isDebugValue())
1449 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1450 LabelsAfterInsn.find(CurMI);
1454 if (I == LabelsAfterInsn.end())
1457 // Label already assigned.
1461 // We need a label after this instruction.
1463 PrevLabel = MMI->getContext().CreateTempSymbol();
1464 Asm->OutStreamer.EmitLabel(PrevLabel);
1466 I->second = PrevLabel;
1469 // Each LexicalScope has first instruction and last instruction to mark
1470 // beginning and end of a scope respectively. Create an inverse map that list
1471 // scopes starts (and ends) with an instruction. One instruction may start (or
1472 // end) multiple scopes. Ignore scopes that are not reachable.
1473 void DwarfDebug::identifyScopeMarkers() {
1474 SmallVector<LexicalScope *, 4> WorkList;
1475 WorkList.push_back(LScopes.getCurrentFunctionScope());
1476 while (!WorkList.empty()) {
1477 LexicalScope *S = WorkList.pop_back_val();
1479 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1480 if (!Children.empty())
1481 for (SmallVectorImpl<LexicalScope *>::const_iterator
1482 SI = Children.begin(),
1483 SE = Children.end();
1485 WorkList.push_back(*SI);
1487 if (S->isAbstractScope())
1490 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1493 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1496 assert(RI->first && "InsnRange does not have first instruction!");
1497 assert(RI->second && "InsnRange does not have second instruction!");
1498 requestLabelBeforeInsn(RI->first);
1499 requestLabelAfterInsn(RI->second);
1504 // Gather pre-function debug information. Assumes being called immediately
1505 // after the function entry point has been emitted.
1506 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1509 // If there's no debug info for the function we're not going to do anything.
1510 if (!MMI->hasDebugInfo())
1513 // Grab the lexical scopes for the function, if we don't have any of those
1514 // then we're not going to be able to do anything.
1515 LScopes.initialize(*MF);
1516 if (LScopes.empty())
1519 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1521 // Make sure that each lexical scope will have a begin/end label.
1522 identifyScopeMarkers();
1524 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1525 // belongs to so that we add to the correct per-cu line table in the
1527 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1528 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1529 assert(TheCU && "Unable to find compile unit!");
1530 if (Asm->OutStreamer.hasRawTextSupport())
1531 // Use a single line table if we are generating assembly.
1532 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1534 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1536 // Check the current section against the standard text section. If different
1537 // keep track so that we will know when we're emitting functions into multiple
1539 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1540 UsedNonDefaultText = true;
1542 // Emit a label for the function so that we have a beginning address.
1543 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1544 // Assumes in correct section after the entry point.
1545 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1547 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1548 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1549 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1551 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1553 bool AtBlockEntry = true;
1554 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1556 const MachineInstr *MI = II;
1558 if (MI->isDebugValue()) {
1559 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1561 // Keep track of user variables.
1563 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1565 // Variable is in a register, we need to check for clobbers.
1566 if (isDbgValueInDefinedReg(MI))
1567 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1569 // Check the history of this variable.
1570 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1571 if (History.empty()) {
1572 UserVariables.push_back(Var);
1573 // The first mention of a function argument gets the FunctionBeginSym
1574 // label, so arguments are visible when breaking at function entry.
1576 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1577 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1578 LabelsBeforeInsn[MI] = FunctionBeginSym;
1580 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1581 const MachineInstr *Prev = History.back();
1582 if (Prev->isDebugValue()) {
1583 // Coalesce identical entries at the end of History.
1584 if (History.size() >= 2 &&
1585 Prev->isIdenticalTo(History[History.size() - 2])) {
1586 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1587 << "\t" << *Prev << "\t"
1588 << *History[History.size() - 2] << "\n");
1592 // Terminate old register assignments that don't reach MI;
1593 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1594 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1595 isDbgValueInDefinedReg(Prev)) {
1596 // Previous register assignment needs to terminate at the end of
1598 MachineBasicBlock::const_iterator LastMI =
1599 PrevMBB->getLastNonDebugInstr();
1600 if (LastMI == PrevMBB->end()) {
1601 // Drop DBG_VALUE for empty range.
1602 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1603 << "\t" << *Prev << "\n");
1605 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1606 // Terminate after LastMI.
1607 History.push_back(LastMI);
1611 History.push_back(MI);
1613 // Not a DBG_VALUE instruction.
1615 AtBlockEntry = false;
1617 // First known non-DBG_VALUE and non-frame setup location marks
1618 // the beginning of the function body.
1619 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1620 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1621 PrologEndLoc = MI->getDebugLoc();
1623 // Check if the instruction clobbers any registers with debug vars.
1624 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1625 MOE = MI->operands_end();
1626 MOI != MOE; ++MOI) {
1627 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1629 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1632 const MDNode *Var = LiveUserVar[Reg];
1635 // Reg is now clobbered.
1636 LiveUserVar[Reg] = 0;
1638 // Was MD last defined by a DBG_VALUE referring to Reg?
1639 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1640 if (HistI == DbgValues.end())
1642 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1643 if (History.empty())
1645 const MachineInstr *Prev = History.back();
1646 // Sanity-check: Register assignments are terminated at the end of
1648 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1650 // Is the variable still in Reg?
1651 if (!isDbgValueInDefinedReg(Prev) ||
1652 Prev->getOperand(0).getReg() != Reg)
1654 // Var is clobbered. Make sure the next instruction gets a label.
1655 History.push_back(MI);
1662 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1664 SmallVectorImpl<const MachineInstr *> &History = I->second;
1665 if (History.empty())
1668 // Make sure the final register assignments are terminated.
1669 const MachineInstr *Prev = History.back();
1670 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1671 const MachineBasicBlock *PrevMBB = Prev->getParent();
1672 MachineBasicBlock::const_iterator LastMI =
1673 PrevMBB->getLastNonDebugInstr();
1674 if (LastMI == PrevMBB->end())
1675 // Drop DBG_VALUE for empty range.
1677 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1678 // Terminate after LastMI.
1679 History.push_back(LastMI);
1682 // Request labels for the full history.
1683 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1684 const MachineInstr *MI = History[i];
1685 if (MI->isDebugValue())
1686 requestLabelBeforeInsn(MI);
1688 requestLabelAfterInsn(MI);
1692 PrevInstLoc = DebugLoc();
1693 PrevLabel = FunctionBeginSym;
1695 // Record beginning of function.
1696 if (!PrologEndLoc.isUnknown()) {
1697 DebugLoc FnStartDL =
1698 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1700 FnStartDL.getLine(), FnStartDL.getCol(),
1701 FnStartDL.getScope(MF->getFunction()->getContext()),
1702 // We'd like to list the prologue as "not statements" but GDB behaves
1703 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1704 DWARF2_FLAG_IS_STMT);
1708 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1709 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1710 DIVariable DV = Var->getVariable();
1711 // Variables with positive arg numbers are parameters.
1712 if (unsigned ArgNum = DV.getArgNumber()) {
1713 // Keep all parameters in order at the start of the variable list to ensure
1714 // function types are correct (no out-of-order parameters)
1716 // This could be improved by only doing it for optimized builds (unoptimized
1717 // builds have the right order to begin with), searching from the back (this
1718 // would catch the unoptimized case quickly), or doing a binary search
1719 // rather than linear search.
1720 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1721 while (I != Vars.end()) {
1722 unsigned CurNum = (*I)->getVariable().getArgNumber();
1723 // A local (non-parameter) variable has been found, insert immediately
1727 // A later indexed parameter has been found, insert immediately before it.
1728 if (CurNum > ArgNum)
1732 Vars.insert(I, Var);
1736 Vars.push_back(Var);
1739 // Gather and emit post-function debug information.
1740 void DwarfDebug::endFunction(const MachineFunction *MF) {
1741 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1742 // though the beginFunction may not be called at all.
1743 // We should handle both cases.
1747 assert(CurFn == MF);
1750 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1755 // Define end label for subprogram.
1756 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1757 // Assumes in correct section after the entry point.
1758 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1760 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1761 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1763 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1764 collectVariableInfo(ProcessedVars);
1766 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1767 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1768 assert(TheCU && "Unable to find compile unit!");
1770 // Construct abstract scopes.
1771 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1772 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1773 LexicalScope *AScope = AList[i];
1774 DISubprogram SP(AScope->getScopeNode());
1775 if (SP.isSubprogram()) {
1776 // Collect info for variables that were optimized out.
1777 DIArray Variables = SP.getVariables();
1778 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1779 DIVariable DV(Variables.getElement(i));
1780 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1782 // Check that DbgVariable for DV wasn't created earlier, when
1783 // findAbstractVariable() was called for inlined instance of DV.
1784 LLVMContext &Ctx = DV->getContext();
1785 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1786 if (AbstractVariables.lookup(CleanDV))
1788 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1789 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1792 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1793 constructScopeDIE(TheCU, AScope);
1796 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1797 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1798 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1800 // Add the range of this function to the list of ranges for the CU.
1801 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1802 TheCU->addRange(llvm_move(Span));
1805 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1806 E = ScopeVariables.end();
1808 DeleteContainerPointers(I->second);
1809 ScopeVariables.clear();
1810 DeleteContainerPointers(CurrentFnArguments);
1811 UserVariables.clear();
1813 AbstractVariables.clear();
1814 LabelsBeforeInsn.clear();
1815 LabelsAfterInsn.clear();
1820 // Register a source line with debug info. Returns the unique label that was
1821 // emitted and which provides correspondence to the source line list.
1822 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1828 DIDescriptor Scope(S);
1830 if (Scope.isCompileUnit()) {
1831 DICompileUnit CU(S);
1832 Fn = CU.getFilename();
1833 Dir = CU.getDirectory();
1834 } else if (Scope.isFile()) {
1836 Fn = F.getFilename();
1837 Dir = F.getDirectory();
1838 } else if (Scope.isSubprogram()) {
1840 Fn = SP.getFilename();
1841 Dir = SP.getDirectory();
1842 } else if (Scope.isLexicalBlockFile()) {
1843 DILexicalBlockFile DBF(S);
1844 Fn = DBF.getFilename();
1845 Dir = DBF.getDirectory();
1846 } else if (Scope.isLexicalBlock()) {
1847 DILexicalBlock DB(S);
1848 Fn = DB.getFilename();
1849 Dir = DB.getDirectory();
1851 llvm_unreachable("Unexpected scope info");
1853 Src = getOrCreateSourceID(
1854 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1856 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1859 //===----------------------------------------------------------------------===//
1861 //===----------------------------------------------------------------------===//
1863 // Compute the size and offset of a DIE. The offset is relative to start of the
1864 // CU. It returns the offset after laying out the DIE.
1865 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1866 // Get the children.
1867 const std::vector<DIE *> &Children = Die->getChildren();
1869 // Record the abbreviation.
1870 assignAbbrevNumber(Die->getAbbrev());
1872 // Get the abbreviation for this DIE.
1873 const DIEAbbrev &Abbrev = Die->getAbbrev();
1876 Die->setOffset(Offset);
1878 // Start the size with the size of abbreviation code.
1879 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1881 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1882 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1884 // Size the DIE attribute values.
1885 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1886 // Size attribute value.
1887 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1889 // Size the DIE children if any.
1890 if (!Children.empty()) {
1891 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1892 "Children flag not set");
1894 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1895 Offset = computeSizeAndOffset(Children[j], Offset);
1897 // End of children marker.
1898 Offset += sizeof(int8_t);
1901 Die->setSize(Offset - Die->getOffset());
1905 // Compute the size and offset for each DIE.
1906 void DwarfFile::computeSizeAndOffsets() {
1907 // Offset from the first CU in the debug info section is 0 initially.
1908 unsigned SecOffset = 0;
1910 // Iterate over each compile unit and set the size and offsets for each
1911 // DIE within each compile unit. All offsets are CU relative.
1912 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1915 (*I)->setDebugInfoOffset(SecOffset);
1917 // CU-relative offset is reset to 0 here.
1918 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1919 (*I)->getHeaderSize(); // Unit-specific headers
1921 // EndOffset here is CU-relative, after laying out
1922 // all of the CU DIE.
1923 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1924 SecOffset += EndOffset;
1928 // Emit initial Dwarf sections with a label at the start of each one.
1929 void DwarfDebug::emitSectionLabels() {
1930 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1932 // Dwarf sections base addresses.
1933 DwarfInfoSectionSym =
1934 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1935 if (useSplitDwarf())
1936 DwarfInfoDWOSectionSym =
1937 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1938 DwarfAbbrevSectionSym =
1939 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1940 if (useSplitDwarf())
1941 DwarfAbbrevDWOSectionSym = emitSectionSym(
1942 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1943 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1945 DwarfLineSectionSym =
1946 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1947 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1948 if (GenerateGnuPubSections) {
1949 DwarfGnuPubNamesSectionSym =
1950 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1951 DwarfGnuPubTypesSectionSym =
1952 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1953 } else if (HasDwarfPubSections) {
1954 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1955 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1958 DwarfStrSectionSym =
1959 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1960 if (useSplitDwarf()) {
1961 DwarfStrDWOSectionSym =
1962 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1963 DwarfAddrSectionSym =
1964 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1966 DwarfDebugRangeSectionSym =
1967 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1969 DwarfDebugLocSectionSym =
1970 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1973 // Recursively emits a debug information entry.
1974 void DwarfDebug::emitDIE(DIE *Die) {
1975 // Get the abbreviation for this DIE.
1976 const DIEAbbrev &Abbrev = Die->getAbbrev();
1978 // Emit the code (index) for the abbreviation.
1979 if (Asm->isVerbose())
1980 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1981 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1982 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1983 dwarf::TagString(Abbrev.getTag()));
1984 Asm->EmitULEB128(Abbrev.getNumber());
1986 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1987 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1989 // Emit the DIE attribute values.
1990 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1991 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1992 dwarf::Form Form = AbbrevData[i].getForm();
1993 assert(Form && "Too many attributes for DIE (check abbreviation)");
1995 if (Asm->isVerbose())
1996 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1999 case dwarf::DW_AT_abstract_origin:
2000 case dwarf::DW_AT_type:
2001 case dwarf::DW_AT_friend:
2002 case dwarf::DW_AT_specification:
2003 case dwarf::DW_AT_import:
2004 case dwarf::DW_AT_containing_type: {
2005 DIEEntry *E = cast<DIEEntry>(Values[i]);
2006 DIE *Origin = E->getEntry();
2007 unsigned Addr = Origin->getOffset();
2008 if (Form == dwarf::DW_FORM_ref_addr) {
2009 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2010 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2011 // section. Origin->getOffset() returns the offset from start of the
2013 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2014 assert(CU && "CUDie should belong to a CU.");
2015 Addr += CU->getDebugInfoOffset();
2016 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2017 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2018 DIEEntry::getRefAddrSize(Asm));
2020 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2021 CU->getSectionSym(),
2022 DIEEntry::getRefAddrSize(Asm));
2024 // Make sure Origin belong to the same CU.
2025 assert(Die->getUnit() == Origin->getUnit() &&
2026 "The referenced DIE should belong to the same CU in ref4");
2027 Asm->EmitInt32(Addr);
2031 case dwarf::DW_AT_location: {
2032 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2033 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2034 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2036 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2038 Values[i]->EmitValue(Asm, Form);
2042 case dwarf::DW_AT_accessibility: {
2043 if (Asm->isVerbose()) {
2044 DIEInteger *V = cast<DIEInteger>(Values[i]);
2045 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2047 Values[i]->EmitValue(Asm, Form);
2051 // Emit an attribute using the defined form.
2052 Values[i]->EmitValue(Asm, Form);
2057 // Emit the DIE children if any.
2058 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2059 const std::vector<DIE *> &Children = Die->getChildren();
2061 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2062 emitDIE(Children[j]);
2064 Asm->OutStreamer.AddComment("End Of Children Mark");
2069 // Emit the various dwarf units to the unit section USection with
2070 // the abbreviations going into ASection.
2071 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2072 const MCSymbol *ASectionSym) {
2073 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2075 DwarfUnit *TheU = *I;
2076 DIE *Die = TheU->getUnitDie();
2077 const MCSection *USection = TheU->getSection();
2078 Asm->OutStreamer.SwitchSection(USection);
2080 // Emit the compile units header.
2081 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2083 // Emit size of content not including length itself
2084 Asm->OutStreamer.AddComment("Length of Unit");
2085 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2087 TheU->emitHeader(ASection, ASectionSym);
2090 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2094 // Emit the debug info section.
2095 void DwarfDebug::emitDebugInfo() {
2096 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2098 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2099 DwarfAbbrevSectionSym);
2102 // Emit the abbreviation section.
2103 void DwarfDebug::emitAbbreviations() {
2104 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2106 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2109 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2110 // Check to see if it is worth the effort.
2111 if (!Abbreviations.empty()) {
2112 // Start the debug abbrev section.
2113 Asm->OutStreamer.SwitchSection(Section);
2115 // For each abbrevation.
2116 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2117 // Get abbreviation data
2118 const DIEAbbrev *Abbrev = Abbreviations[i];
2120 // Emit the abbrevations code (base 1 index.)
2121 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2123 // Emit the abbreviations data.
2127 // Mark end of abbreviations.
2128 Asm->EmitULEB128(0, "EOM(3)");
2132 // Emit the last address of the section and the end of the line matrix.
2133 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2134 // Define last address of section.
2135 Asm->OutStreamer.AddComment("Extended Op");
2138 Asm->OutStreamer.AddComment("Op size");
2139 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2140 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2141 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2143 Asm->OutStreamer.AddComment("Section end label");
2145 Asm->OutStreamer.EmitSymbolValue(
2146 Asm->GetTempSymbol("section_end", SectionEnd),
2147 Asm->getDataLayout().getPointerSize());
2149 // Mark end of matrix.
2150 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2156 // Emit visible names into a hashed accelerator table section.
2157 void DwarfDebug::emitAccelNames() {
2159 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2160 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2161 E = getUnits().end();
2163 DwarfUnit *TheU = *I;
2164 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2165 for (StringMap<std::vector<const DIE *> >::const_iterator
2169 StringRef Name = GI->getKey();
2170 const std::vector<const DIE *> &Entities = GI->second;
2171 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2172 DE = Entities.end();
2174 AT.AddName(Name, *DI);
2178 AT.FinalizeTable(Asm, "Names");
2179 Asm->OutStreamer.SwitchSection(
2180 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2181 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2182 Asm->OutStreamer.EmitLabel(SectionBegin);
2184 // Emit the full data.
2185 AT.Emit(Asm, SectionBegin, &InfoHolder);
2188 // Emit objective C classes and categories into a hashed accelerator table
2190 void DwarfDebug::emitAccelObjC() {
2192 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2193 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2194 E = getUnits().end();
2196 DwarfUnit *TheU = *I;
2197 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2198 for (StringMap<std::vector<const DIE *> >::const_iterator
2202 StringRef Name = GI->getKey();
2203 const std::vector<const DIE *> &Entities = GI->second;
2204 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2205 DE = Entities.end();
2207 AT.AddName(Name, *DI);
2211 AT.FinalizeTable(Asm, "ObjC");
2212 Asm->OutStreamer.SwitchSection(
2213 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2214 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2215 Asm->OutStreamer.EmitLabel(SectionBegin);
2217 // Emit the full data.
2218 AT.Emit(Asm, SectionBegin, &InfoHolder);
2221 // Emit namespace dies into a hashed accelerator table.
2222 void DwarfDebug::emitAccelNamespaces() {
2224 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2225 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2226 E = getUnits().end();
2228 DwarfUnit *TheU = *I;
2229 const StringMap<std::vector<const DIE *> > &Names =
2230 TheU->getAccelNamespace();
2231 for (StringMap<std::vector<const DIE *> >::const_iterator
2235 StringRef Name = GI->getKey();
2236 const std::vector<const DIE *> &Entities = GI->second;
2237 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2238 DE = Entities.end();
2240 AT.AddName(Name, *DI);
2244 AT.FinalizeTable(Asm, "namespac");
2245 Asm->OutStreamer.SwitchSection(
2246 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2247 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2248 Asm->OutStreamer.EmitLabel(SectionBegin);
2250 // Emit the full data.
2251 AT.Emit(Asm, SectionBegin, &InfoHolder);
2254 // Emit type dies into a hashed accelerator table.
2255 void DwarfDebug::emitAccelTypes() {
2256 std::vector<DwarfAccelTable::Atom> Atoms;
2258 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2260 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2262 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2263 DwarfAccelTable AT(Atoms);
2264 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2265 E = getUnits().end();
2267 DwarfUnit *TheU = *I;
2268 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2269 TheU->getAccelTypes();
2271 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2275 StringRef Name = GI->getKey();
2276 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2278 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2279 DI = Entities.begin(),
2280 DE = Entities.end();
2282 AT.AddName(Name, DI->first, DI->second);
2286 AT.FinalizeTable(Asm, "types");
2287 Asm->OutStreamer.SwitchSection(
2288 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2289 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2290 Asm->OutStreamer.EmitLabel(SectionBegin);
2292 // Emit the full data.
2293 AT.Emit(Asm, SectionBegin, &InfoHolder);
2296 // Public name handling.
2297 // The format for the various pubnames:
2299 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2300 // for the DIE that is named.
2302 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2303 // into the CU and the index value is computed according to the type of value
2304 // for the DIE that is named.
2306 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2307 // it's the offset within the debug_info/debug_types dwo section, however, the
2308 // reference in the pubname header doesn't change.
2310 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2311 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2313 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2315 // We could have a specification DIE that has our most of our knowledge,
2316 // look for that now.
2317 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2319 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2320 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2321 Linkage = dwarf::GIEL_EXTERNAL;
2322 } else if (Die->findAttribute(dwarf::DW_AT_external))
2323 Linkage = dwarf::GIEL_EXTERNAL;
2325 switch (Die->getTag()) {
2326 case dwarf::DW_TAG_class_type:
2327 case dwarf::DW_TAG_structure_type:
2328 case dwarf::DW_TAG_union_type:
2329 case dwarf::DW_TAG_enumeration_type:
2330 return dwarf::PubIndexEntryDescriptor(
2331 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2332 ? dwarf::GIEL_STATIC
2333 : dwarf::GIEL_EXTERNAL);
2334 case dwarf::DW_TAG_typedef:
2335 case dwarf::DW_TAG_base_type:
2336 case dwarf::DW_TAG_subrange_type:
2337 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2338 case dwarf::DW_TAG_namespace:
2339 return dwarf::GIEK_TYPE;
2340 case dwarf::DW_TAG_subprogram:
2341 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2342 case dwarf::DW_TAG_constant:
2343 case dwarf::DW_TAG_variable:
2344 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2345 case dwarf::DW_TAG_enumerator:
2346 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2347 dwarf::GIEL_STATIC);
2349 return dwarf::GIEK_NONE;
2353 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2355 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2356 const MCSection *PSec =
2357 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2358 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2360 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2361 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2362 for (unsigned i = 0; i != Units.size(); ++i) {
2363 DwarfUnit *TheU = Units[i];
2364 unsigned ID = TheU->getUniqueID();
2366 // Start the dwarf pubnames section.
2367 Asm->OutStreamer.SwitchSection(PSec);
2369 // Emit a label so we can reference the beginning of this pubname section.
2371 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2374 Asm->OutStreamer.AddComment("Length of Public Names Info");
2375 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2376 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2377 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2379 Asm->OutStreamer.EmitLabel(BeginLabel);
2381 Asm->OutStreamer.AddComment("DWARF Version");
2382 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2384 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2385 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2387 Asm->OutStreamer.AddComment("Compilation Unit Length");
2388 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2390 // Emit the pubnames for this compilation unit.
2391 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2392 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2395 const char *Name = GI->getKeyData();
2396 const DIE *Entity = GI->second;
2398 Asm->OutStreamer.AddComment("DIE offset");
2399 Asm->EmitInt32(Entity->getOffset());
2402 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2403 Asm->OutStreamer.AddComment(
2404 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2405 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2406 Asm->EmitInt8(Desc.toBits());
2409 Asm->OutStreamer.AddComment("External Name");
2410 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2413 Asm->OutStreamer.AddComment("End Mark");
2415 Asm->OutStreamer.EmitLabel(EndLabel);
2419 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2420 const MCSection *PSec =
2421 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2422 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2424 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2425 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2426 for (unsigned i = 0; i != Units.size(); ++i) {
2427 DwarfUnit *TheU = Units[i];
2428 unsigned ID = TheU->getUniqueID();
2430 // Start the dwarf pubtypes section.
2431 Asm->OutStreamer.SwitchSection(PSec);
2433 // Emit a label so we can reference the beginning of this pubtype section.
2435 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2438 Asm->OutStreamer.AddComment("Length of Public Types Info");
2439 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2440 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2441 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2443 Asm->OutStreamer.EmitLabel(BeginLabel);
2445 Asm->OutStreamer.AddComment("DWARF Version");
2446 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2448 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2449 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2451 Asm->OutStreamer.AddComment("Compilation Unit Length");
2452 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2454 // Emit the pubtypes.
2455 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2456 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2459 const char *Name = GI->getKeyData();
2460 const DIE *Entity = GI->second;
2462 Asm->OutStreamer.AddComment("DIE offset");
2463 Asm->EmitInt32(Entity->getOffset());
2466 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2467 Asm->OutStreamer.AddComment(
2468 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2469 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2470 Asm->EmitInt8(Desc.toBits());
2473 Asm->OutStreamer.AddComment("External Name");
2475 // Emit the name with a terminating null byte.
2476 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2479 Asm->OutStreamer.AddComment("End Mark");
2481 Asm->OutStreamer.EmitLabel(EndLabel);
2485 // Emit strings into a string section.
2486 void DwarfFile::emitStrings(const MCSection *StrSection,
2487 const MCSection *OffsetSection = NULL,
2488 const MCSymbol *StrSecSym = NULL) {
2490 if (StringPool.empty())
2493 // Start the dwarf str section.
2494 Asm->OutStreamer.SwitchSection(StrSection);
2496 // Get all of the string pool entries and put them in an array by their ID so
2497 // we can sort them.
2499 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2502 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2503 I = StringPool.begin(),
2504 E = StringPool.end();
2506 Entries.push_back(std::make_pair(I->second.second, &*I));
2508 array_pod_sort(Entries.begin(), Entries.end());
2510 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2511 // Emit a label for reference from debug information entries.
2512 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2514 // Emit the string itself with a terminating null byte.
2515 Asm->OutStreamer.EmitBytes(
2516 StringRef(Entries[i].second->getKeyData(),
2517 Entries[i].second->getKeyLength() + 1));
2520 // If we've got an offset section go ahead and emit that now as well.
2521 if (OffsetSection) {
2522 Asm->OutStreamer.SwitchSection(OffsetSection);
2523 unsigned offset = 0;
2524 unsigned size = 4; // FIXME: DWARF64 is 8.
2525 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2526 Asm->OutStreamer.EmitIntValue(offset, size);
2527 offset += Entries[i].second->getKeyLength() + 1;
2532 // Emit addresses into the section given.
2533 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2535 if (AddressPool.empty())
2538 // Start the dwarf addr section.
2539 Asm->OutStreamer.SwitchSection(AddrSection);
2541 // Order the address pool entries by ID
2542 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2544 for (AddrPool::iterator I = AddressPool.begin(), E = AddressPool.end();
2546 Entries[I->second.Number] =
2548 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I->first)
2549 : MCSymbolRefExpr::Create(I->first, Asm->OutContext);
2551 for (unsigned i = 0, e = Entries.size(); i != e; ++i)
2552 Asm->OutStreamer.EmitValue(Entries[i],
2553 Asm->getDataLayout().getPointerSize());
2556 // Emit visible names into a debug str section.
2557 void DwarfDebug::emitDebugStr() {
2558 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2559 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2562 // Emit locations into the debug loc section.
2563 void DwarfDebug::emitDebugLoc() {
2564 if (DotDebugLocEntries.empty())
2567 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2568 I = DotDebugLocEntries.begin(),
2569 E = DotDebugLocEntries.end();
2571 DotDebugLocEntry &Entry = *I;
2572 if (I + 1 != DotDebugLocEntries.end())
2576 // Start the dwarf loc section.
2577 Asm->OutStreamer.SwitchSection(
2578 Asm->getObjFileLowering().getDwarfLocSection());
2579 unsigned char Size = Asm->getDataLayout().getPointerSize();
2580 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2582 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2583 I = DotDebugLocEntries.begin(),
2584 E = DotDebugLocEntries.end();
2585 I != E; ++I, ++index) {
2586 DotDebugLocEntry &Entry = *I;
2587 if (Entry.isMerged())
2589 if (Entry.isEmpty()) {
2590 Asm->OutStreamer.EmitIntValue(0, Size);
2591 Asm->OutStreamer.EmitIntValue(0, Size);
2592 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2594 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2595 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2596 DIVariable DV(Entry.getVariable());
2597 Asm->OutStreamer.AddComment("Loc expr size");
2598 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2599 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2600 Asm->EmitLabelDifference(end, begin, 2);
2601 Asm->OutStreamer.EmitLabel(begin);
2602 if (Entry.isInt()) {
2603 DIBasicType BTy(DV.getType());
2604 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2605 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2606 Asm->OutStreamer.AddComment("DW_OP_consts");
2607 Asm->EmitInt8(dwarf::DW_OP_consts);
2608 Asm->EmitSLEB128(Entry.getInt());
2610 Asm->OutStreamer.AddComment("DW_OP_constu");
2611 Asm->EmitInt8(dwarf::DW_OP_constu);
2612 Asm->EmitULEB128(Entry.getInt());
2614 } else if (Entry.isLocation()) {
2615 MachineLocation Loc = Entry.getLoc();
2616 if (!DV.hasComplexAddress())
2618 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2620 // Complex address entry.
2621 unsigned N = DV.getNumAddrElements();
2623 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2624 if (Loc.getOffset()) {
2626 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2627 Asm->OutStreamer.AddComment("DW_OP_deref");
2628 Asm->EmitInt8(dwarf::DW_OP_deref);
2629 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2630 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2631 Asm->EmitSLEB128(DV.getAddrElement(1));
2633 // If first address element is OpPlus then emit
2634 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2635 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2636 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2640 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2643 // Emit remaining complex address elements.
2644 for (; i < N; ++i) {
2645 uint64_t Element = DV.getAddrElement(i);
2646 if (Element == DIBuilder::OpPlus) {
2647 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2648 Asm->EmitULEB128(DV.getAddrElement(++i));
2649 } else if (Element == DIBuilder::OpDeref) {
2651 Asm->EmitInt8(dwarf::DW_OP_deref);
2653 llvm_unreachable("unknown Opcode found in complex address");
2657 // else ... ignore constant fp. There is not any good way to
2658 // to represent them here in dwarf.
2659 Asm->OutStreamer.EmitLabel(end);
2664 struct SymbolCUSorter {
2665 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2666 const MCStreamer &Streamer;
2668 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2669 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2670 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2672 // Symbols with no order assigned should be placed at the end.
2673 // (e.g. section end labels)
2675 IA = (unsigned)(-1);
2677 IB = (unsigned)(-1);
2682 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2683 return (A->getUniqueID() < B->getUniqueID());
2687 const MCSymbol *Start, *End;
2690 // Emit a debug aranges section, containing a CU lookup for any
2691 // address we can tie back to a CU.
2692 void DwarfDebug::emitDebugARanges() {
2693 // Start the dwarf aranges section.
2694 Asm->OutStreamer.SwitchSection(
2695 Asm->getObjFileLowering().getDwarfARangesSection());
2697 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2701 // Build a list of sections used.
2702 std::vector<const MCSection *> Sections;
2703 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2705 const MCSection *Section = it->first;
2706 Sections.push_back(Section);
2709 // Sort the sections into order.
2710 // This is only done to ensure consistent output order across different runs.
2711 std::sort(Sections.begin(), Sections.end(), SectionSort);
2713 // Build a set of address spans, sorted by CU.
2714 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2715 const MCSection *Section = Sections[SecIdx];
2716 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2717 if (List.size() < 2)
2720 // Sort the symbols by offset within the section.
2721 SymbolCUSorter sorter(Asm->OutStreamer);
2722 std::sort(List.begin(), List.end(), sorter);
2724 // If we have no section (e.g. common), just write out
2725 // individual spans for each symbol.
2726 if (Section == NULL) {
2727 for (size_t n = 0; n < List.size(); n++) {
2728 const SymbolCU &Cur = List[n];
2731 Span.Start = Cur.Sym;
2734 Spans[Cur.CU].push_back(Span);
2737 // Build spans between each label.
2738 const MCSymbol *StartSym = List[0].Sym;
2739 for (size_t n = 1; n < List.size(); n++) {
2740 const SymbolCU &Prev = List[n - 1];
2741 const SymbolCU &Cur = List[n];
2743 // Try and build the longest span we can within the same CU.
2744 if (Cur.CU != Prev.CU) {
2746 Span.Start = StartSym;
2748 Spans[Prev.CU].push_back(Span);
2755 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2757 // Build a list of CUs used.
2758 std::vector<DwarfCompileUnit *> CUs;
2759 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2760 DwarfCompileUnit *CU = it->first;
2764 // Sort the CU list (again, to ensure consistent output order).
2765 std::sort(CUs.begin(), CUs.end(), CUSort);
2767 // Emit an arange table for each CU we used.
2768 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2769 DwarfCompileUnit *CU = CUs[CUIdx];
2770 std::vector<ArangeSpan> &List = Spans[CU];
2772 // Emit size of content not including length itself.
2773 unsigned ContentSize =
2774 sizeof(int16_t) + // DWARF ARange version number
2775 sizeof(int32_t) + // Offset of CU in the .debug_info section
2776 sizeof(int8_t) + // Pointer Size (in bytes)
2777 sizeof(int8_t); // Segment Size (in bytes)
2779 unsigned TupleSize = PtrSize * 2;
2781 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2783 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2785 ContentSize += Padding;
2786 ContentSize += (List.size() + 1) * TupleSize;
2788 // For each compile unit, write the list of spans it covers.
2789 Asm->OutStreamer.AddComment("Length of ARange Set");
2790 Asm->EmitInt32(ContentSize);
2791 Asm->OutStreamer.AddComment("DWARF Arange version number");
2792 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2793 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2794 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2795 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2796 Asm->EmitInt8(PtrSize);
2797 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2800 Asm->OutStreamer.EmitFill(Padding, 0xff);
2802 for (unsigned n = 0; n < List.size(); n++) {
2803 const ArangeSpan &Span = List[n];
2804 Asm->EmitLabelReference(Span.Start, PtrSize);
2806 // Calculate the size as being from the span start to it's end.
2808 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2810 // For symbols without an end marker (e.g. common), we
2811 // write a single arange entry containing just that one symbol.
2812 uint64_t Size = SymSize[Span.Start];
2816 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2820 Asm->OutStreamer.AddComment("ARange terminator");
2821 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2822 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2826 // Emit visible names into a debug ranges section.
2827 void DwarfDebug::emitDebugRanges() {
2828 // Start the dwarf ranges section.
2829 Asm->OutStreamer.SwitchSection(
2830 Asm->getObjFileLowering().getDwarfRangesSection());
2832 // Size for our labels.
2833 unsigned char Size = Asm->getDataLayout().getPointerSize();
2835 // Grab the specific ranges for the compile units in the module.
2836 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2840 DwarfCompileUnit *TheCU = I->second;
2842 // Emit a symbol so we can find the beginning of our ranges.
2843 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2845 // Iterate over the misc ranges for the compile units in the module.
2846 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2847 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2848 E = RangeLists.end();
2850 const RangeSpanList &List = *I;
2852 // Emit our symbol so we can find the beginning of the range.
2853 Asm->OutStreamer.EmitLabel(List.getSym());
2855 for (SmallVectorImpl<RangeSpan>::const_iterator
2856 RI = List.getRanges().begin(),
2857 RE = List.getRanges().end();
2859 const RangeSpan &Range = *RI;
2860 const MCSymbol *Begin = Range.getStart();
2861 const MCSymbol *End = Range.getEnd();
2862 assert(Begin && "Range without a begin symbol?");
2863 assert(End && "Range without an end symbol?");
2864 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2865 Asm->OutStreamer.EmitSymbolValue(End, Size);
2868 // And terminate the list with two 0 values.
2869 Asm->OutStreamer.EmitIntValue(0, Size);
2870 Asm->OutStreamer.EmitIntValue(0, Size);
2873 // Now emit a range for the CU itself.
2874 if (useCURanges()) {
2875 Asm->OutStreamer.EmitLabel(
2876 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2877 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2878 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2879 RangeSpan Range = Ranges[i];
2880 const MCSymbol *Begin = Range.getStart();
2881 const MCSymbol *End = Range.getEnd();
2882 assert(Begin && "Range without a begin symbol?");
2883 assert(End && "Range without an end symbol?");
2884 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2885 Asm->OutStreamer.EmitSymbolValue(End, Size);
2887 // And terminate the list with two 0 values.
2888 Asm->OutStreamer.EmitIntValue(0, Size);
2889 Asm->OutStreamer.EmitIntValue(0, Size);
2894 // DWARF5 Experimental Separate Dwarf emitters.
2896 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2898 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2899 U->getCUNode().getSplitDebugFilename());
2901 // Relocate to the beginning of the addr_base section, else 0 for the
2902 // beginning of the one for this compile unit.
2903 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2904 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2906 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2908 if (!CompilationDir.empty())
2909 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2911 addGnuPubAttributes(NewU, Die);
2913 SkeletonHolder.addUnit(NewU);
2916 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2917 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2918 // DW_AT_ranges_base, DW_AT_addr_base.
2919 // TODO: Implement DW_AT_ranges_base.
2920 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2922 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2923 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2924 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2925 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2926 DwarfInfoSectionSym);
2928 NewCU->initStmtList(DwarfLineSectionSym);
2930 initSkeletonUnit(CU, Die, NewCU);
2935 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2937 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2938 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2939 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2941 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2942 DwarfTypeUnit *NewTU =
2943 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2944 NewTU->setTypeSignature(TU->getTypeSignature());
2945 NewTU->setType(NULL);
2947 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2948 CU.applyStmtList(*Die);
2950 initSkeletonUnit(TU, Die, NewTU);
2954 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2955 // compile units that would normally be in debug_info.
2956 void DwarfDebug::emitDebugInfoDWO() {
2957 assert(useSplitDwarf() && "No split dwarf debug info?");
2958 InfoHolder.emitUnits(this,
2959 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2960 DwarfAbbrevDWOSectionSym);
2963 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2964 // abbreviations for the .debug_info.dwo section.
2965 void DwarfDebug::emitDebugAbbrevDWO() {
2966 assert(useSplitDwarf() && "No split dwarf?");
2967 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2970 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2971 // string section and is identical in format to traditional .debug_str
2973 void DwarfDebug::emitDebugStrDWO() {
2974 assert(useSplitDwarf() && "No split dwarf?");
2975 const MCSection *OffSec =
2976 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2977 const MCSymbol *StrSym = DwarfStrSectionSym;
2978 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2982 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2983 StringRef Identifier, DIE *RefDie,
2984 DICompositeType CTy) {
2985 // Flag the type unit reference as a declaration so that if it contains
2986 // members (implicit special members, static data member definitions, member
2987 // declarations for definitions in this CU, etc) consumers don't get confused
2988 // and think this is a full definition.
2989 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2991 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2993 CU.addDIETypeSignature(RefDie, *TU);
2997 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2998 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2999 UnitDie, CU, Asm, this, &InfoHolder);
3001 InfoHolder.addUnit(NewTU);
3003 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3007 Hash.update(Identifier);
3008 // ... take the least significant 8 bytes and return those. Our MD5
3009 // implementation always returns its results in little endian, swap bytes
3011 MD5::MD5Result Result;
3013 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3014 NewTU->setTypeSignature(Signature);
3015 if (useSplitDwarf())
3016 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3018 CU.applyStmtList(*UnitDie);
3020 NewTU->setType(NewTU->createTypeDIE(CTy));
3024 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3025 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3027 CU.addDIETypeSignature(RefDie, *NewTU);