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"),
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 static cl::opt<DefaultOnOff>
87 SplitDwarf("split-dwarf", cl::Hidden,
88 cl::desc("Output DWARF5 split debug info."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 static cl::opt<DefaultOnOff>
95 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
96 cl::desc("Generate DWARF pubnames and pubtypes sections"),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 static cl::opt<unsigned>
103 DwarfVersionNumber("dwarf-version", cl::Hidden,
104 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
107 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
108 cl::desc("Generate DW_AT_ranges for compile units"),
111 static const char *const DWARFGroupName = "DWARF Emission";
112 static const char *const DbgTimerName = "DWARF Debug Writer";
114 //===----------------------------------------------------------------------===//
118 /// resolve - Look in the DwarfDebug map for the MDNode that
119 /// corresponds to the reference.
120 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
121 return DD->resolve(Ref);
124 DIType DbgVariable::getType() const {
125 DIType Ty = Var.getType();
126 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
127 // addresses instead.
128 if (Var.isBlockByrefVariable()) {
129 /* Byref variables, in Blocks, are declared by the programmer as
130 "SomeType VarName;", but the compiler creates a
131 __Block_byref_x_VarName struct, and gives the variable VarName
132 either the struct, or a pointer to the struct, as its type. This
133 is necessary for various behind-the-scenes things the compiler
134 needs to do with by-reference variables in blocks.
136 However, as far as the original *programmer* is concerned, the
137 variable should still have type 'SomeType', as originally declared.
139 The following function dives into the __Block_byref_x_VarName
140 struct to find the original type of the variable. This will be
141 passed back to the code generating the type for the Debug
142 Information Entry for the variable 'VarName'. 'VarName' will then
143 have the original type 'SomeType' in its debug information.
145 The original type 'SomeType' will be the type of the field named
146 'VarName' inside the __Block_byref_x_VarName struct.
148 NOTE: In order for this to not completely fail on the debugger
149 side, the Debug Information Entry for the variable VarName needs to
150 have a DW_AT_location that tells the debugger how to unwind through
151 the pointers and __Block_byref_x_VarName struct to find the actual
152 value of the variable. The function addBlockByrefType does this. */
154 uint16_t tag = Ty.getTag();
156 if (tag == dwarf::DW_TAG_pointer_type)
157 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
159 DIArray Elements = DICompositeType(subType).getTypeArray();
160 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
161 DIDerivedType DT(Elements.getElement(i));
162 if (getName() == DT.getName())
163 return (resolve(DT.getTypeDerivedFrom()));
169 } // end llvm namespace
171 /// Return Dwarf Version by checking module flags.
172 static unsigned getDwarfVersionFromModule(const Module *M) {
173 Value *Val = M->getModuleFlag("Dwarf Version");
175 return dwarf::DWARF_VERSION;
176 return cast<ConstantInt>(Val)->getZExtValue();
179 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
180 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
181 PrevLabel(NULL), GlobalRangeCount(0),
182 InfoHolder(A, "info_string", DIEValueAllocator),
183 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
187 DwarfAddrSectionSym = 0;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
189 FunctionBeginSym = FunctionEndSym = 0;
193 // Turn on accelerator tables for Darwin by default, pubnames by
194 // default for non-Darwin, and handle split dwarf.
195 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
197 if (DwarfAccelTables == Default)
198 HasDwarfAccelTables = IsDarwin;
200 HasDwarfAccelTables = DwarfAccelTables == Enable;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable;
207 if (DwarfPubSections == Default)
208 HasDwarfPubSections = !IsDarwin;
210 HasDwarfPubSections = DwarfPubSections == Enable;
212 DwarfVersion = DwarfVersionNumber
214 : getDwarfVersionFromModule(MMI->getModule());
217 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
222 // Switch to the specified MCSection and emit an assembler
223 // temporary label to it if SymbolStem is specified.
224 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
225 const char *SymbolStem = 0) {
226 Asm->OutStreamer.SwitchSection(Section);
230 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
231 Asm->OutStreamer.EmitLabel(TmpSym);
235 DwarfFile::~DwarfFile() {
236 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
241 MCSymbol *DwarfFile::getStringPoolSym() {
242 return Asm->GetTempSymbol(StringPref);
245 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
246 std::pair<MCSymbol *, unsigned> &Entry =
247 StringPool.GetOrCreateValue(Str).getValue();
251 Entry.second = NextStringPoolNumber++;
252 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
255 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
256 std::pair<MCSymbol *, unsigned> &Entry =
257 StringPool.GetOrCreateValue(Str).getValue();
261 Entry.second = NextStringPoolNumber++;
262 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
266 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
267 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
270 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
271 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
272 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
274 ++NextAddrPoolNumber;
275 return P.first->second;
278 // Define a unique number for the abbreviation.
280 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
281 // Check the set for priors.
282 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
284 // If it's newly added.
285 if (InSet == &Abbrev) {
286 // Add to abbreviation list.
287 Abbreviations.push_back(&Abbrev);
289 // Assign the vector position + 1 as its number.
290 Abbrev.setNumber(Abbreviations.size());
292 // Assign existing abbreviation number.
293 Abbrev.setNumber(InSet->getNumber());
297 static bool isObjCClass(StringRef Name) {
298 return Name.startswith("+") || Name.startswith("-");
301 static bool hasObjCCategory(StringRef Name) {
302 if (!isObjCClass(Name))
305 return Name.find(") ") != StringRef::npos;
308 static void getObjCClassCategory(StringRef In, StringRef &Class,
309 StringRef &Category) {
310 if (!hasObjCCategory(In)) {
311 Class = In.slice(In.find('[') + 1, In.find(' '));
316 Class = In.slice(In.find('[') + 1, In.find('('));
317 Category = In.slice(In.find('[') + 1, In.find(' '));
321 static StringRef getObjCMethodName(StringRef In) {
322 return In.slice(In.find(' ') + 1, In.find(']'));
325 // Helper for sorting sections into a stable output order.
326 static bool SectionSort(const MCSection *A, const MCSection *B) {
327 std::string LA = (A ? A->getLabelBeginName() : "");
328 std::string LB = (B ? B->getLabelBeginName() : "");
332 // Add the various names to the Dwarf accelerator table names.
333 // TODO: Determine whether or not we should add names for programs
334 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
335 // is only slightly different than the lookup of non-standard ObjC names.
336 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
337 if (!SP.isDefinition())
339 TheU->addAccelName(SP.getName(), Die);
341 // If the linkage name is different than the name, go ahead and output
342 // that as well into the name table.
343 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
344 TheU->addAccelName(SP.getLinkageName(), Die);
346 // If this is an Objective-C selector name add it to the ObjC accelerator
348 if (isObjCClass(SP.getName())) {
349 StringRef Class, Category;
350 getObjCClassCategory(SP.getName(), Class, Category);
351 TheU->addAccelObjC(Class, Die);
353 TheU->addAccelObjC(Category, Die);
354 // Also add the base method name to the name table.
355 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
359 /// isSubprogramContext - Return true if Context is either a subprogram
360 /// or another context nested inside a subprogram.
361 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
364 DIDescriptor D(Context);
365 if (D.isSubprogram())
368 return isSubprogramContext(resolve(DIType(Context).getContext()));
372 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
373 // and DW_AT_high_pc attributes. If there are global variables in this
374 // scope then create and insert DIEs for these variables.
375 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
377 DIE *SPDie = SPCU->getDIE(SP);
379 assert(SPDie && "Unable to find subprogram DIE!");
381 // If we're updating an abstract DIE, then we will be adding the children and
382 // object pointer later on. But what we don't want to do is process the
383 // concrete DIE twice.
384 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
385 // Pick up abstract subprogram DIE.
387 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
388 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
390 DISubprogram SPDecl = SP.getFunctionDeclaration();
391 if (!SPDecl.isSubprogram()) {
392 // There is not any need to generate specification DIE for a function
393 // defined at compile unit level. If a function is defined inside another
394 // function then gdb prefers the definition at top level and but does not
395 // expect specification DIE in parent function. So avoid creating
396 // specification DIE for a function defined inside a function.
397 DIScope SPContext = resolve(SP.getContext());
398 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
399 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
400 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
403 DICompositeType SPTy = SP.getType();
404 DIArray Args = SPTy.getTypeArray();
405 uint16_t SPTag = SPTy.getTag();
406 if (SPTag == dwarf::DW_TAG_subroutine_type)
407 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
409 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
410 DIType ATy(Args.getElement(i));
411 SPCU->addType(Arg, ATy);
412 if (ATy.isArtificial())
413 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
414 if (ATy.isObjectPointer())
415 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
417 DIE *SPDeclDie = SPDie;
418 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
419 *SPCU->getUnitDie());
420 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
425 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
426 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
428 // Add this range to the list of ranges for the CU.
429 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
430 SPCU->addRange(llvm_move(Span));
432 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
433 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
434 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
436 // Add name to the name table, we do this here because we're guaranteed
437 // to have concrete versions of our DW_TAG_subprogram nodes.
438 addSubprogramNames(SPCU, SP, SPDie);
443 /// Check whether we should create a DIE for the given Scope, return true
444 /// if we don't create a DIE (the corresponding DIE is null).
445 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
446 if (Scope->isAbstractScope())
449 // We don't create a DIE if there is no Range.
450 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
454 if (Ranges.size() > 1)
457 // We don't create a DIE if we have a single Range and the end label
459 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
460 MCSymbol *End = getLabelAfterInsn(RI->second);
464 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
465 dwarf::Attribute A, const MCSymbol *L,
466 const MCSymbol *Sec) {
467 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
468 U->addSectionLabel(D, A, L);
470 U->addSectionDelta(D, A, L, Sec);
473 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
474 const SmallVectorImpl<InsnRange> &Range) {
475 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
476 // emitting it appropriately.
477 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
478 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
479 DwarfDebugRangeSectionSym);
481 RangeSpanList List(RangeSym);
482 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
485 RangeSpan Span(getLabelBeforeInsn(RI->first),
486 getLabelAfterInsn(RI->second));
487 List.addRange(llvm_move(Span));
490 // Add the range list to the set of ranges to be emitted.
491 TheCU->addRangeList(llvm_move(List));
494 // Construct new DW_TAG_lexical_block for this scope and attach
495 // DW_AT_low_pc/DW_AT_high_pc labels.
496 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
497 LexicalScope *Scope) {
498 if (isLexicalScopeDIENull(Scope))
501 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
502 if (Scope->isAbstractScope())
505 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
507 // If we have multiple ranges, emit them into the range section.
508 if (ScopeRanges.size() > 1) {
509 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
513 // Construct the address range for this DIE.
514 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
515 MCSymbol *Start = getLabelBeforeInsn(RI->first);
516 MCSymbol *End = getLabelAfterInsn(RI->second);
517 assert(End && "End label should not be null!");
519 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
520 assert(End->isDefined() && "Invalid end label for an inlined scope!");
522 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
523 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
528 // This scope represents inlined body of a function. Construct DIE to
529 // represent this concrete inlined copy of the function.
530 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
531 LexicalScope *Scope) {
532 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
533 assert(!ScopeRanges.empty() &&
534 "LexicalScope does not have instruction markers!");
536 if (!Scope->getScopeNode())
538 DIScope DS(Scope->getScopeNode());
539 DISubprogram InlinedSP = getDISubprogram(DS);
540 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
542 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
546 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
547 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
549 // If we have multiple ranges, emit them into the range section.
550 if (ScopeRanges.size() > 1)
551 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
553 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
554 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
555 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
557 if (StartLabel == 0 || EndLabel == 0)
558 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
560 assert(StartLabel->isDefined() &&
561 "Invalid starting label for an inlined scope!");
562 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
564 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
565 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
568 InlinedSubprogramDIEs.insert(OriginDIE);
570 // Add the call site information to the DIE.
571 DILocation DL(Scope->getInlinedAt());
572 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
573 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
574 TheCU->getUniqueID()));
575 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
577 // Add name to the name table, we do this here because we're guaranteed
578 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
579 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
584 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
586 SmallVectorImpl<DIE *> &Children) {
587 DIE *ObjectPointer = NULL;
589 // Collect arguments for current function.
590 if (LScopes.isCurrentFunctionScope(Scope))
591 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
592 if (DbgVariable *ArgDV = CurrentFnArguments[i])
594 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
595 Children.push_back(Arg);
596 if (ArgDV->isObjectPointer())
600 // Collect lexical scope children first.
601 const SmallVectorImpl<DbgVariable *> &Variables =
602 ScopeVariables.lookup(Scope);
603 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
604 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
605 Scope->isAbstractScope())) {
606 Children.push_back(Variable);
607 if (Variables[i]->isObjectPointer())
608 ObjectPointer = Variable;
610 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
611 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
612 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
613 Children.push_back(Nested);
614 return ObjectPointer;
617 // Construct a DIE for this scope.
618 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
619 LexicalScope *Scope) {
620 if (!Scope || !Scope->getScopeNode())
623 DIScope DS(Scope->getScopeNode());
625 SmallVector<DIE *, 8> Children;
626 DIE *ObjectPointer = NULL;
627 bool ChildrenCreated = false;
629 // We try to create the scope DIE first, then the children DIEs. This will
630 // avoid creating un-used children then removing them later when we find out
631 // the scope DIE is null.
632 DIE *ScopeDIE = NULL;
633 if (Scope->getInlinedAt())
634 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
635 else if (DS.isSubprogram()) {
636 ProcessedSPNodes.insert(DS);
637 if (Scope->isAbstractScope()) {
638 ScopeDIE = TheCU->getDIE(DS);
639 // Note down abstract DIE.
641 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
643 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
645 // Early exit when we know the scope DIE is going to be null.
646 if (isLexicalScopeDIENull(Scope))
649 // We create children here when we know the scope DIE is not going to be
650 // null and the children will be added to the scope DIE.
651 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
652 ChildrenCreated = true;
654 // There is no need to emit empty lexical block DIE.
655 std::pair<ImportedEntityMap::const_iterator,
656 ImportedEntityMap::const_iterator> Range =
658 ScopesWithImportedEntities.begin(),
659 ScopesWithImportedEntities.end(),
660 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
662 if (Children.empty() && Range.first == Range.second)
664 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
665 assert(ScopeDIE && "Scope DIE should not be null.");
666 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
668 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
672 assert(Children.empty() &&
673 "We create children only when the scope DIE is not null.");
676 if (!ChildrenCreated)
677 // We create children when the scope DIE is not null.
678 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
681 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
684 ScopeDIE->addChild(*I);
686 if (DS.isSubprogram() && ObjectPointer != NULL)
687 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
692 // Look up the source id with the given directory and source file names.
693 // If none currently exists, create a new id and insert it in the
694 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
696 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
698 // If we use .loc in assembly, we can't separate .file entries according to
699 // compile units. Thus all files will belong to the default compile unit.
701 // FIXME: add a better feature test than hasRawTextSupport. Even better,
702 // extend .file to support this.
703 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
706 // If FE did not provide a file name, then assume stdin.
707 if (FileName.empty())
708 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
710 // TODO: this might not belong here. See if we can factor this better.
711 if (DirName == CompilationDir)
714 // FileIDCUMap stores the current ID for the given compile unit.
715 unsigned SrcId = FileIDCUMap[CUID] + 1;
717 // We look up the CUID/file/dir by concatenating them with a zero byte.
718 SmallString<128> NamePair;
719 NamePair += utostr(CUID);
722 NamePair += '\0'; // Zero bytes are not allowed in paths.
723 NamePair += FileName;
725 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
726 if (Ent.getValue() != SrcId)
727 return Ent.getValue();
729 FileIDCUMap[CUID] = SrcId;
730 // Print out a .file directive to specify files for .loc directives.
731 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
736 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
737 if (!GenerateGnuPubSections)
740 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
741 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
742 DwarfGnuPubNamesSectionSym);
744 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
745 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
746 DwarfGnuPubTypesSectionSym);
749 // Create new DwarfCompileUnit for the given metadata node with tag
750 // DW_TAG_compile_unit.
751 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
752 StringRef FN = DIUnit.getFilename();
753 CompilationDir = DIUnit.getDirectory();
755 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
756 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
757 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
758 InfoHolder.addUnit(NewCU);
760 FileIDCUMap[NewCU->getUniqueID()] = 0;
761 // Call this to emit a .file directive if it wasn't emitted for the source
762 // file this CU comes from yet.
763 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
765 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
766 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
767 DIUnit.getLanguage());
768 NewCU->addString(Die, dwarf::DW_AT_name, FN);
770 // Define start line table label for each Compile Unit.
771 MCSymbol *LineTableStartSym =
772 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
773 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
774 NewCU->getUniqueID());
776 // Use a single line table if we are using .loc and generating assembly.
778 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
779 (NewCU->getUniqueID() == 0);
781 if (!useSplitDwarf()) {
782 // DW_AT_stmt_list is a offset of line number information for this
783 // compile unit in debug_line section. For split dwarf this is
784 // left in the skeleton CU and so not included.
785 // The line table entries are not always emitted in assembly, so it
786 // is not okay to use line_table_start here.
787 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
788 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
789 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
790 : LineTableStartSym);
791 else if (UseTheFirstCU)
792 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
794 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
795 DwarfLineSectionSym);
797 // If we're using split dwarf the compilation dir is going to be in the
798 // skeleton CU and so we don't need to duplicate it here.
799 if (!CompilationDir.empty())
800 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
802 addGnuPubAttributes(NewCU, Die);
805 if (DIUnit.isOptimized())
806 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
808 StringRef Flags = DIUnit.getFlags();
810 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
812 if (unsigned RVer = DIUnit.getRunTimeVersion())
813 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
814 dwarf::DW_FORM_data1, RVer);
819 if (useSplitDwarf()) {
820 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
821 DwarfInfoDWOSectionSym);
822 NewCU->setSkeleton(constructSkeletonCU(NewCU));
824 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
825 DwarfInfoSectionSym);
827 CUMap.insert(std::make_pair(DIUnit, NewCU));
828 CUDieMap.insert(std::make_pair(Die, NewCU));
832 // Construct subprogram DIE.
833 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
835 // FIXME: We should only call this routine once, however, during LTO if a
836 // program is defined in multiple CUs we could end up calling it out of
837 // beginModule as we walk the CUs.
839 DwarfCompileUnit *&CURef = SPMap[N];
845 if (!SP.isDefinition())
846 // This is a method declaration which will be handled while constructing
850 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
852 // Expose as a global name.
853 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
856 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
858 DIImportedEntity Module(N);
859 if (!Module.Verify())
861 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
862 constructImportedEntityDIE(TheCU, Module, D);
865 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
866 const MDNode *N, DIE *Context) {
867 DIImportedEntity Module(N);
868 if (!Module.Verify())
870 return constructImportedEntityDIE(TheCU, Module, Context);
873 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
874 const DIImportedEntity &Module,
876 assert(Module.Verify() &&
877 "Use one of the MDNode * overloads to handle invalid metadata");
878 assert(Context && "Should always have a context for an imported_module");
879 DIE *IMDie = new DIE(Module.getTag());
880 TheCU->insertDIE(Module, IMDie);
882 DIDescriptor Entity = Module.getEntity();
883 if (Entity.isNameSpace())
884 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
885 else if (Entity.isSubprogram())
886 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
887 else if (Entity.isType())
888 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
890 EntityDie = TheCU->getDIE(Entity);
891 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
892 Module.getContext().getDirectory(),
893 TheCU->getUniqueID());
894 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
895 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
896 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
897 StringRef Name = Module.getName();
899 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
900 Context->addChild(IMDie);
903 // Emit all Dwarf sections that should come prior to the content. Create
904 // global DIEs and emit initial debug info sections. This is invoked by
905 // the target AsmPrinter.
906 void DwarfDebug::beginModule() {
907 if (DisableDebugInfoPrinting)
910 const Module *M = MMI->getModule();
912 // If module has named metadata anchors then use them, otherwise scan the
913 // module using debug info finder to collect debug info.
914 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
917 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
919 // Emit initial sections so we can reference labels later.
922 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
923 DICompileUnit CUNode(CU_Nodes->getOperand(i));
924 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
925 DIArray ImportedEntities = CUNode.getImportedEntities();
926 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
927 ScopesWithImportedEntities.push_back(std::make_pair(
928 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
929 ImportedEntities.getElement(i)));
930 std::sort(ScopesWithImportedEntities.begin(),
931 ScopesWithImportedEntities.end(), less_first());
932 DIArray GVs = CUNode.getGlobalVariables();
933 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
934 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
935 DIArray SPs = CUNode.getSubprograms();
936 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
937 constructSubprogramDIE(CU, SPs.getElement(i));
938 DIArray EnumTypes = CUNode.getEnumTypes();
939 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
940 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
941 DIArray RetainedTypes = CUNode.getRetainedTypes();
942 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
943 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
944 // Emit imported_modules last so that the relevant context is already
946 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
947 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
950 // Tell MMI that we have debug info.
951 MMI->setDebugInfoAvailability(true);
953 // Prime section data.
954 SectionMap[Asm->getObjFileLowering().getTextSection()];
957 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
958 void DwarfDebug::computeInlinedDIEs() {
959 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
960 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
961 AE = InlinedSubprogramDIEs.end();
964 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
966 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
967 AE = AbstractSPDies.end();
969 DIE *ISP = AI->second;
970 if (InlinedSubprogramDIEs.count(ISP))
972 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
976 // Collect info for variables that were optimized out.
977 void DwarfDebug::collectDeadVariables() {
978 const Module *M = MMI->getModule();
980 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
981 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
982 DICompileUnit TheCU(CU_Nodes->getOperand(i));
983 DIArray Subprograms = TheCU.getSubprograms();
984 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
985 DISubprogram SP(Subprograms.getElement(i));
986 if (ProcessedSPNodes.count(SP) != 0)
988 if (!SP.isSubprogram())
990 if (!SP.isDefinition())
992 DIArray Variables = SP.getVariables();
993 if (Variables.getNumElements() == 0)
996 // Construct subprogram DIE and add variables DIEs.
997 DwarfCompileUnit *SPCU =
998 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
999 assert(SPCU && "Unable to find Compile Unit!");
1000 // FIXME: See the comment in constructSubprogramDIE about duplicate
1002 constructSubprogramDIE(SPCU, SP);
1003 DIE *SPDIE = SPCU->getDIE(SP);
1004 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1005 DIVariable DV(Variables.getElement(vi));
1006 if (!DV.isVariable())
1008 DbgVariable NewVar(DV, NULL, this);
1009 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1010 SPDIE->addChild(VariableDIE);
1017 void DwarfDebug::finalizeModuleInfo() {
1018 // Collect info for variables that were optimized out.
1019 collectDeadVariables();
1021 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1022 computeInlinedDIEs();
1024 // Handle anything that needs to be done on a per-unit basis after
1025 // all other generation.
1026 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1027 E = getUnits().end();
1029 DwarfUnit *TheU = *I;
1030 // Emit DW_AT_containing_type attribute to connect types with their
1031 // vtable holding type.
1032 TheU->constructContainingTypeDIEs();
1034 // Add CU specific attributes if we need to add any.
1035 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1036 // If we're splitting the dwarf out now that we've got the entire
1037 // CU then add the dwo id to it.
1038 DwarfCompileUnit *SkCU =
1039 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1040 if (useSplitDwarf()) {
1041 // This should be a unique identifier when we want to build .dwp files.
1043 if (GenerateCUHash) {
1045 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1047 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1048 dwarf::DW_FORM_data8, ID);
1049 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1050 dwarf::DW_FORM_data8, ID);
1053 // If we've requested ranges and have them emit a DW_AT_ranges attribute
1054 // on the unit that will remain in the .o file, otherwise add a
1056 // FIXME: Also add a high pc if we can.
1057 // FIXME: We should use ranges if we have multiple compile units.
1058 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1059 if (DwarfCURanges && TheU->getRanges().size())
1060 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1061 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1062 DwarfDebugRangeSectionSym);
1064 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1069 // Compute DIE offsets and sizes.
1070 InfoHolder.computeSizeAndOffsets();
1071 if (useSplitDwarf())
1072 SkeletonHolder.computeSizeAndOffsets();
1075 void DwarfDebug::endSections() {
1076 // Filter labels by section.
1077 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1078 const SymbolCU &SCU = ArangeLabels[n];
1079 if (SCU.Sym->isInSection()) {
1080 // Make a note of this symbol and it's section.
1081 const MCSection *Section = &SCU.Sym->getSection();
1082 if (!Section->getKind().isMetadata())
1083 SectionMap[Section].push_back(SCU);
1085 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1086 // appear in the output. This sucks as we rely on sections to build
1087 // arange spans. We can do it without, but it's icky.
1088 SectionMap[NULL].push_back(SCU);
1092 // Build a list of sections used.
1093 std::vector<const MCSection *> Sections;
1094 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1096 const MCSection *Section = it->first;
1097 Sections.push_back(Section);
1100 // Sort the sections into order.
1101 // This is only done to ensure consistent output order across different runs.
1102 std::sort(Sections.begin(), Sections.end(), SectionSort);
1104 // Add terminating symbols for each section.
1105 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1106 const MCSection *Section = Sections[ID];
1107 MCSymbol *Sym = NULL;
1110 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1111 // if we know the section name up-front. For user-created sections, the
1113 // label may not be valid to use as a label. (section names can use a
1115 // set of characters on some systems)
1116 Sym = Asm->GetTempSymbol("debug_end", ID);
1117 Asm->OutStreamer.SwitchSection(Section);
1118 Asm->OutStreamer.EmitLabel(Sym);
1121 // Insert a final terminator.
1122 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1126 // Emit all Dwarf sections that should come after the content.
1127 void DwarfDebug::endModule() {
1134 // End any existing sections.
1135 // TODO: Does this need to happen?
1138 // Finalize the debug info for the module.
1139 finalizeModuleInfo();
1143 // Emit all the DIEs into a debug info section.
1146 // Corresponding abbreviations into a abbrev section.
1147 emitAbbreviations();
1149 // Emit info into a debug loc section.
1152 // Emit info into a debug aranges section.
1155 // Emit info into a debug ranges section.
1158 if (useSplitDwarf()) {
1161 emitDebugAbbrevDWO();
1162 // Emit DWO addresses.
1163 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1166 // Emit info into the dwarf accelerator table sections.
1167 if (useDwarfAccelTables()) {
1170 emitAccelNamespaces();
1174 // Emit the pubnames and pubtypes sections if requested.
1175 if (HasDwarfPubSections) {
1176 emitDebugPubNames(GenerateGnuPubSections);
1177 emitDebugPubTypes(GenerateGnuPubSections);
1183 // Reset these for the next Module if we have one.
1187 // Find abstract variable, if any, associated with Var.
1188 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1189 DebugLoc ScopeLoc) {
1190 LLVMContext &Ctx = DV->getContext();
1191 // More then one inlined variable corresponds to one abstract variable.
1192 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1193 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1195 return AbsDbgVariable;
1197 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1201 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1202 addScopeVariable(Scope, AbsDbgVariable);
1203 AbstractVariables[Var] = AbsDbgVariable;
1204 return AbsDbgVariable;
1207 // If Var is a current function argument then add it to CurrentFnArguments list.
1208 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1209 if (!LScopes.isCurrentFunctionScope(Scope))
1211 DIVariable DV = Var->getVariable();
1212 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1214 unsigned ArgNo = DV.getArgNumber();
1218 size_t Size = CurrentFnArguments.size();
1220 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1221 // llvm::Function argument size is not good indicator of how many
1222 // arguments does the function have at source level.
1224 CurrentFnArguments.resize(ArgNo * 2);
1225 CurrentFnArguments[ArgNo - 1] = Var;
1229 // Collect variable information from side table maintained by MMI.
1230 void DwarfDebug::collectVariableInfoFromMMITable(
1231 SmallPtrSet<const MDNode *, 16> &Processed) {
1232 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1233 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1236 const MDNode *Var = VI->first;
1239 Processed.insert(Var);
1241 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1243 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1245 // If variable scope is not found then skip this variable.
1249 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1250 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1251 RegVar->setFrameIndex(VP.first);
1252 if (!addCurrentFnArgument(RegVar, Scope))
1253 addScopeVariable(Scope, RegVar);
1255 AbsDbgVariable->setFrameIndex(VP.first);
1259 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1261 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1262 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1263 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1264 MI->getOperand(0).getReg() &&
1265 (MI->getOperand(1).isImm() ||
1266 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1269 // Get .debug_loc entry for the instruction range starting at MI.
1270 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1271 const MCSymbol *FLabel,
1272 const MCSymbol *SLabel,
1273 const MachineInstr *MI) {
1274 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1276 assert(MI->getNumOperands() == 3);
1277 if (MI->getOperand(0).isReg()) {
1278 MachineLocation MLoc;
1279 // If the second operand is an immediate, this is a
1280 // register-indirect address.
1281 if (!MI->getOperand(1).isImm())
1282 MLoc.set(MI->getOperand(0).getReg());
1284 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1285 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1287 if (MI->getOperand(0).isImm())
1288 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1289 if (MI->getOperand(0).isFPImm())
1290 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1291 if (MI->getOperand(0).isCImm())
1292 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1294 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1297 // Find variables for each lexical scope.
1299 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1301 // Grab the variable info that was squirreled away in the MMI side-table.
1302 collectVariableInfoFromMMITable(Processed);
1304 for (SmallVectorImpl<const MDNode *>::const_iterator
1305 UVI = UserVariables.begin(),
1306 UVE = UserVariables.end();
1307 UVI != UVE; ++UVI) {
1308 const MDNode *Var = *UVI;
1309 if (Processed.count(Var))
1312 // History contains relevant DBG_VALUE instructions for Var and instructions
1314 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1315 if (History.empty())
1317 const MachineInstr *MInsn = History.front();
1320 LexicalScope *Scope = NULL;
1321 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1322 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1323 Scope = LScopes.getCurrentFunctionScope();
1324 else if (MDNode *IA = DV.getInlinedAt())
1325 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1327 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1328 // If variable scope is not found then skip this variable.
1332 Processed.insert(DV);
1333 assert(MInsn->isDebugValue() && "History must begin with debug value");
1334 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1335 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1336 if (!addCurrentFnArgument(RegVar, Scope))
1337 addScopeVariable(Scope, RegVar);
1339 AbsVar->setMInsn(MInsn);
1341 // Simplify ranges that are fully coalesced.
1342 if (History.size() <= 1 ||
1343 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1344 RegVar->setMInsn(MInsn);
1348 // Handle multiple DBG_VALUE instructions describing one variable.
1349 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1351 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1352 HI = History.begin(),
1355 const MachineInstr *Begin = *HI;
1356 assert(Begin->isDebugValue() && "Invalid History entry");
1358 // Check if DBG_VALUE is truncating a range.
1359 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1360 !Begin->getOperand(0).getReg())
1363 // Compute the range for a register location.
1364 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1365 const MCSymbol *SLabel = 0;
1368 // If Begin is the last instruction in History then its value is valid
1369 // until the end of the function.
1370 SLabel = FunctionEndSym;
1372 const MachineInstr *End = HI[1];
1373 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1374 << "\t" << *Begin << "\t" << *End << "\n");
1375 if (End->isDebugValue())
1376 SLabel = getLabelBeforeInsn(End);
1378 // End is a normal instruction clobbering the range.
1379 SLabel = getLabelAfterInsn(End);
1380 assert(SLabel && "Forgot label after clobber instruction");
1385 // The value is valid until the next DBG_VALUE or clobber.
1386 DotDebugLocEntries.push_back(
1387 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1389 DotDebugLocEntries.push_back(DotDebugLocEntry());
1392 // Collect info for variables that were optimized out.
1393 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1394 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1395 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1396 DIVariable DV(Variables.getElement(i));
1397 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1399 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1400 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1404 // Return Label preceding the instruction.
1405 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1406 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1407 assert(Label && "Didn't insert label before instruction");
1411 // Return Label immediately following the instruction.
1412 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1413 return LabelsAfterInsn.lookup(MI);
1416 // Process beginning of an instruction.
1417 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1420 // Check if source location changes, but ignore DBG_VALUE locations.
1421 if (!MI->isDebugValue()) {
1422 DebugLoc DL = MI->getDebugLoc();
1423 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1426 if (DL == PrologEndLoc) {
1427 Flags |= DWARF2_FLAG_PROLOGUE_END;
1428 PrologEndLoc = DebugLoc();
1430 if (PrologEndLoc.isUnknown())
1431 Flags |= DWARF2_FLAG_IS_STMT;
1433 if (!DL.isUnknown()) {
1434 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1435 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1437 recordSourceLine(0, 0, 0, 0);
1441 // Insert labels where requested.
1442 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1443 LabelsBeforeInsn.find(MI);
1446 if (I == LabelsBeforeInsn.end())
1449 // Label already assigned.
1454 PrevLabel = MMI->getContext().CreateTempSymbol();
1455 Asm->OutStreamer.EmitLabel(PrevLabel);
1457 I->second = PrevLabel;
1460 // Process end of an instruction.
1461 void DwarfDebug::endInstruction() {
1463 // Don't create a new label after DBG_VALUE instructions.
1464 // They don't generate code.
1465 if (!CurMI->isDebugValue())
1468 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1469 LabelsAfterInsn.find(CurMI);
1473 if (I == LabelsAfterInsn.end())
1476 // Label already assigned.
1480 // We need a label after this instruction.
1482 PrevLabel = MMI->getContext().CreateTempSymbol();
1483 Asm->OutStreamer.EmitLabel(PrevLabel);
1485 I->second = PrevLabel;
1488 // Each LexicalScope has first instruction and last instruction to mark
1489 // beginning and end of a scope respectively. Create an inverse map that list
1490 // scopes starts (and ends) with an instruction. One instruction may start (or
1491 // end) multiple scopes. Ignore scopes that are not reachable.
1492 void DwarfDebug::identifyScopeMarkers() {
1493 SmallVector<LexicalScope *, 4> WorkList;
1494 WorkList.push_back(LScopes.getCurrentFunctionScope());
1495 while (!WorkList.empty()) {
1496 LexicalScope *S = WorkList.pop_back_val();
1498 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1499 if (!Children.empty())
1500 for (SmallVectorImpl<LexicalScope *>::const_iterator
1501 SI = Children.begin(),
1502 SE = Children.end();
1504 WorkList.push_back(*SI);
1506 if (S->isAbstractScope())
1509 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1512 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1515 assert(RI->first && "InsnRange does not have first instruction!");
1516 assert(RI->second && "InsnRange does not have second instruction!");
1517 requestLabelBeforeInsn(RI->first);
1518 requestLabelAfterInsn(RI->second);
1523 // Get MDNode for DebugLoc's scope.
1524 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1525 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1526 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1527 return DL.getScope(Ctx);
1530 // Walk up the scope chain of given debug loc and find line number info
1531 // for the function.
1532 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1533 const MDNode *Scope = getScopeNode(DL, Ctx);
1534 DISubprogram SP = getDISubprogram(Scope);
1535 if (SP.isSubprogram()) {
1536 // Check for number of operands since the compatibility is
1538 if (SP->getNumOperands() > 19)
1539 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1541 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1547 // Gather pre-function debug information. Assumes being called immediately
1548 // after the function entry point has been emitted.
1549 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1552 // If there's no debug info for the function we're not going to do anything.
1553 if (!MMI->hasDebugInfo())
1556 // Grab the lexical scopes for the function, if we don't have any of those
1557 // then we're not going to be able to do anything.
1558 LScopes.initialize(*MF);
1559 if (LScopes.empty())
1562 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1564 // Make sure that each lexical scope will have a begin/end label.
1565 identifyScopeMarkers();
1567 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1568 // belongs to so that we add to the correct per-cu line table in the
1570 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1571 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1572 assert(TheCU && "Unable to find compile unit!");
1573 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1574 // Use a single line table if we are using .loc and generating assembly.
1575 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1577 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1579 // Emit a label for the function so that we have a beginning address.
1580 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1581 // Assumes in correct section after the entry point.
1582 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1584 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1585 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1586 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1588 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1590 bool AtBlockEntry = true;
1591 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1593 const MachineInstr *MI = II;
1595 if (MI->isDebugValue()) {
1596 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1598 // Keep track of user variables.
1600 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1602 // Variable is in a register, we need to check for clobbers.
1603 if (isDbgValueInDefinedReg(MI))
1604 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1606 // Check the history of this variable.
1607 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1608 if (History.empty()) {
1609 UserVariables.push_back(Var);
1610 // The first mention of a function argument gets the FunctionBeginSym
1611 // label, so arguments are visible when breaking at function entry.
1613 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1614 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1615 LabelsBeforeInsn[MI] = FunctionBeginSym;
1617 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1618 const MachineInstr *Prev = History.back();
1619 if (Prev->isDebugValue()) {
1620 // Coalesce identical entries at the end of History.
1621 if (History.size() >= 2 &&
1622 Prev->isIdenticalTo(History[History.size() - 2])) {
1623 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1624 << "\t" << *Prev << "\t"
1625 << *History[History.size() - 2] << "\n");
1629 // Terminate old register assignments that don't reach MI;
1630 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1631 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1632 isDbgValueInDefinedReg(Prev)) {
1633 // Previous register assignment needs to terminate at the end of
1635 MachineBasicBlock::const_iterator LastMI =
1636 PrevMBB->getLastNonDebugInstr();
1637 if (LastMI == PrevMBB->end()) {
1638 // Drop DBG_VALUE for empty range.
1639 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1640 << "\t" << *Prev << "\n");
1642 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1643 // Terminate after LastMI.
1644 History.push_back(LastMI);
1648 History.push_back(MI);
1650 // Not a DBG_VALUE instruction.
1652 AtBlockEntry = false;
1654 // First known non-DBG_VALUE and non-frame setup location marks
1655 // the beginning of the function body.
1656 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1657 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1658 PrologEndLoc = MI->getDebugLoc();
1660 // Check if the instruction clobbers any registers with debug vars.
1661 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1662 MOE = MI->operands_end();
1663 MOI != MOE; ++MOI) {
1664 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1666 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1669 const MDNode *Var = LiveUserVar[Reg];
1672 // Reg is now clobbered.
1673 LiveUserVar[Reg] = 0;
1675 // Was MD last defined by a DBG_VALUE referring to Reg?
1676 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1677 if (HistI == DbgValues.end())
1679 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1680 if (History.empty())
1682 const MachineInstr *Prev = History.back();
1683 // Sanity-check: Register assignments are terminated at the end of
1685 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1687 // Is the variable still in Reg?
1688 if (!isDbgValueInDefinedReg(Prev) ||
1689 Prev->getOperand(0).getReg() != Reg)
1691 // Var is clobbered. Make sure the next instruction gets a label.
1692 History.push_back(MI);
1699 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1701 SmallVectorImpl<const MachineInstr *> &History = I->second;
1702 if (History.empty())
1705 // Make sure the final register assignments are terminated.
1706 const MachineInstr *Prev = History.back();
1707 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1708 const MachineBasicBlock *PrevMBB = Prev->getParent();
1709 MachineBasicBlock::const_iterator LastMI =
1710 PrevMBB->getLastNonDebugInstr();
1711 if (LastMI == PrevMBB->end())
1712 // Drop DBG_VALUE for empty range.
1714 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1715 // Terminate after LastMI.
1716 History.push_back(LastMI);
1719 // Request labels for the full history.
1720 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1721 const MachineInstr *MI = History[i];
1722 if (MI->isDebugValue())
1723 requestLabelBeforeInsn(MI);
1725 requestLabelAfterInsn(MI);
1729 PrevInstLoc = DebugLoc();
1730 PrevLabel = FunctionBeginSym;
1732 // Record beginning of function.
1733 if (!PrologEndLoc.isUnknown()) {
1734 DebugLoc FnStartDL =
1735 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1737 FnStartDL.getLine(), FnStartDL.getCol(),
1738 FnStartDL.getScope(MF->getFunction()->getContext()),
1739 // We'd like to list the prologue as "not statements" but GDB behaves
1740 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1741 DWARF2_FLAG_IS_STMT);
1745 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1746 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1747 DIVariable DV = Var->getVariable();
1748 // Variables with positive arg numbers are parameters.
1749 if (unsigned ArgNum = DV.getArgNumber()) {
1750 // Keep all parameters in order at the start of the variable list to ensure
1751 // function types are correct (no out-of-order parameters)
1753 // This could be improved by only doing it for optimized builds (unoptimized
1754 // builds have the right order to begin with), searching from the back (this
1755 // would catch the unoptimized case quickly), or doing a binary search
1756 // rather than linear search.
1757 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1758 while (I != Vars.end()) {
1759 unsigned CurNum = (*I)->getVariable().getArgNumber();
1760 // A local (non-parameter) variable has been found, insert immediately
1764 // A later indexed parameter has been found, insert immediately before it.
1765 if (CurNum > ArgNum)
1769 Vars.insert(I, Var);
1773 Vars.push_back(Var);
1776 // Gather and emit post-function debug information.
1777 void DwarfDebug::endFunction(const MachineFunction *MF) {
1778 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1779 // though the beginFunction may not be called at all.
1780 // We should handle both cases.
1784 assert(CurFn == MF);
1787 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1792 // Define end label for subprogram.
1793 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1794 // Assumes in correct section after the entry point.
1795 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1796 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1797 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1799 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1800 collectVariableInfo(ProcessedVars);
1802 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1803 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1804 assert(TheCU && "Unable to find compile unit!");
1806 // Construct abstract scopes.
1807 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1808 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1809 LexicalScope *AScope = AList[i];
1810 DISubprogram SP(AScope->getScopeNode());
1811 if (SP.isSubprogram()) {
1812 // Collect info for variables that were optimized out.
1813 DIArray Variables = SP.getVariables();
1814 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1815 DIVariable DV(Variables.getElement(i));
1816 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1818 // Check that DbgVariable for DV wasn't created earlier, when
1819 // findAbstractVariable() was called for inlined instance of DV.
1820 LLVMContext &Ctx = DV->getContext();
1821 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1822 if (AbstractVariables.lookup(CleanDV))
1824 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1825 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1828 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1829 constructScopeDIE(TheCU, AScope);
1832 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1834 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1835 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1838 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1839 E = ScopeVariables.end();
1841 DeleteContainerPointers(I->second);
1842 ScopeVariables.clear();
1843 DeleteContainerPointers(CurrentFnArguments);
1844 UserVariables.clear();
1846 AbstractVariables.clear();
1847 LabelsBeforeInsn.clear();
1848 LabelsAfterInsn.clear();
1853 // Register a source line with debug info. Returns the unique label that was
1854 // emitted and which provides correspondence to the source line list.
1855 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1861 DIDescriptor Scope(S);
1863 if (Scope.isCompileUnit()) {
1864 DICompileUnit CU(S);
1865 Fn = CU.getFilename();
1866 Dir = CU.getDirectory();
1867 } else if (Scope.isFile()) {
1869 Fn = F.getFilename();
1870 Dir = F.getDirectory();
1871 } else if (Scope.isSubprogram()) {
1873 Fn = SP.getFilename();
1874 Dir = SP.getDirectory();
1875 } else if (Scope.isLexicalBlockFile()) {
1876 DILexicalBlockFile DBF(S);
1877 Fn = DBF.getFilename();
1878 Dir = DBF.getDirectory();
1879 } else if (Scope.isLexicalBlock()) {
1880 DILexicalBlock DB(S);
1881 Fn = DB.getFilename();
1882 Dir = DB.getDirectory();
1884 llvm_unreachable("Unexpected scope info");
1886 Src = getOrCreateSourceID(
1887 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1889 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1892 //===----------------------------------------------------------------------===//
1894 //===----------------------------------------------------------------------===//
1896 // Compute the size and offset of a DIE. The offset is relative to start of the
1897 // CU. It returns the offset after laying out the DIE.
1898 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1899 // Get the children.
1900 const std::vector<DIE *> &Children = Die->getChildren();
1902 // Record the abbreviation.
1903 assignAbbrevNumber(Die->getAbbrev());
1905 // Get the abbreviation for this DIE.
1906 const DIEAbbrev &Abbrev = Die->getAbbrev();
1909 Die->setOffset(Offset);
1911 // Start the size with the size of abbreviation code.
1912 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1914 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1915 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1917 // Size the DIE attribute values.
1918 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1919 // Size attribute value.
1920 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1922 // Size the DIE children if any.
1923 if (!Children.empty()) {
1924 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1925 "Children flag not set");
1927 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1928 Offset = computeSizeAndOffset(Children[j], Offset);
1930 // End of children marker.
1931 Offset += sizeof(int8_t);
1934 Die->setSize(Offset - Die->getOffset());
1938 // Compute the size and offset for each DIE.
1939 void DwarfFile::computeSizeAndOffsets() {
1940 // Offset from the first CU in the debug info section is 0 initially.
1941 unsigned SecOffset = 0;
1943 // Iterate over each compile unit and set the size and offsets for each
1944 // DIE within each compile unit. All offsets are CU relative.
1945 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1948 (*I)->setDebugInfoOffset(SecOffset);
1950 // CU-relative offset is reset to 0 here.
1951 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1952 (*I)->getHeaderSize(); // Unit-specific headers
1954 // EndOffset here is CU-relative, after laying out
1955 // all of the CU DIE.
1956 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1957 SecOffset += EndOffset;
1961 // Emit initial Dwarf sections with a label at the start of each one.
1962 void DwarfDebug::emitSectionLabels() {
1963 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1965 // Dwarf sections base addresses.
1966 DwarfInfoSectionSym =
1967 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1968 if (useSplitDwarf())
1969 DwarfInfoDWOSectionSym =
1970 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1971 DwarfAbbrevSectionSym =
1972 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1973 if (useSplitDwarf())
1974 DwarfAbbrevDWOSectionSym = emitSectionSym(
1975 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1976 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1978 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1979 emitSectionSym(Asm, MacroInfo);
1981 DwarfLineSectionSym =
1982 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1983 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1984 if (GenerateGnuPubSections) {
1985 DwarfGnuPubNamesSectionSym =
1986 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1987 DwarfGnuPubTypesSectionSym =
1988 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1989 } else if (HasDwarfPubSections) {
1990 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1991 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1994 DwarfStrSectionSym =
1995 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1996 if (useSplitDwarf()) {
1997 DwarfStrDWOSectionSym =
1998 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1999 DwarfAddrSectionSym =
2000 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2002 DwarfDebugRangeSectionSym =
2003 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2005 DwarfDebugLocSectionSym =
2006 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2009 // Recursively emits a debug information entry.
2010 void DwarfDebug::emitDIE(DIE *Die) {
2011 // Get the abbreviation for this DIE.
2012 const DIEAbbrev &Abbrev = Die->getAbbrev();
2014 // Emit the code (index) for the abbreviation.
2015 if (Asm->isVerbose())
2016 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2017 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2018 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2019 dwarf::TagString(Abbrev.getTag()));
2020 Asm->EmitULEB128(Abbrev.getNumber());
2022 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2023 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2025 // Emit the DIE attribute values.
2026 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2027 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2028 dwarf::Form Form = AbbrevData[i].getForm();
2029 assert(Form && "Too many attributes for DIE (check abbreviation)");
2031 if (Asm->isVerbose())
2032 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2035 case dwarf::DW_AT_abstract_origin:
2036 case dwarf::DW_AT_type:
2037 case dwarf::DW_AT_friend:
2038 case dwarf::DW_AT_specification:
2039 case dwarf::DW_AT_import:
2040 case dwarf::DW_AT_containing_type: {
2041 DIEEntry *E = cast<DIEEntry>(Values[i]);
2042 DIE *Origin = E->getEntry();
2043 unsigned Addr = Origin->getOffset();
2044 if (Form == dwarf::DW_FORM_ref_addr) {
2045 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2046 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2047 // section. Origin->getOffset() returns the offset from start of the
2049 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2050 assert(CU && "CUDie should belong to a CU.");
2051 Addr += CU->getDebugInfoOffset();
2052 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2053 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2054 DIEEntry::getRefAddrSize(Asm));
2056 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2057 CU->getSectionSym(),
2058 DIEEntry::getRefAddrSize(Asm));
2060 // Make sure Origin belong to the same CU.
2061 assert(Die->getUnit() == Origin->getUnit() &&
2062 "The referenced DIE should belong to the same CU in ref4");
2063 Asm->EmitInt32(Addr);
2067 case dwarf::DW_AT_location: {
2068 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2069 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2070 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2072 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2074 Values[i]->EmitValue(Asm, Form);
2078 case dwarf::DW_AT_accessibility: {
2079 if (Asm->isVerbose()) {
2080 DIEInteger *V = cast<DIEInteger>(Values[i]);
2081 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2083 Values[i]->EmitValue(Asm, Form);
2087 // Emit an attribute using the defined form.
2088 Values[i]->EmitValue(Asm, Form);
2093 // Emit the DIE children if any.
2094 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2095 const std::vector<DIE *> &Children = Die->getChildren();
2097 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2098 emitDIE(Children[j]);
2100 Asm->OutStreamer.AddComment("End Of Children Mark");
2105 // Emit the various dwarf units to the unit section USection with
2106 // the abbreviations going into ASection.
2107 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2108 const MCSymbol *ASectionSym) {
2109 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2111 DwarfUnit *TheU = *I;
2112 DIE *Die = TheU->getUnitDie();
2113 const MCSection *USection = TheU->getSection();
2114 Asm->OutStreamer.SwitchSection(USection);
2116 // Emit the compile units header.
2117 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2119 // Emit size of content not including length itself
2120 Asm->OutStreamer.AddComment("Length of Unit");
2121 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2123 TheU->emitHeader(ASection, ASectionSym);
2126 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2130 // Emit the debug info section.
2131 void DwarfDebug::emitDebugInfo() {
2132 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2134 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2135 DwarfAbbrevSectionSym);
2138 // Emit the abbreviation section.
2139 void DwarfDebug::emitAbbreviations() {
2140 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2142 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2145 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2146 // Check to see if it is worth the effort.
2147 if (!Abbreviations.empty()) {
2148 // Start the debug abbrev section.
2149 Asm->OutStreamer.SwitchSection(Section);
2151 // For each abbrevation.
2152 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2153 // Get abbreviation data
2154 const DIEAbbrev *Abbrev = Abbreviations[i];
2156 // Emit the abbrevations code (base 1 index.)
2157 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2159 // Emit the abbreviations data.
2163 // Mark end of abbreviations.
2164 Asm->EmitULEB128(0, "EOM(3)");
2168 // Emit the last address of the section and the end of the line matrix.
2169 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2170 // Define last address of section.
2171 Asm->OutStreamer.AddComment("Extended Op");
2174 Asm->OutStreamer.AddComment("Op size");
2175 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2176 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2177 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2179 Asm->OutStreamer.AddComment("Section end label");
2181 Asm->OutStreamer.EmitSymbolValue(
2182 Asm->GetTempSymbol("section_end", SectionEnd),
2183 Asm->getDataLayout().getPointerSize());
2185 // Mark end of matrix.
2186 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2192 // Emit visible names into a hashed accelerator table section.
2193 void DwarfDebug::emitAccelNames() {
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->getAccelNames();
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, "Names");
2215 Asm->OutStreamer.SwitchSection(
2216 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2217 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2218 Asm->OutStreamer.EmitLabel(SectionBegin);
2220 // Emit the full data.
2221 AT.Emit(Asm, SectionBegin, &InfoHolder);
2224 // Emit objective C classes and categories into a hashed accelerator table
2226 void DwarfDebug::emitAccelObjC() {
2228 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2229 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2230 E = getUnits().end();
2232 DwarfUnit *TheU = *I;
2233 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
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, "ObjC");
2248 Asm->OutStreamer.SwitchSection(
2249 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2250 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2251 Asm->OutStreamer.EmitLabel(SectionBegin);
2253 // Emit the full data.
2254 AT.Emit(Asm, SectionBegin, &InfoHolder);
2257 // Emit namespace dies into a hashed accelerator table.
2258 void DwarfDebug::emitAccelNamespaces() {
2260 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2261 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2262 E = getUnits().end();
2264 DwarfUnit *TheU = *I;
2265 const StringMap<std::vector<const DIE *> > &Names =
2266 TheU->getAccelNamespace();
2267 for (StringMap<std::vector<const DIE *> >::const_iterator
2271 StringRef Name = GI->getKey();
2272 const std::vector<const DIE *> &Entities = GI->second;
2273 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2274 DE = Entities.end();
2276 AT.AddName(Name, *DI);
2280 AT.FinalizeTable(Asm, "namespac");
2281 Asm->OutStreamer.SwitchSection(
2282 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2283 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2284 Asm->OutStreamer.EmitLabel(SectionBegin);
2286 // Emit the full data.
2287 AT.Emit(Asm, SectionBegin, &InfoHolder);
2290 // Emit type dies into a hashed accelerator table.
2291 void DwarfDebug::emitAccelTypes() {
2292 std::vector<DwarfAccelTable::Atom> Atoms;
2294 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2296 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2298 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2299 DwarfAccelTable AT(Atoms);
2300 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2301 E = getUnits().end();
2303 DwarfUnit *TheU = *I;
2304 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2305 TheU->getAccelTypes();
2307 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2311 StringRef Name = GI->getKey();
2312 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2314 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2315 DI = Entities.begin(),
2316 DE = Entities.end();
2318 AT.AddName(Name, DI->first, DI->second);
2322 AT.FinalizeTable(Asm, "types");
2323 Asm->OutStreamer.SwitchSection(
2324 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2325 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2326 Asm->OutStreamer.EmitLabel(SectionBegin);
2328 // Emit the full data.
2329 AT.Emit(Asm, SectionBegin, &InfoHolder);
2332 // Public name handling.
2333 // The format for the various pubnames:
2335 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2336 // for the DIE that is named.
2338 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2339 // into the CU and the index value is computed according to the type of value
2340 // for the DIE that is named.
2342 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2343 // it's the offset within the debug_info/debug_types dwo section, however, the
2344 // reference in the pubname header doesn't change.
2346 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2347 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2349 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2351 // We could have a specification DIE that has our most of our knowledge,
2352 // look for that now.
2353 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2355 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2356 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2357 Linkage = dwarf::GIEL_EXTERNAL;
2358 } else if (Die->findAttribute(dwarf::DW_AT_external))
2359 Linkage = dwarf::GIEL_EXTERNAL;
2361 switch (Die->getTag()) {
2362 case dwarf::DW_TAG_class_type:
2363 case dwarf::DW_TAG_structure_type:
2364 case dwarf::DW_TAG_union_type:
2365 case dwarf::DW_TAG_enumeration_type:
2366 return dwarf::PubIndexEntryDescriptor(
2367 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2368 ? dwarf::GIEL_STATIC
2369 : dwarf::GIEL_EXTERNAL);
2370 case dwarf::DW_TAG_typedef:
2371 case dwarf::DW_TAG_base_type:
2372 case dwarf::DW_TAG_subrange_type:
2373 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2374 case dwarf::DW_TAG_namespace:
2375 return dwarf::GIEK_TYPE;
2376 case dwarf::DW_TAG_subprogram:
2377 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2378 case dwarf::DW_TAG_constant:
2379 case dwarf::DW_TAG_variable:
2380 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2381 case dwarf::DW_TAG_enumerator:
2382 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2383 dwarf::GIEL_STATIC);
2385 return dwarf::GIEK_NONE;
2389 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2391 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2392 const MCSection *PSec =
2393 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2394 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2396 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2397 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2398 for (unsigned i = 0; i != Units.size(); ++i) {
2399 DwarfUnit *TheU = Units[i];
2400 unsigned ID = TheU->getUniqueID();
2402 // Start the dwarf pubnames section.
2403 Asm->OutStreamer.SwitchSection(PSec);
2405 // Emit a label so we can reference the beginning of this pubname section.
2407 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2410 Asm->OutStreamer.AddComment("Length of Public Names Info");
2411 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2412 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2413 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2415 Asm->OutStreamer.EmitLabel(BeginLabel);
2417 Asm->OutStreamer.AddComment("DWARF Version");
2418 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2420 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2421 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2423 Asm->OutStreamer.AddComment("Compilation Unit Length");
2424 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2426 // Emit the pubnames for this compilation unit.
2427 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2428 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2431 const char *Name = GI->getKeyData();
2432 const DIE *Entity = GI->second;
2434 Asm->OutStreamer.AddComment("DIE offset");
2435 Asm->EmitInt32(Entity->getOffset());
2438 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2439 Asm->OutStreamer.AddComment(
2440 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2441 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2442 Asm->EmitInt8(Desc.toBits());
2445 Asm->OutStreamer.AddComment("External Name");
2446 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2449 Asm->OutStreamer.AddComment("End Mark");
2451 Asm->OutStreamer.EmitLabel(EndLabel);
2455 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2456 const MCSection *PSec =
2457 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2458 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2460 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2461 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2462 for (unsigned i = 0; i != Units.size(); ++i) {
2463 DwarfUnit *TheU = Units[i];
2464 unsigned ID = TheU->getUniqueID();
2466 // Start the dwarf pubtypes section.
2467 Asm->OutStreamer.SwitchSection(PSec);
2469 // Emit a label so we can reference the beginning of this pubtype section.
2471 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2474 Asm->OutStreamer.AddComment("Length of Public Types Info");
2475 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2476 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2477 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2479 Asm->OutStreamer.EmitLabel(BeginLabel);
2481 Asm->OutStreamer.AddComment("DWARF Version");
2482 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2484 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2485 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2487 Asm->OutStreamer.AddComment("Compilation Unit Length");
2488 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2490 // Emit the pubtypes.
2491 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2492 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2495 const char *Name = GI->getKeyData();
2496 const DIE *Entity = GI->second;
2498 Asm->OutStreamer.AddComment("DIE offset");
2499 Asm->EmitInt32(Entity->getOffset());
2502 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2503 Asm->OutStreamer.AddComment(
2504 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2505 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2506 Asm->EmitInt8(Desc.toBits());
2509 Asm->OutStreamer.AddComment("External Name");
2511 // Emit the name with a terminating null byte.
2512 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2515 Asm->OutStreamer.AddComment("End Mark");
2517 Asm->OutStreamer.EmitLabel(EndLabel);
2521 // Emit strings into a string section.
2522 void DwarfFile::emitStrings(const MCSection *StrSection,
2523 const MCSection *OffsetSection = NULL,
2524 const MCSymbol *StrSecSym = NULL) {
2526 if (StringPool.empty())
2529 // Start the dwarf str section.
2530 Asm->OutStreamer.SwitchSection(StrSection);
2532 // Get all of the string pool entries and put them in an array by their ID so
2533 // we can sort them.
2535 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2538 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2539 I = StringPool.begin(),
2540 E = StringPool.end();
2542 Entries.push_back(std::make_pair(I->second.second, &*I));
2544 array_pod_sort(Entries.begin(), Entries.end());
2546 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2547 // Emit a label for reference from debug information entries.
2548 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2550 // Emit the string itself with a terminating null byte.
2551 Asm->OutStreamer.EmitBytes(
2552 StringRef(Entries[i].second->getKeyData(),
2553 Entries[i].second->getKeyLength() + 1));
2556 // If we've got an offset section go ahead and emit that now as well.
2557 if (OffsetSection) {
2558 Asm->OutStreamer.SwitchSection(OffsetSection);
2559 unsigned offset = 0;
2560 unsigned size = 4; // FIXME: DWARF64 is 8.
2561 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2562 Asm->OutStreamer.EmitIntValue(offset, size);
2563 offset += Entries[i].second->getKeyLength() + 1;
2568 // Emit addresses into the section given.
2569 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2571 if (AddressPool.empty())
2574 // Start the dwarf addr section.
2575 Asm->OutStreamer.SwitchSection(AddrSection);
2577 // Order the address pool entries by ID
2578 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2580 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2581 E = AddressPool.end();
2583 Entries[I->second] = I->first;
2585 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2586 // Emit an expression for reference from debug information entries.
2587 if (const MCExpr *Expr = Entries[i])
2588 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2590 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2594 // Emit visible names into a debug str section.
2595 void DwarfDebug::emitDebugStr() {
2596 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2597 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2600 // Emit locations into the debug loc section.
2601 void DwarfDebug::emitDebugLoc() {
2602 if (DotDebugLocEntries.empty())
2605 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2606 I = DotDebugLocEntries.begin(),
2607 E = DotDebugLocEntries.end();
2609 DotDebugLocEntry &Entry = *I;
2610 if (I + 1 != DotDebugLocEntries.end())
2614 // Start the dwarf loc section.
2615 Asm->OutStreamer.SwitchSection(
2616 Asm->getObjFileLowering().getDwarfLocSection());
2617 unsigned char Size = Asm->getDataLayout().getPointerSize();
2618 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2620 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2621 I = DotDebugLocEntries.begin(),
2622 E = DotDebugLocEntries.end();
2623 I != E; ++I, ++index) {
2624 DotDebugLocEntry &Entry = *I;
2625 if (Entry.isMerged())
2627 if (Entry.isEmpty()) {
2628 Asm->OutStreamer.EmitIntValue(0, Size);
2629 Asm->OutStreamer.EmitIntValue(0, Size);
2630 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2632 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2633 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2634 DIVariable DV(Entry.getVariable());
2635 Asm->OutStreamer.AddComment("Loc expr size");
2636 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2637 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2638 Asm->EmitLabelDifference(end, begin, 2);
2639 Asm->OutStreamer.EmitLabel(begin);
2640 if (Entry.isInt()) {
2641 DIBasicType BTy(DV.getType());
2642 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2643 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2644 Asm->OutStreamer.AddComment("DW_OP_consts");
2645 Asm->EmitInt8(dwarf::DW_OP_consts);
2646 Asm->EmitSLEB128(Entry.getInt());
2648 Asm->OutStreamer.AddComment("DW_OP_constu");
2649 Asm->EmitInt8(dwarf::DW_OP_constu);
2650 Asm->EmitULEB128(Entry.getInt());
2652 } else if (Entry.isLocation()) {
2653 MachineLocation Loc = Entry.getLoc();
2654 if (!DV.hasComplexAddress())
2656 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2658 // Complex address entry.
2659 unsigned N = DV.getNumAddrElements();
2661 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2662 if (Loc.getOffset()) {
2664 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2665 Asm->OutStreamer.AddComment("DW_OP_deref");
2666 Asm->EmitInt8(dwarf::DW_OP_deref);
2667 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2668 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2669 Asm->EmitSLEB128(DV.getAddrElement(1));
2671 // If first address element is OpPlus then emit
2672 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2673 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2674 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2678 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2681 // Emit remaining complex address elements.
2682 for (; i < N; ++i) {
2683 uint64_t Element = DV.getAddrElement(i);
2684 if (Element == DIBuilder::OpPlus) {
2685 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2686 Asm->EmitULEB128(DV.getAddrElement(++i));
2687 } else if (Element == DIBuilder::OpDeref) {
2689 Asm->EmitInt8(dwarf::DW_OP_deref);
2691 llvm_unreachable("unknown Opcode found in complex address");
2695 // else ... ignore constant fp. There is not any good way to
2696 // to represent them here in dwarf.
2697 Asm->OutStreamer.EmitLabel(end);
2702 struct SymbolCUSorter {
2703 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2704 const MCStreamer &Streamer;
2706 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2707 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2708 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2710 // Symbols with no order assigned should be placed at the end.
2711 // (e.g. section end labels)
2713 IA = (unsigned)(-1);
2715 IB = (unsigned)(-1);
2720 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2721 return (A->getUniqueID() < B->getUniqueID());
2725 const MCSymbol *Start, *End;
2728 // Emit a debug aranges section, containing a CU lookup for any
2729 // address we can tie back to a CU.
2730 void DwarfDebug::emitDebugARanges() {
2731 // Start the dwarf aranges section.
2732 Asm->OutStreamer.SwitchSection(
2733 Asm->getObjFileLowering().getDwarfARangesSection());
2735 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2739 // Build a list of sections used.
2740 std::vector<const MCSection *> Sections;
2741 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2743 const MCSection *Section = it->first;
2744 Sections.push_back(Section);
2747 // Sort the sections into order.
2748 // This is only done to ensure consistent output order across different runs.
2749 std::sort(Sections.begin(), Sections.end(), SectionSort);
2751 // Build a set of address spans, sorted by CU.
2752 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2753 const MCSection *Section = Sections[SecIdx];
2754 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2755 if (List.size() < 2)
2758 // Sort the symbols by offset within the section.
2759 SymbolCUSorter sorter(Asm->OutStreamer);
2760 std::sort(List.begin(), List.end(), sorter);
2762 // If we have no section (e.g. common), just write out
2763 // individual spans for each symbol.
2764 if (Section == NULL) {
2765 for (size_t n = 0; n < List.size(); n++) {
2766 const SymbolCU &Cur = List[n];
2769 Span.Start = Cur.Sym;
2772 Spans[Cur.CU].push_back(Span);
2775 // Build spans between each label.
2776 const MCSymbol *StartSym = List[0].Sym;
2777 for (size_t n = 1; n < List.size(); n++) {
2778 const SymbolCU &Prev = List[n - 1];
2779 const SymbolCU &Cur = List[n];
2781 // Try and build the longest span we can within the same CU.
2782 if (Cur.CU != Prev.CU) {
2784 Span.Start = StartSym;
2786 Spans[Prev.CU].push_back(Span);
2793 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2795 // Build a list of CUs used.
2796 std::vector<DwarfCompileUnit *> CUs;
2797 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2798 DwarfCompileUnit *CU = it->first;
2802 // Sort the CU list (again, to ensure consistent output order).
2803 std::sort(CUs.begin(), CUs.end(), CUSort);
2805 // Emit an arange table for each CU we used.
2806 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2807 DwarfCompileUnit *CU = CUs[CUIdx];
2808 std::vector<ArangeSpan> &List = Spans[CU];
2810 // Emit size of content not including length itself.
2811 unsigned ContentSize =
2812 sizeof(int16_t) + // DWARF ARange version number
2813 sizeof(int32_t) + // Offset of CU in the .debug_info section
2814 sizeof(int8_t) + // Pointer Size (in bytes)
2815 sizeof(int8_t); // Segment Size (in bytes)
2817 unsigned TupleSize = PtrSize * 2;
2819 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2821 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2823 ContentSize += Padding;
2824 ContentSize += (List.size() + 1) * TupleSize;
2826 // For each compile unit, write the list of spans it covers.
2827 Asm->OutStreamer.AddComment("Length of ARange Set");
2828 Asm->EmitInt32(ContentSize);
2829 Asm->OutStreamer.AddComment("DWARF Arange version number");
2830 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2831 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2832 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2833 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2834 Asm->EmitInt8(PtrSize);
2835 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2838 Asm->OutStreamer.EmitFill(Padding, 0xff);
2840 for (unsigned n = 0; n < List.size(); n++) {
2841 const ArangeSpan &Span = List[n];
2842 Asm->EmitLabelReference(Span.Start, PtrSize);
2844 // Calculate the size as being from the span start to it's end.
2846 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2848 // For symbols without an end marker (e.g. common), we
2849 // write a single arange entry containing just that one symbol.
2850 uint64_t Size = SymSize[Span.Start];
2854 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2858 Asm->OutStreamer.AddComment("ARange terminator");
2859 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2860 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2864 // Emit visible names into a debug ranges section.
2865 void DwarfDebug::emitDebugRanges() {
2866 // Start the dwarf ranges section.
2867 Asm->OutStreamer.SwitchSection(
2868 Asm->getObjFileLowering().getDwarfRangesSection());
2870 // Size for our labels.
2871 unsigned char Size = Asm->getDataLayout().getPointerSize();
2873 // Grab the specific ranges for the compile units in the module.
2874 for (DenseMap<const MDNode *, DwarfCompileUnit *>::iterator I = CUMap.begin(),
2877 DwarfCompileUnit *TheCU = I->second;
2879 // Emit a symbol so we can find the beginning of our ranges.
2880 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2882 // Iterate over the misc ranges for the compile units in the module.
2883 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2884 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2885 E = RangeLists.end();
2887 const RangeSpanList &List = *I;
2889 // Emit our symbol so we can find the beginning of the range.
2890 Asm->OutStreamer.EmitLabel(List.getSym());
2892 for (SmallVectorImpl<RangeSpan>::const_iterator
2893 RI = List.getRanges().begin(),
2894 RE = List.getRanges().end();
2896 const RangeSpan &Range = *RI;
2897 const MCSymbol *Begin = Range.getStart();
2898 const MCSymbol *End = Range.getEnd();
2899 assert(Begin && "Range without a begin symbol?");
2900 assert(End && "Range without an end symbol?");
2901 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2902 Asm->OutStreamer.EmitSymbolValue(End, Size);
2905 // And terminate the list with two 0 values.
2906 Asm->OutStreamer.EmitIntValue(0, Size);
2907 Asm->OutStreamer.EmitIntValue(0, Size);
2910 // Now emit a range for the CU itself.
2911 if (DwarfCURanges) {
2912 Asm->OutStreamer.EmitLabel(
2913 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2914 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2915 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2916 RangeSpan Range = Ranges[i];
2917 const MCSymbol *Begin = Range.getStart();
2918 const MCSymbol *End = Range.getEnd();
2919 assert(Begin && "Range without a begin symbol?");
2920 assert(End && "Range without an end symbol?");
2921 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2922 Asm->OutStreamer.EmitSymbolValue(End, Size);
2924 // And terminate the list with two 0 values.
2925 Asm->OutStreamer.EmitIntValue(0, Size);
2926 Asm->OutStreamer.EmitIntValue(0, Size);
2931 // DWARF5 Experimental Separate Dwarf emitters.
2933 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2934 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2935 // DW_AT_ranges_base, DW_AT_addr_base.
2936 // TODO: Implement DW_AT_ranges_base.
2937 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2939 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2940 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2941 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2942 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2943 DwarfInfoSectionSym);
2945 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2946 CU->getCUNode().getSplitDebugFilename());
2948 // Relocate to the beginning of the addr_base section, else 0 for the
2949 // beginning of the one for this compile unit.
2950 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2951 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2952 DwarfAddrSectionSym);
2954 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2956 // DW_AT_stmt_list is a offset of line number information for this
2957 // compile unit in debug_line section.
2958 // FIXME: Should handle multiple compile units.
2959 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2960 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2962 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2964 if (!CompilationDir.empty())
2965 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2967 addGnuPubAttributes(NewCU, Die);
2969 SkeletonHolder.addUnit(NewCU);
2974 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2975 // compile units that would normally be in debug_info.
2976 void DwarfDebug::emitDebugInfoDWO() {
2977 assert(useSplitDwarf() && "No split dwarf debug info?");
2978 InfoHolder.emitUnits(this,
2979 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2980 DwarfAbbrevDWOSectionSym);
2983 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2984 // abbreviations for the .debug_info.dwo section.
2985 void DwarfDebug::emitDebugAbbrevDWO() {
2986 assert(useSplitDwarf() && "No split dwarf?");
2987 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2990 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2991 // string section and is identical in format to traditional .debug_str
2993 void DwarfDebug::emitDebugStrDWO() {
2994 assert(useSplitDwarf() && "No split dwarf?");
2995 const MCSection *OffSec =
2996 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2997 const MCSymbol *StrSym = DwarfStrSectionSym;
2998 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3002 void DwarfDebug::addDwarfTypeUnitType(DICompileUnit CUNode,
3003 StringRef Identifier, DIE *RefDie,
3004 DICompositeType CTy) {
3005 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
3007 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3008 DwarfTypeUnit *NewTU =
3009 new DwarfTypeUnit(InfoHolder.getUnits().size(), UnitDie, CUNode, Asm,
3012 InfoHolder.addUnit(NewTU);
3014 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3015 CUNode.getLanguage());
3017 DIE *Die = NewTU->createTypeDIE(CTy);
3020 Hash.update(Identifier);
3021 // ... take the least significant 8 bytes and return those. Our MD5
3022 // implementation always returns its results in little endian, swap bytes
3024 MD5::MD5Result Result;
3026 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3027 NewTU->setTypeSignature(Signature);
3028 NewTU->setType(Die);
3032 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3033 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3036 CUMap.begin()->second->addDIETypeSignature(RefDie, *TU);