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 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1946 emitSectionSym(Asm, MacroInfo);
1948 DwarfLineSectionSym =
1949 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1950 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1951 if (GenerateGnuPubSections) {
1952 DwarfGnuPubNamesSectionSym =
1953 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1954 DwarfGnuPubTypesSectionSym =
1955 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1956 } else if (HasDwarfPubSections) {
1957 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1958 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1961 DwarfStrSectionSym =
1962 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1963 if (useSplitDwarf()) {
1964 DwarfStrDWOSectionSym =
1965 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1966 DwarfAddrSectionSym =
1967 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1969 DwarfDebugRangeSectionSym =
1970 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1972 DwarfDebugLocSectionSym =
1973 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1976 // Recursively emits a debug information entry.
1977 void DwarfDebug::emitDIE(DIE *Die) {
1978 // Get the abbreviation for this DIE.
1979 const DIEAbbrev &Abbrev = Die->getAbbrev();
1981 // Emit the code (index) for the abbreviation.
1982 if (Asm->isVerbose())
1983 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1984 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1985 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1986 dwarf::TagString(Abbrev.getTag()));
1987 Asm->EmitULEB128(Abbrev.getNumber());
1989 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1990 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1992 // Emit the DIE attribute values.
1993 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1994 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1995 dwarf::Form Form = AbbrevData[i].getForm();
1996 assert(Form && "Too many attributes for DIE (check abbreviation)");
1998 if (Asm->isVerbose())
1999 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2002 case dwarf::DW_AT_abstract_origin:
2003 case dwarf::DW_AT_type:
2004 case dwarf::DW_AT_friend:
2005 case dwarf::DW_AT_specification:
2006 case dwarf::DW_AT_import:
2007 case dwarf::DW_AT_containing_type: {
2008 DIEEntry *E = cast<DIEEntry>(Values[i]);
2009 DIE *Origin = E->getEntry();
2010 unsigned Addr = Origin->getOffset();
2011 if (Form == dwarf::DW_FORM_ref_addr) {
2012 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2013 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2014 // section. Origin->getOffset() returns the offset from start of the
2016 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2017 assert(CU && "CUDie should belong to a CU.");
2018 Addr += CU->getDebugInfoOffset();
2019 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2020 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2021 DIEEntry::getRefAddrSize(Asm));
2023 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2024 CU->getSectionSym(),
2025 DIEEntry::getRefAddrSize(Asm));
2027 // Make sure Origin belong to the same CU.
2028 assert(Die->getUnit() == Origin->getUnit() &&
2029 "The referenced DIE should belong to the same CU in ref4");
2030 Asm->EmitInt32(Addr);
2034 case dwarf::DW_AT_location: {
2035 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2036 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2037 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2039 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2041 Values[i]->EmitValue(Asm, Form);
2045 case dwarf::DW_AT_accessibility: {
2046 if (Asm->isVerbose()) {
2047 DIEInteger *V = cast<DIEInteger>(Values[i]);
2048 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2050 Values[i]->EmitValue(Asm, Form);
2054 // Emit an attribute using the defined form.
2055 Values[i]->EmitValue(Asm, Form);
2060 // Emit the DIE children if any.
2061 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2062 const std::vector<DIE *> &Children = Die->getChildren();
2064 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2065 emitDIE(Children[j]);
2067 Asm->OutStreamer.AddComment("End Of Children Mark");
2072 // Emit the various dwarf units to the unit section USection with
2073 // the abbreviations going into ASection.
2074 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2075 const MCSymbol *ASectionSym) {
2076 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2078 DwarfUnit *TheU = *I;
2079 DIE *Die = TheU->getUnitDie();
2080 const MCSection *USection = TheU->getSection();
2081 Asm->OutStreamer.SwitchSection(USection);
2083 // Emit the compile units header.
2084 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2086 // Emit size of content not including length itself
2087 Asm->OutStreamer.AddComment("Length of Unit");
2088 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2090 TheU->emitHeader(ASection, ASectionSym);
2093 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2097 // Emit the debug info section.
2098 void DwarfDebug::emitDebugInfo() {
2099 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2101 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2102 DwarfAbbrevSectionSym);
2105 // Emit the abbreviation section.
2106 void DwarfDebug::emitAbbreviations() {
2107 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2109 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2112 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2113 // Check to see if it is worth the effort.
2114 if (!Abbreviations.empty()) {
2115 // Start the debug abbrev section.
2116 Asm->OutStreamer.SwitchSection(Section);
2118 // For each abbrevation.
2119 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2120 // Get abbreviation data
2121 const DIEAbbrev *Abbrev = Abbreviations[i];
2123 // Emit the abbrevations code (base 1 index.)
2124 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2126 // Emit the abbreviations data.
2130 // Mark end of abbreviations.
2131 Asm->EmitULEB128(0, "EOM(3)");
2135 // Emit the last address of the section and the end of the line matrix.
2136 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2137 // Define last address of section.
2138 Asm->OutStreamer.AddComment("Extended Op");
2141 Asm->OutStreamer.AddComment("Op size");
2142 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2143 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2144 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2146 Asm->OutStreamer.AddComment("Section end label");
2148 Asm->OutStreamer.EmitSymbolValue(
2149 Asm->GetTempSymbol("section_end", SectionEnd),
2150 Asm->getDataLayout().getPointerSize());
2152 // Mark end of matrix.
2153 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2159 // Emit visible names into a hashed accelerator table section.
2160 void DwarfDebug::emitAccelNames() {
2162 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2163 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2164 E = getUnits().end();
2166 DwarfUnit *TheU = *I;
2167 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2168 for (StringMap<std::vector<const DIE *> >::const_iterator
2172 StringRef Name = GI->getKey();
2173 const std::vector<const DIE *> &Entities = GI->second;
2174 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2175 DE = Entities.end();
2177 AT.AddName(Name, *DI);
2181 AT.FinalizeTable(Asm, "Names");
2182 Asm->OutStreamer.SwitchSection(
2183 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2184 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2185 Asm->OutStreamer.EmitLabel(SectionBegin);
2187 // Emit the full data.
2188 AT.Emit(Asm, SectionBegin, &InfoHolder);
2191 // Emit objective C classes and categories into a hashed accelerator table
2193 void DwarfDebug::emitAccelObjC() {
2195 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2196 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2197 E = getUnits().end();
2199 DwarfUnit *TheU = *I;
2200 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2201 for (StringMap<std::vector<const DIE *> >::const_iterator
2205 StringRef Name = GI->getKey();
2206 const std::vector<const DIE *> &Entities = GI->second;
2207 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2208 DE = Entities.end();
2210 AT.AddName(Name, *DI);
2214 AT.FinalizeTable(Asm, "ObjC");
2215 Asm->OutStreamer.SwitchSection(
2216 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2217 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2218 Asm->OutStreamer.EmitLabel(SectionBegin);
2220 // Emit the full data.
2221 AT.Emit(Asm, SectionBegin, &InfoHolder);
2224 // Emit namespace dies into a hashed accelerator table.
2225 void DwarfDebug::emitAccelNamespaces() {
2227 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2228 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2229 E = getUnits().end();
2231 DwarfUnit *TheU = *I;
2232 const StringMap<std::vector<const DIE *> > &Names =
2233 TheU->getAccelNamespace();
2234 for (StringMap<std::vector<const DIE *> >::const_iterator
2238 StringRef Name = GI->getKey();
2239 const std::vector<const DIE *> &Entities = GI->second;
2240 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2241 DE = Entities.end();
2243 AT.AddName(Name, *DI);
2247 AT.FinalizeTable(Asm, "namespac");
2248 Asm->OutStreamer.SwitchSection(
2249 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2250 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2251 Asm->OutStreamer.EmitLabel(SectionBegin);
2253 // Emit the full data.
2254 AT.Emit(Asm, SectionBegin, &InfoHolder);
2257 // Emit type dies into a hashed accelerator table.
2258 void DwarfDebug::emitAccelTypes() {
2259 std::vector<DwarfAccelTable::Atom> Atoms;
2261 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2263 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2265 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2266 DwarfAccelTable AT(Atoms);
2267 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2268 E = getUnits().end();
2270 DwarfUnit *TheU = *I;
2271 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2272 TheU->getAccelTypes();
2274 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2278 StringRef Name = GI->getKey();
2279 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2281 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2282 DI = Entities.begin(),
2283 DE = Entities.end();
2285 AT.AddName(Name, DI->first, DI->second);
2289 AT.FinalizeTable(Asm, "types");
2290 Asm->OutStreamer.SwitchSection(
2291 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2292 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2293 Asm->OutStreamer.EmitLabel(SectionBegin);
2295 // Emit the full data.
2296 AT.Emit(Asm, SectionBegin, &InfoHolder);
2299 // Public name handling.
2300 // The format for the various pubnames:
2302 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2303 // for the DIE that is named.
2305 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2306 // into the CU and the index value is computed according to the type of value
2307 // for the DIE that is named.
2309 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2310 // it's the offset within the debug_info/debug_types dwo section, however, the
2311 // reference in the pubname header doesn't change.
2313 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2314 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2316 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2318 // We could have a specification DIE that has our most of our knowledge,
2319 // look for that now.
2320 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2322 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2323 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2324 Linkage = dwarf::GIEL_EXTERNAL;
2325 } else if (Die->findAttribute(dwarf::DW_AT_external))
2326 Linkage = dwarf::GIEL_EXTERNAL;
2328 switch (Die->getTag()) {
2329 case dwarf::DW_TAG_class_type:
2330 case dwarf::DW_TAG_structure_type:
2331 case dwarf::DW_TAG_union_type:
2332 case dwarf::DW_TAG_enumeration_type:
2333 return dwarf::PubIndexEntryDescriptor(
2334 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2335 ? dwarf::GIEL_STATIC
2336 : dwarf::GIEL_EXTERNAL);
2337 case dwarf::DW_TAG_typedef:
2338 case dwarf::DW_TAG_base_type:
2339 case dwarf::DW_TAG_subrange_type:
2340 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2341 case dwarf::DW_TAG_namespace:
2342 return dwarf::GIEK_TYPE;
2343 case dwarf::DW_TAG_subprogram:
2344 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2345 case dwarf::DW_TAG_constant:
2346 case dwarf::DW_TAG_variable:
2347 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2348 case dwarf::DW_TAG_enumerator:
2349 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2350 dwarf::GIEL_STATIC);
2352 return dwarf::GIEK_NONE;
2356 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2358 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2359 const MCSection *PSec =
2360 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2361 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2363 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2364 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2365 for (unsigned i = 0; i != Units.size(); ++i) {
2366 DwarfUnit *TheU = Units[i];
2367 unsigned ID = TheU->getUniqueID();
2369 // Start the dwarf pubnames section.
2370 Asm->OutStreamer.SwitchSection(PSec);
2372 // Emit a label so we can reference the beginning of this pubname section.
2374 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2377 Asm->OutStreamer.AddComment("Length of Public Names Info");
2378 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2379 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2380 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2382 Asm->OutStreamer.EmitLabel(BeginLabel);
2384 Asm->OutStreamer.AddComment("DWARF Version");
2385 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2387 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2388 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2390 Asm->OutStreamer.AddComment("Compilation Unit Length");
2391 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2393 // Emit the pubnames for this compilation unit.
2394 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2395 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2398 const char *Name = GI->getKeyData();
2399 const DIE *Entity = GI->second;
2401 Asm->OutStreamer.AddComment("DIE offset");
2402 Asm->EmitInt32(Entity->getOffset());
2405 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2406 Asm->OutStreamer.AddComment(
2407 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2408 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2409 Asm->EmitInt8(Desc.toBits());
2412 Asm->OutStreamer.AddComment("External Name");
2413 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2416 Asm->OutStreamer.AddComment("End Mark");
2418 Asm->OutStreamer.EmitLabel(EndLabel);
2422 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2423 const MCSection *PSec =
2424 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2425 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2427 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2428 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2429 for (unsigned i = 0; i != Units.size(); ++i) {
2430 DwarfUnit *TheU = Units[i];
2431 unsigned ID = TheU->getUniqueID();
2433 // Start the dwarf pubtypes section.
2434 Asm->OutStreamer.SwitchSection(PSec);
2436 // Emit a label so we can reference the beginning of this pubtype section.
2438 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2441 Asm->OutStreamer.AddComment("Length of Public Types Info");
2442 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2443 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2444 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2446 Asm->OutStreamer.EmitLabel(BeginLabel);
2448 Asm->OutStreamer.AddComment("DWARF Version");
2449 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2451 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2452 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2454 Asm->OutStreamer.AddComment("Compilation Unit Length");
2455 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2457 // Emit the pubtypes.
2458 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2459 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2462 const char *Name = GI->getKeyData();
2463 const DIE *Entity = GI->second;
2465 Asm->OutStreamer.AddComment("DIE offset");
2466 Asm->EmitInt32(Entity->getOffset());
2469 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2470 Asm->OutStreamer.AddComment(
2471 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2472 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2473 Asm->EmitInt8(Desc.toBits());
2476 Asm->OutStreamer.AddComment("External Name");
2478 // Emit the name with a terminating null byte.
2479 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2482 Asm->OutStreamer.AddComment("End Mark");
2484 Asm->OutStreamer.EmitLabel(EndLabel);
2488 // Emit strings into a string section.
2489 void DwarfFile::emitStrings(const MCSection *StrSection,
2490 const MCSection *OffsetSection = NULL,
2491 const MCSymbol *StrSecSym = NULL) {
2493 if (StringPool.empty())
2496 // Start the dwarf str section.
2497 Asm->OutStreamer.SwitchSection(StrSection);
2499 // Get all of the string pool entries and put them in an array by their ID so
2500 // we can sort them.
2502 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2505 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2506 I = StringPool.begin(),
2507 E = StringPool.end();
2509 Entries.push_back(std::make_pair(I->second.second, &*I));
2511 array_pod_sort(Entries.begin(), Entries.end());
2513 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2514 // Emit a label for reference from debug information entries.
2515 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2517 // Emit the string itself with a terminating null byte.
2518 Asm->OutStreamer.EmitBytes(
2519 StringRef(Entries[i].second->getKeyData(),
2520 Entries[i].second->getKeyLength() + 1));
2523 // If we've got an offset section go ahead and emit that now as well.
2524 if (OffsetSection) {
2525 Asm->OutStreamer.SwitchSection(OffsetSection);
2526 unsigned offset = 0;
2527 unsigned size = 4; // FIXME: DWARF64 is 8.
2528 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2529 Asm->OutStreamer.EmitIntValue(offset, size);
2530 offset += Entries[i].second->getKeyLength() + 1;
2535 // Emit addresses into the section given.
2536 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2538 if (AddressPool.empty())
2541 // Start the dwarf addr section.
2542 Asm->OutStreamer.SwitchSection(AddrSection);
2544 // Order the address pool entries by ID
2545 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2547 for (AddrPool::iterator I = AddressPool.begin(), E = AddressPool.end();
2549 Entries[I->second.Number] =
2551 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I->first)
2552 : MCSymbolRefExpr::Create(I->first, Asm->OutContext);
2554 for (unsigned i = 0, e = Entries.size(); i != e; ++i)
2555 Asm->OutStreamer.EmitValue(Entries[i],
2556 Asm->getDataLayout().getPointerSize());
2559 // Emit visible names into a debug str section.
2560 void DwarfDebug::emitDebugStr() {
2561 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2562 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2565 // Emit locations into the debug loc section.
2566 void DwarfDebug::emitDebugLoc() {
2567 if (DotDebugLocEntries.empty())
2570 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2571 I = DotDebugLocEntries.begin(),
2572 E = DotDebugLocEntries.end();
2574 DotDebugLocEntry &Entry = *I;
2575 if (I + 1 != DotDebugLocEntries.end())
2579 // Start the dwarf loc section.
2580 Asm->OutStreamer.SwitchSection(
2581 Asm->getObjFileLowering().getDwarfLocSection());
2582 unsigned char Size = Asm->getDataLayout().getPointerSize();
2583 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2585 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2586 I = DotDebugLocEntries.begin(),
2587 E = DotDebugLocEntries.end();
2588 I != E; ++I, ++index) {
2589 DotDebugLocEntry &Entry = *I;
2590 if (Entry.isMerged())
2592 if (Entry.isEmpty()) {
2593 Asm->OutStreamer.EmitIntValue(0, Size);
2594 Asm->OutStreamer.EmitIntValue(0, Size);
2595 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2597 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2598 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2599 DIVariable DV(Entry.getVariable());
2600 Asm->OutStreamer.AddComment("Loc expr size");
2601 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2602 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2603 Asm->EmitLabelDifference(end, begin, 2);
2604 Asm->OutStreamer.EmitLabel(begin);
2605 if (Entry.isInt()) {
2606 DIBasicType BTy(DV.getType());
2607 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2608 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2609 Asm->OutStreamer.AddComment("DW_OP_consts");
2610 Asm->EmitInt8(dwarf::DW_OP_consts);
2611 Asm->EmitSLEB128(Entry.getInt());
2613 Asm->OutStreamer.AddComment("DW_OP_constu");
2614 Asm->EmitInt8(dwarf::DW_OP_constu);
2615 Asm->EmitULEB128(Entry.getInt());
2617 } else if (Entry.isLocation()) {
2618 MachineLocation Loc = Entry.getLoc();
2619 if (!DV.hasComplexAddress())
2621 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2623 // Complex address entry.
2624 unsigned N = DV.getNumAddrElements();
2626 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2627 if (Loc.getOffset()) {
2629 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2630 Asm->OutStreamer.AddComment("DW_OP_deref");
2631 Asm->EmitInt8(dwarf::DW_OP_deref);
2632 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2633 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2634 Asm->EmitSLEB128(DV.getAddrElement(1));
2636 // If first address element is OpPlus then emit
2637 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2638 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2639 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2643 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2646 // Emit remaining complex address elements.
2647 for (; i < N; ++i) {
2648 uint64_t Element = DV.getAddrElement(i);
2649 if (Element == DIBuilder::OpPlus) {
2650 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2651 Asm->EmitULEB128(DV.getAddrElement(++i));
2652 } else if (Element == DIBuilder::OpDeref) {
2654 Asm->EmitInt8(dwarf::DW_OP_deref);
2656 llvm_unreachable("unknown Opcode found in complex address");
2660 // else ... ignore constant fp. There is not any good way to
2661 // to represent them here in dwarf.
2662 Asm->OutStreamer.EmitLabel(end);
2667 struct SymbolCUSorter {
2668 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2669 const MCStreamer &Streamer;
2671 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2672 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2673 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2675 // Symbols with no order assigned should be placed at the end.
2676 // (e.g. section end labels)
2678 IA = (unsigned)(-1);
2680 IB = (unsigned)(-1);
2685 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2686 return (A->getUniqueID() < B->getUniqueID());
2690 const MCSymbol *Start, *End;
2693 // Emit a debug aranges section, containing a CU lookup for any
2694 // address we can tie back to a CU.
2695 void DwarfDebug::emitDebugARanges() {
2696 // Start the dwarf aranges section.
2697 Asm->OutStreamer.SwitchSection(
2698 Asm->getObjFileLowering().getDwarfARangesSection());
2700 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2704 // Build a list of sections used.
2705 std::vector<const MCSection *> Sections;
2706 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2708 const MCSection *Section = it->first;
2709 Sections.push_back(Section);
2712 // Sort the sections into order.
2713 // This is only done to ensure consistent output order across different runs.
2714 std::sort(Sections.begin(), Sections.end(), SectionSort);
2716 // Build a set of address spans, sorted by CU.
2717 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2718 const MCSection *Section = Sections[SecIdx];
2719 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2720 if (List.size() < 2)
2723 // Sort the symbols by offset within the section.
2724 SymbolCUSorter sorter(Asm->OutStreamer);
2725 std::sort(List.begin(), List.end(), sorter);
2727 // If we have no section (e.g. common), just write out
2728 // individual spans for each symbol.
2729 if (Section == NULL) {
2730 for (size_t n = 0; n < List.size(); n++) {
2731 const SymbolCU &Cur = List[n];
2734 Span.Start = Cur.Sym;
2737 Spans[Cur.CU].push_back(Span);
2740 // Build spans between each label.
2741 const MCSymbol *StartSym = List[0].Sym;
2742 for (size_t n = 1; n < List.size(); n++) {
2743 const SymbolCU &Prev = List[n - 1];
2744 const SymbolCU &Cur = List[n];
2746 // Try and build the longest span we can within the same CU.
2747 if (Cur.CU != Prev.CU) {
2749 Span.Start = StartSym;
2751 Spans[Prev.CU].push_back(Span);
2758 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2760 // Build a list of CUs used.
2761 std::vector<DwarfCompileUnit *> CUs;
2762 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2763 DwarfCompileUnit *CU = it->first;
2767 // Sort the CU list (again, to ensure consistent output order).
2768 std::sort(CUs.begin(), CUs.end(), CUSort);
2770 // Emit an arange table for each CU we used.
2771 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2772 DwarfCompileUnit *CU = CUs[CUIdx];
2773 std::vector<ArangeSpan> &List = Spans[CU];
2775 // Emit size of content not including length itself.
2776 unsigned ContentSize =
2777 sizeof(int16_t) + // DWARF ARange version number
2778 sizeof(int32_t) + // Offset of CU in the .debug_info section
2779 sizeof(int8_t) + // Pointer Size (in bytes)
2780 sizeof(int8_t); // Segment Size (in bytes)
2782 unsigned TupleSize = PtrSize * 2;
2784 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2786 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2788 ContentSize += Padding;
2789 ContentSize += (List.size() + 1) * TupleSize;
2791 // For each compile unit, write the list of spans it covers.
2792 Asm->OutStreamer.AddComment("Length of ARange Set");
2793 Asm->EmitInt32(ContentSize);
2794 Asm->OutStreamer.AddComment("DWARF Arange version number");
2795 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2796 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2797 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2798 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2799 Asm->EmitInt8(PtrSize);
2800 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2803 Asm->OutStreamer.EmitFill(Padding, 0xff);
2805 for (unsigned n = 0; n < List.size(); n++) {
2806 const ArangeSpan &Span = List[n];
2807 Asm->EmitLabelReference(Span.Start, PtrSize);
2809 // Calculate the size as being from the span start to it's end.
2811 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2813 // For symbols without an end marker (e.g. common), we
2814 // write a single arange entry containing just that one symbol.
2815 uint64_t Size = SymSize[Span.Start];
2819 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2823 Asm->OutStreamer.AddComment("ARange terminator");
2824 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2825 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2829 // Emit visible names into a debug ranges section.
2830 void DwarfDebug::emitDebugRanges() {
2831 // Start the dwarf ranges section.
2832 Asm->OutStreamer.SwitchSection(
2833 Asm->getObjFileLowering().getDwarfRangesSection());
2835 // Size for our labels.
2836 unsigned char Size = Asm->getDataLayout().getPointerSize();
2838 // Grab the specific ranges for the compile units in the module.
2839 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2843 DwarfCompileUnit *TheCU = I->second;
2845 // Emit a symbol so we can find the beginning of our ranges.
2846 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2848 // Iterate over the misc ranges for the compile units in the module.
2849 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2850 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2851 E = RangeLists.end();
2853 const RangeSpanList &List = *I;
2855 // Emit our symbol so we can find the beginning of the range.
2856 Asm->OutStreamer.EmitLabel(List.getSym());
2858 for (SmallVectorImpl<RangeSpan>::const_iterator
2859 RI = List.getRanges().begin(),
2860 RE = List.getRanges().end();
2862 const RangeSpan &Range = *RI;
2863 const MCSymbol *Begin = Range.getStart();
2864 const MCSymbol *End = Range.getEnd();
2865 assert(Begin && "Range without a begin symbol?");
2866 assert(End && "Range without an end symbol?");
2867 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2868 Asm->OutStreamer.EmitSymbolValue(End, Size);
2871 // And terminate the list with two 0 values.
2872 Asm->OutStreamer.EmitIntValue(0, Size);
2873 Asm->OutStreamer.EmitIntValue(0, Size);
2876 // Now emit a range for the CU itself.
2877 if (useCURanges()) {
2878 Asm->OutStreamer.EmitLabel(
2879 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2880 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2881 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2882 RangeSpan Range = Ranges[i];
2883 const MCSymbol *Begin = Range.getStart();
2884 const MCSymbol *End = Range.getEnd();
2885 assert(Begin && "Range without a begin symbol?");
2886 assert(End && "Range without an end symbol?");
2887 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2888 Asm->OutStreamer.EmitSymbolValue(End, Size);
2890 // And terminate the list with two 0 values.
2891 Asm->OutStreamer.EmitIntValue(0, Size);
2892 Asm->OutStreamer.EmitIntValue(0, Size);
2897 // DWARF5 Experimental Separate Dwarf emitters.
2899 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2901 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2902 U->getCUNode().getSplitDebugFilename());
2904 // Relocate to the beginning of the addr_base section, else 0 for the
2905 // beginning of the one for this compile unit.
2906 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2907 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2909 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2911 if (!CompilationDir.empty())
2912 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2914 addGnuPubAttributes(NewU, Die);
2916 SkeletonHolder.addUnit(NewU);
2919 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2920 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2921 // DW_AT_ranges_base, DW_AT_addr_base.
2922 // TODO: Implement DW_AT_ranges_base.
2923 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2925 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2926 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2927 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2928 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2929 DwarfInfoSectionSym);
2931 NewCU->initStmtList(DwarfLineSectionSym);
2933 initSkeletonUnit(CU, Die, NewCU);
2938 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2940 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2941 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2942 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2944 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2945 DwarfTypeUnit *NewTU =
2946 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2947 NewTU->setTypeSignature(TU->getTypeSignature());
2948 NewTU->setType(NULL);
2950 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2951 CU.applyStmtList(*Die);
2953 initSkeletonUnit(TU, Die, NewTU);
2957 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2958 // compile units that would normally be in debug_info.
2959 void DwarfDebug::emitDebugInfoDWO() {
2960 assert(useSplitDwarf() && "No split dwarf debug info?");
2961 InfoHolder.emitUnits(this,
2962 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2963 DwarfAbbrevDWOSectionSym);
2966 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2967 // abbreviations for the .debug_info.dwo section.
2968 void DwarfDebug::emitDebugAbbrevDWO() {
2969 assert(useSplitDwarf() && "No split dwarf?");
2970 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2973 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2974 // string section and is identical in format to traditional .debug_str
2976 void DwarfDebug::emitDebugStrDWO() {
2977 assert(useSplitDwarf() && "No split dwarf?");
2978 const MCSection *OffSec =
2979 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2980 const MCSymbol *StrSym = DwarfStrSectionSym;
2981 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2985 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2986 StringRef Identifier, DIE *RefDie,
2987 DICompositeType CTy) {
2988 // Flag the type unit reference as a declaration so that if it contains
2989 // members (implicit special members, static data member definitions, member
2990 // declarations for definitions in this CU, etc) consumers don't get confused
2991 // and think this is a full definition.
2992 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2994 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2996 CU.addDIETypeSignature(RefDie, *TU);
3000 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3001 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
3002 UnitDie, CU, Asm, this, &InfoHolder);
3004 InfoHolder.addUnit(NewTU);
3006 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3010 Hash.update(Identifier);
3011 // ... take the least significant 8 bytes and return those. Our MD5
3012 // implementation always returns its results in little endian, swap bytes
3014 MD5::MD5Result Result;
3016 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3017 NewTU->setTypeSignature(Signature);
3018 if (useSplitDwarf())
3019 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3021 CU.applyStmtList(*UnitDie);
3023 NewTU->setType(NewTU->createTypeDIE(CTy));
3027 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3028 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3030 CU.addDIETypeSignature(RefDie, *NewTU);