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 "DwarfCompileUnit.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."),
62 GenerateODRHash("generate-odr-hash", cl::Hidden,
63 cl::desc("Add an ODR hash to external type DIEs."),
67 GenerateCUHash("generate-cu-hash", cl::Hidden,
68 cl::desc("Add the CU hash as the dwo_id."),
79 static cl::opt<DefaultOnOff>
80 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
81 cl::desc("Output prototype dwarf accelerator tables."),
82 cl::values(clEnumVal(Default, "Default for platform"),
83 clEnumVal(Enable, "Enabled"),
84 clEnumVal(Disable, "Disabled"), clEnumValEnd),
87 static cl::opt<DefaultOnOff>
88 SplitDwarf("split-dwarf", cl::Hidden,
89 cl::desc("Output prototype dwarf split debug info."),
90 cl::values(clEnumVal(Default, "Default for platform"),
91 clEnumVal(Enable, "Enabled"),
92 clEnumVal(Disable, "Disabled"), clEnumValEnd),
95 static cl::opt<DefaultOnOff>
96 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
97 cl::desc("Generate DWARF pubnames and pubtypes sections"),
98 cl::values(clEnumVal(Default, "Default for platform"),
99 clEnumVal(Enable, "Enabled"),
100 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 static const char *const DWARFGroupName = "DWARF Emission";
104 static const char *const DbgTimerName = "DWARF Debug Writer";
106 //===----------------------------------------------------------------------===//
108 // Configuration values for initial hash set sizes (log2).
110 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
114 DIType DbgVariable::getType() const {
115 DIType Ty = Var.getType();
116 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
117 // addresses instead.
118 if (Var.isBlockByrefVariable()) {
119 /* Byref variables, in Blocks, are declared by the programmer as
120 "SomeType VarName;", but the compiler creates a
121 __Block_byref_x_VarName struct, and gives the variable VarName
122 either the struct, or a pointer to the struct, as its type. This
123 is necessary for various behind-the-scenes things the compiler
124 needs to do with by-reference variables in blocks.
126 However, as far as the original *programmer* is concerned, the
127 variable should still have type 'SomeType', as originally declared.
129 The following function dives into the __Block_byref_x_VarName
130 struct to find the original type of the variable. This will be
131 passed back to the code generating the type for the Debug
132 Information Entry for the variable 'VarName'. 'VarName' will then
133 have the original type 'SomeType' in its debug information.
135 The original type 'SomeType' will be the type of the field named
136 'VarName' inside the __Block_byref_x_VarName struct.
138 NOTE: In order for this to not completely fail on the debugger
139 side, the Debug Information Entry for the variable VarName needs to
140 have a DW_AT_location that tells the debugger how to unwind through
141 the pointers and __Block_byref_x_VarName struct to find the actual
142 value of the variable. The function addBlockByrefType does this. */
144 uint16_t tag = Ty.getTag();
146 if (tag == dwarf::DW_TAG_pointer_type)
147 subType = DIDerivedType(Ty).getTypeDerivedFrom();
149 DIArray Elements = DICompositeType(subType).getTypeArray();
150 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
151 DIDerivedType DT = DIDerivedType(Elements.getElement(i));
152 if (getName() == DT.getName())
153 return (DT.getTypeDerivedFrom());
159 } // end llvm namespace
161 /// Return Dwarf Version by checking module flags.
162 static unsigned getDwarfVersionFromModule(const Module *M) {
163 Value *Val = M->getModuleFlag("Dwarf Version");
165 return dwarf::DWARF_VERSION;
166 return cast<ConstantInt>(Val)->getZExtValue();
169 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
170 : Asm(A), MMI(Asm->MMI), FirstCU(0),
171 AbbreviationsSet(InitAbbreviationsSetSize),
172 SourceIdMap(DIEValueAllocator),
173 PrevLabel(NULL), GlobalCUIndexCount(0),
174 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
176 SkeletonAbbrevSet(InitAbbreviationsSetSize),
177 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
180 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
181 DwarfStrSectionSym = TextSectionSym = 0;
182 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
183 DwarfAddrSectionSym = 0;
184 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
185 FunctionBeginSym = FunctionEndSym = 0;
187 // Turn on accelerator tables and older gdb compatibility
188 // for Darwin by default, pubnames by default for non-Darwin,
189 // and handle split dwarf.
190 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
192 if (DwarfAccelTables == Default)
193 HasDwarfAccelTables = IsDarwin;
195 HasDwarfAccelTables = DwarfAccelTables == Enable;
197 if (SplitDwarf == Default)
198 HasSplitDwarf = false;
200 HasSplitDwarf = SplitDwarf == Enable;
202 if (DwarfPubSections == Default)
203 HasDwarfPubSections = !IsDarwin;
205 HasDwarfPubSections = DwarfPubSections == Enable;
207 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
210 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
214 DwarfDebug::~DwarfDebug() {
217 // Switch to the specified MCSection and emit an assembler
218 // temporary label to it if SymbolStem is specified.
219 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
220 const char *SymbolStem = 0) {
221 Asm->OutStreamer.SwitchSection(Section);
222 if (!SymbolStem) return 0;
224 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
225 Asm->OutStreamer.EmitLabel(TmpSym);
229 MCSymbol *DwarfUnits::getStringPoolSym() {
230 return Asm->GetTempSymbol(StringPref);
233 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
234 std::pair<MCSymbol*, unsigned> &Entry =
235 StringPool.GetOrCreateValue(Str).getValue();
236 if (Entry.first) return Entry.first;
238 Entry.second = NextStringPoolNumber++;
239 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
242 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
243 std::pair<MCSymbol*, unsigned> &Entry =
244 StringPool.GetOrCreateValue(Str).getValue();
245 if (Entry.first) return Entry.second;
247 Entry.second = NextStringPoolNumber++;
248 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
252 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
253 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
256 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
257 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
258 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
260 ++NextAddrPoolNumber;
261 return P.first->second;
264 // Define a unique number for the abbreviation.
266 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
267 // Check the set for priors.
268 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
270 // If it's newly added.
271 if (InSet == &Abbrev) {
272 // Add to abbreviation list.
273 Abbreviations->push_back(&Abbrev);
275 // Assign the vector position + 1 as its number.
276 Abbrev.setNumber(Abbreviations->size());
278 // Assign existing abbreviation number.
279 Abbrev.setNumber(InSet->getNumber());
283 static bool isObjCClass(StringRef Name) {
284 return Name.startswith("+") || Name.startswith("-");
287 static bool hasObjCCategory(StringRef Name) {
288 if (!isObjCClass(Name)) return false;
290 return Name.find(") ") != StringRef::npos;
293 static void getObjCClassCategory(StringRef In, StringRef &Class,
294 StringRef &Category) {
295 if (!hasObjCCategory(In)) {
296 Class = In.slice(In.find('[') + 1, In.find(' '));
301 Class = In.slice(In.find('[') + 1, In.find('('));
302 Category = In.slice(In.find('[') + 1, In.find(' '));
306 static StringRef getObjCMethodName(StringRef In) {
307 return In.slice(In.find(' ') + 1, In.find(']'));
310 // Add the various names to the Dwarf accelerator table names.
311 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
313 if (!SP.isDefinition()) return;
315 TheCU->addAccelName(SP.getName(), Die);
317 // If the linkage name is different than the name, go ahead and output
318 // that as well into the name table.
319 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
320 TheCU->addAccelName(SP.getLinkageName(), Die);
322 // If this is an Objective-C selector name add it to the ObjC accelerator
324 if (isObjCClass(SP.getName())) {
325 StringRef Class, Category;
326 getObjCClassCategory(SP.getName(), Class, Category);
327 TheCU->addAccelObjC(Class, Die);
329 TheCU->addAccelObjC(Category, Die);
330 // Also add the base method name to the name table.
331 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
335 /// isSubprogramContext - Return true if Context is either a subprogram
336 /// or another context nested inside a subprogram.
337 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
340 DIDescriptor D(Context);
341 if (D.isSubprogram())
344 return isSubprogramContext(resolve(DIType(Context).getContext()));
348 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
349 // and DW_AT_high_pc attributes. If there are global variables in this
350 // scope then create and insert DIEs for these variables.
351 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
352 const MDNode *SPNode) {
353 DIE *SPDie = SPCU->getDIE(SPNode);
355 assert(SPDie && "Unable to find subprogram DIE!");
356 DISubprogram SP(SPNode);
358 // If we're updating an abstract DIE, then we will be adding the children and
359 // object pointer later on. But what we don't want to do is process the
360 // concrete DIE twice.
361 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
363 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
364 // Pick up abstract subprogram DIE.
365 SPDie = new DIE(dwarf::DW_TAG_subprogram);
366 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
368 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
369 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
373 DISubprogram SPDecl = SP.getFunctionDeclaration();
374 if (!SPDecl.isSubprogram()) {
375 // There is not any need to generate specification DIE for a function
376 // defined at compile unit level. If a function is defined inside another
377 // function then gdb prefers the definition at top level and but does not
378 // expect specification DIE in parent function. So avoid creating
379 // specification DIE for a function defined inside a function.
380 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
381 !SP.getContext().isFile() &&
382 !isSubprogramContext(SP.getContext())) {
383 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
386 DICompositeType SPTy = SP.getType();
387 DIArray Args = SPTy.getTypeArray();
388 uint16_t SPTag = SPTy.getTag();
389 if (SPTag == dwarf::DW_TAG_subroutine_type)
390 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
391 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
392 DIType ATy = DIType(Args.getElement(i));
393 SPCU->addType(Arg, ATy);
394 if (ATy.isArtificial())
395 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
396 if (ATy.isObjectPointer())
397 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
398 dwarf::DW_FORM_ref4, Arg);
399 SPDie->addChild(Arg);
401 DIE *SPDeclDie = SPDie;
402 SPDie = new DIE(dwarf::DW_TAG_subprogram);
403 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
404 dwarf::DW_FORM_ref4, SPDeclDie);
410 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
411 Asm->GetTempSymbol("func_begin",
412 Asm->getFunctionNumber()));
413 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
414 Asm->GetTempSymbol("func_end",
415 Asm->getFunctionNumber()));
416 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
417 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
418 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
420 // Add name to the name table, we do this here because we're guaranteed
421 // to have concrete versions of our DW_TAG_subprogram nodes.
422 addSubprogramNames(SPCU, SP, SPDie);
427 /// Check whether we should create a DIE for the given Scope, return true
428 /// if we don't create a DIE (the corresponding DIE is null).
429 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
430 if (Scope->isAbstractScope())
433 // We don't create a DIE if there is no Range.
434 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
438 if (Ranges.size() > 1)
441 // We don't create a DIE if we have a single Range and the end label
443 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
444 MCSymbol *End = getLabelAfterInsn(RI->second);
448 // Construct new DW_TAG_lexical_block for this scope and attach
449 // DW_AT_low_pc/DW_AT_high_pc labels.
450 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
451 LexicalScope *Scope) {
452 if (isLexicalScopeDIENull(Scope))
455 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
456 if (Scope->isAbstractScope())
459 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
460 // If we have multiple ranges, emit them into the range section.
461 if (Ranges.size() > 1) {
462 // .debug_range section has not been laid out yet. Emit offset in
463 // .debug_range as a uint, size 4, for now. emitDIE will handle
464 // DW_AT_ranges appropriately.
465 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
466 DebugRangeSymbols.size()
467 * Asm->getDataLayout().getPointerSize());
468 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
469 RE = Ranges.end(); RI != RE; ++RI) {
470 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
471 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
474 // Terminate the range list.
475 DebugRangeSymbols.push_back(NULL);
476 DebugRangeSymbols.push_back(NULL);
480 // Construct the address range for this DIE.
481 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
482 MCSymbol *Start = getLabelBeforeInsn(RI->first);
483 MCSymbol *End = getLabelAfterInsn(RI->second);
484 assert(End && "End label should not be null!");
486 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
487 assert(End->isDefined() && "Invalid end label for an inlined scope!");
489 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
490 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
495 // This scope represents inlined body of a function. Construct DIE to
496 // represent this concrete inlined copy of the function.
497 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
498 LexicalScope *Scope) {
499 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
500 assert(Ranges.empty() == false &&
501 "LexicalScope does not have instruction markers!");
503 if (!Scope->getScopeNode())
505 DIScope DS(Scope->getScopeNode());
506 DISubprogram InlinedSP = getDISubprogram(DS);
507 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
509 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
513 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
514 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
515 dwarf::DW_FORM_ref4, OriginDIE);
517 if (Ranges.size() > 1) {
518 // .debug_range section has not been laid out yet. Emit offset in
519 // .debug_range as a uint, size 4, for now. emitDIE will handle
520 // DW_AT_ranges appropriately.
521 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
522 DebugRangeSymbols.size()
523 * Asm->getDataLayout().getPointerSize());
524 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
525 RE = Ranges.end(); RI != RE; ++RI) {
526 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
527 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
529 DebugRangeSymbols.push_back(NULL);
530 DebugRangeSymbols.push_back(NULL);
532 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
533 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
534 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
536 if (StartLabel == 0 || EndLabel == 0)
537 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
539 assert(StartLabel->isDefined() &&
540 "Invalid starting label for an inlined scope!");
541 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
543 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
544 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
547 InlinedSubprogramDIEs.insert(OriginDIE);
549 // Add the call site information to the DIE.
550 DILocation DL(Scope->getInlinedAt());
551 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
552 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
553 TheCU->getUniqueID()));
554 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
556 // Add name to the name table, we do this here because we're guaranteed
557 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
558 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
563 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
564 SmallVectorImpl<DIE*> &Children) {
565 DIE *ObjectPointer = NULL;
567 // Collect arguments for current function.
568 if (LScopes.isCurrentFunctionScope(Scope))
569 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
570 if (DbgVariable *ArgDV = CurrentFnArguments[i])
572 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
573 Children.push_back(Arg);
574 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
577 // Collect lexical scope children first.
578 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
579 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
581 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
582 Children.push_back(Variable);
583 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
585 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
586 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
587 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
588 Children.push_back(Nested);
589 return ObjectPointer;
592 // Construct a DIE for this scope.
593 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
594 if (!Scope || !Scope->getScopeNode())
597 DIScope DS(Scope->getScopeNode());
599 SmallVector<DIE *, 8> Children;
600 DIE *ObjectPointer = NULL;
601 bool ChildrenCreated = false;
603 // We try to create the scope DIE first, then the children DIEs. This will
604 // avoid creating un-used children then removing them later when we find out
605 // the scope DIE is null.
606 DIE *ScopeDIE = NULL;
607 if (Scope->getInlinedAt())
608 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
609 else if (DS.isSubprogram()) {
610 ProcessedSPNodes.insert(DS);
611 if (Scope->isAbstractScope()) {
612 ScopeDIE = TheCU->getDIE(DS);
613 // Note down abstract DIE.
615 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
618 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
621 // Early exit when we know the scope DIE is going to be null.
622 if (isLexicalScopeDIENull(Scope))
625 // We create children here when we know the scope DIE is not going to be
626 // null and the children will be added to the scope DIE.
627 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
628 ChildrenCreated = true;
630 // There is no need to emit empty lexical block DIE.
631 std::pair<ImportedEntityMap::const_iterator,
632 ImportedEntityMap::const_iterator> Range = std::equal_range(
633 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
634 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
636 if (Children.empty() && Range.first == Range.second)
638 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
639 assert(ScopeDIE && "Scope DIE should not be null.");
640 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
642 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
646 assert(Children.empty() &&
647 "We create children only when the scope DIE is not null.");
650 if (!ChildrenCreated)
651 // We create children when the scope DIE is not null.
652 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
655 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
656 E = Children.end(); I != E; ++I)
657 ScopeDIE->addChild(*I);
659 if (DS.isSubprogram() && ObjectPointer != NULL)
660 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
661 dwarf::DW_FORM_ref4, ObjectPointer);
663 if (DS.isSubprogram())
664 TheCU->addPubTypes(DISubprogram(DS));
669 // Look up the source id with the given directory and source file names.
670 // If none currently exists, create a new id and insert it in the
671 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
673 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
674 StringRef DirName, unsigned CUID) {
675 // If we use .loc in assembly, we can't separate .file entries according to
676 // compile units. Thus all files will belong to the default compile unit.
677 if (Asm->TM.hasMCUseLoc() &&
678 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
681 // If FE did not provide a file name, then assume stdin.
682 if (FileName.empty())
683 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
685 // TODO: this might not belong here. See if we can factor this better.
686 if (DirName == CompilationDir)
689 // FileIDCUMap stores the current ID for the given compile unit.
690 unsigned SrcId = FileIDCUMap[CUID] + 1;
692 // We look up the CUID/file/dir by concatenating them with a zero byte.
693 SmallString<128> NamePair;
694 NamePair += utostr(CUID);
697 NamePair += '\0'; // Zero bytes are not allowed in paths.
698 NamePair += FileName;
700 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
701 if (Ent.getValue() != SrcId)
702 return Ent.getValue();
704 FileIDCUMap[CUID] = SrcId;
705 // Print out a .file directive to specify files for .loc directives.
706 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
711 // Create new CompileUnit for the given metadata node with tag
712 // DW_TAG_compile_unit.
713 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
714 DICompileUnit DIUnit(N);
715 StringRef FN = DIUnit.getFilename();
716 CompilationDir = DIUnit.getDirectory();
718 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
720 new CompileUnit(GlobalCUIndexCount++, Die, N, Asm, this, &InfoHolder);
722 FileIDCUMap[NewCU->getUniqueID()] = 0;
723 // Call this to emit a .file directive if it wasn't emitted for the source
724 // file this CU comes from yet.
725 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
727 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
728 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
729 DIUnit.getLanguage());
730 NewCU->addString(Die, dwarf::DW_AT_name, FN);
732 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
733 // into an entity. We're using 0 (or a NULL label) for this. For
734 // split dwarf it's in the skeleton CU so omit it here.
735 if (!useSplitDwarf())
736 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
738 // Define start line table label for each Compile Unit.
739 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
740 NewCU->getUniqueID());
741 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
742 NewCU->getUniqueID());
744 // Use a single line table if we are using .loc and generating assembly.
746 (Asm->TM.hasMCUseLoc() &&
747 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
748 (NewCU->getUniqueID() == 0);
750 // DW_AT_stmt_list is a offset of line number information for this
751 // compile unit in debug_line section. For split dwarf this is
752 // left in the skeleton CU and so not included.
753 // The line table entries are not always emitted in assembly, so it
754 // is not okay to use line_table_start here.
755 if (!useSplitDwarf()) {
756 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
757 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
759 Asm->GetTempSymbol("section_line") : LineTableStartSym);
760 else if (UseTheFirstCU)
761 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
763 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
764 LineTableStartSym, DwarfLineSectionSym);
767 // If we're using split dwarf the compilation dir is going to be in the
768 // skeleton CU and so we don't need to duplicate it here.
769 if (!useSplitDwarf() && !CompilationDir.empty())
770 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
771 if (DIUnit.isOptimized())
772 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
774 StringRef Flags = DIUnit.getFlags();
776 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
778 if (unsigned RVer = DIUnit.getRunTimeVersion())
779 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
780 dwarf::DW_FORM_data1, RVer);
785 InfoHolder.addUnit(NewCU);
787 CUMap.insert(std::make_pair(N, NewCU));
791 // Construct subprogram DIE.
792 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
794 CompileUnit *&CURef = SPMap[N];
800 if (!SP.isDefinition())
801 // This is a method declaration which will be handled while constructing
805 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
808 TheCU->insertDIE(N, SubprogramDie);
810 // Add to context owner.
811 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
813 // Expose as a global name.
814 TheCU->addGlobalName(SP.getName(), SubprogramDie);
817 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
819 DIImportedEntity Module(N);
820 if (!Module.Verify())
822 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
823 constructImportedEntityDIE(TheCU, Module, D);
826 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
828 DIImportedEntity Module(N);
829 if (!Module.Verify())
831 return constructImportedEntityDIE(TheCU, Module, Context);
834 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
835 const DIImportedEntity &Module,
837 assert(Module.Verify() &&
838 "Use one of the MDNode * overloads to handle invalid metadata");
839 assert(Context && "Should always have a context for an imported_module");
840 DIE *IMDie = new DIE(Module.getTag());
841 TheCU->insertDIE(Module, IMDie);
843 DIDescriptor Entity = Module.getEntity();
844 if (Entity.isNameSpace())
845 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
846 else if (Entity.isSubprogram())
847 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
848 else if (Entity.isType())
849 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
851 EntityDie = TheCU->getDIE(Entity);
852 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
853 Module.getContext().getDirectory(),
854 TheCU->getUniqueID());
855 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
856 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
857 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
859 StringRef Name = Module.getName();
861 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
862 Context->addChild(IMDie);
865 // Emit all Dwarf sections that should come prior to the content. Create
866 // global DIEs and emit initial debug info sections. This is invoked by
867 // the target AsmPrinter.
868 void DwarfDebug::beginModule() {
869 if (DisableDebugInfoPrinting)
872 const Module *M = MMI->getModule();
874 // If module has named metadata anchors then use them, otherwise scan the
875 // module using debug info finder to collect debug info.
876 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
879 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
881 // Emit initial sections so we can reference labels later.
884 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
885 DICompileUnit CUNode(CU_Nodes->getOperand(i));
886 CompileUnit *CU = constructCompileUnit(CUNode);
887 DIArray ImportedEntities = CUNode.getImportedEntities();
888 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
889 ScopesWithImportedEntities.push_back(std::make_pair(
890 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
891 ImportedEntities.getElement(i)));
892 std::sort(ScopesWithImportedEntities.begin(),
893 ScopesWithImportedEntities.end(), less_first());
894 DIArray GVs = CUNode.getGlobalVariables();
895 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
896 CU->createGlobalVariableDIE(GVs.getElement(i));
897 DIArray SPs = CUNode.getSubprograms();
898 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
899 constructSubprogramDIE(CU, SPs.getElement(i));
900 DIArray EnumTypes = CUNode.getEnumTypes();
901 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
902 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
903 DIArray RetainedTypes = CUNode.getRetainedTypes();
904 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
905 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
906 // Emit imported_modules last so that the relevant context is already
908 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
909 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
912 // Tell MMI that we have debug info.
913 MMI->setDebugInfoAvailability(true);
915 // Prime section data.
916 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
919 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
920 void DwarfDebug::computeInlinedDIEs() {
921 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
922 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
923 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
925 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
927 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
928 AE = AbstractSPDies.end(); AI != AE; ++AI) {
929 DIE *ISP = AI->second;
930 if (InlinedSubprogramDIEs.count(ISP))
932 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
936 // Collect info for variables that were optimized out.
937 void DwarfDebug::collectDeadVariables() {
938 const Module *M = MMI->getModule();
939 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
941 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
942 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
943 DICompileUnit TheCU(CU_Nodes->getOperand(i));
944 DIArray Subprograms = TheCU.getSubprograms();
945 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
946 DISubprogram SP(Subprograms.getElement(i));
947 if (ProcessedSPNodes.count(SP) != 0) continue;
948 if (!SP.isSubprogram()) continue;
949 if (!SP.isDefinition()) continue;
950 DIArray Variables = SP.getVariables();
951 if (Variables.getNumElements() == 0) continue;
953 LexicalScope *Scope =
954 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
955 DeadFnScopeMap[SP] = Scope;
957 // Construct subprogram DIE and add variables DIEs.
958 CompileUnit *SPCU = CUMap.lookup(TheCU);
959 assert(SPCU && "Unable to find Compile Unit!");
960 constructSubprogramDIE(SPCU, SP);
961 DIE *ScopeDIE = SPCU->getDIE(SP);
962 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
963 DIVariable DV(Variables.getElement(vi));
964 if (!DV.isVariable()) continue;
965 DbgVariable NewVar(DV, NULL);
966 if (DIE *VariableDIE =
967 SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
968 ScopeDIE->addChild(VariableDIE);
973 DeleteContainerSeconds(DeadFnScopeMap);
976 // Type Signature [7.27] and ODR Hash code.
978 /// \brief Grabs the string in whichever attribute is passed in and returns
979 /// a reference to it. Returns "" if the attribute doesn't exist.
980 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
981 DIEValue *V = Die->findAttribute(Attr);
983 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
984 return S->getString();
986 return StringRef("");
989 /// Return true if the current DIE is contained within an anonymous namespace.
990 static bool isContainedInAnonNamespace(DIE *Die) {
991 DIE *Parent = Die->getParent();
994 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
995 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
997 Parent = Parent->getParent();
1003 /// Test if the current CU language is C++ and that we have
1004 /// a named type that is not contained in an anonymous namespace.
1005 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
1006 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1007 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1008 !isContainedInAnonNamespace(Die);
1011 void DwarfDebug::finalizeModuleInfo() {
1012 // Collect info for variables that were optimized out.
1013 collectDeadVariables();
1015 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1016 computeInlinedDIEs();
1018 // Split out type units and conditionally add an ODR tag to the split
1020 // FIXME: Do type splitting.
1021 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
1022 DIE *Die = TypeUnits[i];
1024 // If we've requested ODR hashes and it's applicable for an ODR hash then
1025 // add the ODR signature now.
1026 // FIXME: This should be added onto the type unit, not the type, but this
1027 // works as an intermediate stage.
1028 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
1029 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
1030 dwarf::DW_FORM_data8,
1031 Hash.computeDIEODRSignature(Die));
1034 // Handle anything that needs to be done on a per-cu basis.
1035 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1037 CUI != CUE; ++CUI) {
1038 CompileUnit *TheCU = CUI->second;
1039 // Emit DW_AT_containing_type attribute to connect types with their
1040 // vtable holding type.
1041 TheCU->constructContainingTypeDIEs();
1043 // If we're splitting the dwarf out now that we've got the entire
1044 // CU then construct a skeleton CU based upon it.
1045 if (useSplitDwarf()) {
1047 if (GenerateCUHash) {
1049 ID = CUHash.computeCUSignature(TheCU->getCUDie());
1051 // This should be a unique identifier when we want to build .dwp files.
1052 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1053 dwarf::DW_FORM_data8, ID);
1054 // Now construct the skeleton CU associated.
1055 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1056 // This should be a unique identifier when we want to build .dwp files.
1057 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1058 dwarf::DW_FORM_data8, ID);
1062 // Compute DIE offsets and sizes.
1063 InfoHolder.computeSizeAndOffsets();
1064 if (useSplitDwarf())
1065 SkeletonHolder.computeSizeAndOffsets();
1068 void DwarfDebug::endSections() {
1069 // Standard sections final addresses.
1070 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1071 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1072 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1073 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1075 // End text sections.
1076 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
1077 Asm->OutStreamer.SwitchSection(SectionMap[I]);
1078 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1082 // Emit all Dwarf sections that should come after the content.
1083 void DwarfDebug::endModule() {
1085 if (!FirstCU) return;
1087 // End any existing sections.
1088 // TODO: Does this need to happen?
1091 // Finalize the debug info for the module.
1092 finalizeModuleInfo();
1094 if (!useSplitDwarf()) {
1095 // Emit all the DIEs into a debug info section.
1098 // Corresponding abbreviations into a abbrev section.
1099 emitAbbreviations();
1101 // Emit info into a debug loc section.
1104 // Emit info into a debug aranges section.
1107 // Emit info into a debug ranges section.
1110 // Emit info into a debug macinfo section.
1114 // TODO: Fill this in for separated debug sections and separate
1115 // out information into new sections.
1117 // Emit the debug info section and compile units.
1121 // Corresponding abbreviations into a abbrev section.
1122 emitAbbreviations();
1123 emitDebugAbbrevDWO();
1125 // Emit info into a debug loc section.
1128 // Emit info into a debug aranges section.
1131 // Emit info into a debug ranges section.
1134 // Emit info into a debug macinfo section.
1137 // Emit DWO addresses.
1138 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1142 // Emit info into the dwarf accelerator table sections.
1143 if (useDwarfAccelTables()) {
1146 emitAccelNamespaces();
1150 // Emit the pubnames and pubtypes sections if requested.
1151 if (HasDwarfPubSections) {
1152 emitDebugPubNames();
1153 emitDebugPubTypes();
1156 // Finally emit string information into a string table.
1158 if (useSplitDwarf())
1163 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1164 E = CUMap.end(); I != E; ++I)
1167 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1168 E = SkeletonCUs.end(); I != E; ++I)
1171 // Reset these for the next Module if we have one.
1175 // Find abstract variable, if any, associated with Var.
1176 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1177 DebugLoc ScopeLoc) {
1178 LLVMContext &Ctx = DV->getContext();
1179 // More then one inlined variable corresponds to one abstract variable.
1180 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1181 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1183 return AbsDbgVariable;
1185 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1189 AbsDbgVariable = new DbgVariable(Var, NULL);
1190 addScopeVariable(Scope, AbsDbgVariable);
1191 AbstractVariables[Var] = AbsDbgVariable;
1192 return AbsDbgVariable;
1195 // If Var is a current function argument then add it to CurrentFnArguments list.
1196 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1197 DbgVariable *Var, LexicalScope *Scope) {
1198 if (!LScopes.isCurrentFunctionScope(Scope))
1200 DIVariable DV = Var->getVariable();
1201 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1203 unsigned ArgNo = DV.getArgNumber();
1207 size_t Size = CurrentFnArguments.size();
1209 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1210 // llvm::Function argument size is not good indicator of how many
1211 // arguments does the function have at source level.
1213 CurrentFnArguments.resize(ArgNo * 2);
1214 CurrentFnArguments[ArgNo - 1] = Var;
1218 // Collect variable information from side table maintained by MMI.
1220 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1221 SmallPtrSet<const MDNode *, 16> &Processed) {
1222 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1223 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1224 VE = VMap.end(); VI != VE; ++VI) {
1225 const MDNode *Var = VI->first;
1227 Processed.insert(Var);
1229 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1231 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1233 // If variable scope is not found then skip this variable.
1237 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1238 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1239 RegVar->setFrameIndex(VP.first);
1240 if (!addCurrentFnArgument(MF, RegVar, Scope))
1241 addScopeVariable(Scope, RegVar);
1243 AbsDbgVariable->setFrameIndex(VP.first);
1247 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1249 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1250 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1251 return MI->getNumOperands() == 3 &&
1252 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1253 (MI->getOperand(1).isImm() ||
1254 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1257 // Get .debug_loc entry for the instruction range starting at MI.
1258 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1259 const MCSymbol *FLabel,
1260 const MCSymbol *SLabel,
1261 const MachineInstr *MI) {
1262 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1264 assert(MI->getNumOperands() == 3);
1265 if (MI->getOperand(0).isReg()) {
1266 MachineLocation MLoc;
1267 // If the second operand is an immediate, this is a
1268 // register-indirect address.
1269 if (!MI->getOperand(1).isImm())
1270 MLoc.set(MI->getOperand(0).getReg());
1272 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1273 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1275 if (MI->getOperand(0).isImm())
1276 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1277 if (MI->getOperand(0).isFPImm())
1278 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1279 if (MI->getOperand(0).isCImm())
1280 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1282 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1285 // Find variables for each lexical scope.
1287 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1288 SmallPtrSet<const MDNode *, 16> &Processed) {
1290 // Grab the variable info that was squirreled away in the MMI side-table.
1291 collectVariableInfoFromMMITable(MF, Processed);
1293 for (SmallVectorImpl<const MDNode*>::const_iterator
1294 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1296 const MDNode *Var = *UVI;
1297 if (Processed.count(Var))
1300 // History contains relevant DBG_VALUE instructions for Var and instructions
1302 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1303 if (History.empty())
1305 const MachineInstr *MInsn = History.front();
1308 LexicalScope *Scope = NULL;
1309 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1310 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1311 Scope = LScopes.getCurrentFunctionScope();
1312 else if (MDNode *IA = DV.getInlinedAt())
1313 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1315 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1316 // If variable scope is not found then skip this variable.
1320 Processed.insert(DV);
1321 assert(MInsn->isDebugValue() && "History must begin with debug value");
1322 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1323 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1324 if (!addCurrentFnArgument(MF, RegVar, Scope))
1325 addScopeVariable(Scope, RegVar);
1327 AbsVar->setMInsn(MInsn);
1329 // Simplify ranges that are fully coalesced.
1330 if (History.size() <= 1 || (History.size() == 2 &&
1331 MInsn->isIdenticalTo(History.back()))) {
1332 RegVar->setMInsn(MInsn);
1336 // Handle multiple DBG_VALUE instructions describing one variable.
1337 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1339 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1340 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1341 const MachineInstr *Begin = *HI;
1342 assert(Begin->isDebugValue() && "Invalid History entry");
1344 // Check if DBG_VALUE is truncating a range.
1345 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1346 && !Begin->getOperand(0).getReg())
1349 // Compute the range for a register location.
1350 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1351 const MCSymbol *SLabel = 0;
1354 // If Begin is the last instruction in History then its value is valid
1355 // until the end of the function.
1356 SLabel = FunctionEndSym;
1358 const MachineInstr *End = HI[1];
1359 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1360 << "\t" << *Begin << "\t" << *End << "\n");
1361 if (End->isDebugValue())
1362 SLabel = getLabelBeforeInsn(End);
1364 // End is a normal instruction clobbering the range.
1365 SLabel = getLabelAfterInsn(End);
1366 assert(SLabel && "Forgot label after clobber instruction");
1371 // The value is valid until the next DBG_VALUE or clobber.
1372 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1375 DotDebugLocEntries.push_back(DotDebugLocEntry());
1378 // Collect info for variables that were optimized out.
1379 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1380 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1381 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1382 DIVariable DV(Variables.getElement(i));
1383 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1385 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1386 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1390 // Return Label preceding the instruction.
1391 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1392 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1393 assert(Label && "Didn't insert label before instruction");
1397 // Return Label immediately following the instruction.
1398 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1399 return LabelsAfterInsn.lookup(MI);
1402 // Process beginning of an instruction.
1403 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1404 // Check if source location changes, but ignore DBG_VALUE locations.
1405 if (!MI->isDebugValue()) {
1406 DebugLoc DL = MI->getDebugLoc();
1407 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1410 if (DL == PrologEndLoc) {
1411 Flags |= DWARF2_FLAG_PROLOGUE_END;
1412 PrologEndLoc = DebugLoc();
1414 if (PrologEndLoc.isUnknown())
1415 Flags |= DWARF2_FLAG_IS_STMT;
1417 if (!DL.isUnknown()) {
1418 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1419 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1421 recordSourceLine(0, 0, 0, 0);
1425 // Insert labels where requested.
1426 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1427 LabelsBeforeInsn.find(MI);
1430 if (I == LabelsBeforeInsn.end())
1433 // Label already assigned.
1438 PrevLabel = MMI->getContext().CreateTempSymbol();
1439 Asm->OutStreamer.EmitLabel(PrevLabel);
1441 I->second = PrevLabel;
1444 // Process end of an instruction.
1445 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1446 // Don't create a new label after DBG_VALUE instructions.
1447 // They don't generate code.
1448 if (!MI->isDebugValue())
1451 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1452 LabelsAfterInsn.find(MI);
1455 if (I == LabelsAfterInsn.end())
1458 // Label already assigned.
1462 // We need a label after this instruction.
1464 PrevLabel = MMI->getContext().CreateTempSymbol();
1465 Asm->OutStreamer.EmitLabel(PrevLabel);
1467 I->second = PrevLabel;
1470 // Each LexicalScope has first instruction and last instruction to mark
1471 // beginning and end of a scope respectively. Create an inverse map that list
1472 // scopes starts (and ends) with an instruction. One instruction may start (or
1473 // end) multiple scopes. Ignore scopes that are not reachable.
1474 void DwarfDebug::identifyScopeMarkers() {
1475 SmallVector<LexicalScope *, 4> WorkList;
1476 WorkList.push_back(LScopes.getCurrentFunctionScope());
1477 while (!WorkList.empty()) {
1478 LexicalScope *S = WorkList.pop_back_val();
1480 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1481 if (!Children.empty())
1482 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1483 SE = Children.end(); SI != SE; ++SI)
1484 WorkList.push_back(*SI);
1486 if (S->isAbstractScope())
1489 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1492 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1493 RE = Ranges.end(); RI != RE; ++RI) {
1494 assert(RI->first && "InsnRange does not have first instruction!");
1495 assert(RI->second && "InsnRange does not have second instruction!");
1496 requestLabelBeforeInsn(RI->first);
1497 requestLabelAfterInsn(RI->second);
1502 // Get MDNode for DebugLoc's scope.
1503 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1504 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1505 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1506 return DL.getScope(Ctx);
1509 // Walk up the scope chain of given debug loc and find line number info
1510 // for the function.
1511 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1512 const MDNode *Scope = getScopeNode(DL, Ctx);
1513 DISubprogram SP = getDISubprogram(Scope);
1514 if (SP.isSubprogram()) {
1515 // Check for number of operands since the compatibility is
1517 if (SP->getNumOperands() > 19)
1518 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1520 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1526 // Gather pre-function debug information. Assumes being called immediately
1527 // after the function entry point has been emitted.
1528 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1529 if (!MMI->hasDebugInfo()) return;
1530 LScopes.initialize(*MF);
1531 if (LScopes.empty()) return;
1532 identifyScopeMarkers();
1534 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1536 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1537 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1538 assert(TheCU && "Unable to find compile unit!");
1539 if (Asm->TM.hasMCUseLoc() &&
1540 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1541 // Use a single line table if we are using .loc and generating assembly.
1542 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1544 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1546 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1547 Asm->getFunctionNumber());
1548 // Assumes in correct section after the entry point.
1549 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1551 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1553 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1554 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1555 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1557 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1559 bool AtBlockEntry = true;
1560 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1562 const MachineInstr *MI = II;
1564 if (MI->isDebugValue()) {
1565 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1567 // Keep track of user variables.
1569 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1571 // Variable is in a register, we need to check for clobbers.
1572 if (isDbgValueInDefinedReg(MI))
1573 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1575 // Check the history of this variable.
1576 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1577 if (History.empty()) {
1578 UserVariables.push_back(Var);
1579 // The first mention of a function argument gets the FunctionBeginSym
1580 // label, so arguments are visible when breaking at function entry.
1582 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1583 DISubprogram(getDISubprogram(DV.getContext()))
1584 .describes(MF->getFunction()))
1585 LabelsBeforeInsn[MI] = FunctionBeginSym;
1587 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1588 const MachineInstr *Prev = History.back();
1589 if (Prev->isDebugValue()) {
1590 // Coalesce identical entries at the end of History.
1591 if (History.size() >= 2 &&
1592 Prev->isIdenticalTo(History[History.size() - 2])) {
1593 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1595 << "\t" << *History[History.size() - 2] << "\n");
1599 // Terminate old register assignments that don't reach MI;
1600 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1601 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1602 isDbgValueInDefinedReg(Prev)) {
1603 // Previous register assignment needs to terminate at the end of
1605 MachineBasicBlock::const_iterator LastMI =
1606 PrevMBB->getLastNonDebugInstr();
1607 if (LastMI == PrevMBB->end()) {
1608 // Drop DBG_VALUE for empty range.
1609 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1610 << "\t" << *Prev << "\n");
1612 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1613 // Terminate after LastMI.
1614 History.push_back(LastMI);
1618 History.push_back(MI);
1620 // Not a DBG_VALUE instruction.
1622 AtBlockEntry = false;
1624 // First known non-DBG_VALUE and non-frame setup location marks
1625 // the beginning of the function body.
1626 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1627 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1628 PrologEndLoc = MI->getDebugLoc();
1630 // Check if the instruction clobbers any registers with debug vars.
1631 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1632 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1633 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1635 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1636 AI.isValid(); ++AI) {
1638 const MDNode *Var = LiveUserVar[Reg];
1641 // Reg is now clobbered.
1642 LiveUserVar[Reg] = 0;
1644 // Was MD last defined by a DBG_VALUE referring to Reg?
1645 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1646 if (HistI == DbgValues.end())
1648 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1649 if (History.empty())
1651 const MachineInstr *Prev = History.back();
1652 // Sanity-check: Register assignments are terminated at the end of
1654 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1656 // Is the variable still in Reg?
1657 if (!isDbgValueInDefinedReg(Prev) ||
1658 Prev->getOperand(0).getReg() != Reg)
1660 // Var is clobbered. Make sure the next instruction gets a label.
1661 History.push_back(MI);
1668 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1670 SmallVectorImpl<const MachineInstr*> &History = I->second;
1671 if (History.empty())
1674 // Make sure the final register assignments are terminated.
1675 const MachineInstr *Prev = History.back();
1676 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1677 const MachineBasicBlock *PrevMBB = Prev->getParent();
1678 MachineBasicBlock::const_iterator LastMI =
1679 PrevMBB->getLastNonDebugInstr();
1680 if (LastMI == PrevMBB->end())
1681 // Drop DBG_VALUE for empty range.
1683 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1684 // Terminate after LastMI.
1685 History.push_back(LastMI);
1688 // Request labels for the full history.
1689 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1690 const MachineInstr *MI = History[i];
1691 if (MI->isDebugValue())
1692 requestLabelBeforeInsn(MI);
1694 requestLabelAfterInsn(MI);
1698 PrevInstLoc = DebugLoc();
1699 PrevLabel = FunctionBeginSym;
1701 // Record beginning of function.
1702 if (!PrologEndLoc.isUnknown()) {
1703 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1704 MF->getFunction()->getContext());
1705 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1706 FnStartDL.getScope(MF->getFunction()->getContext()),
1707 // We'd like to list the prologue as "not statements" but GDB behaves
1708 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1709 DWARF2_FLAG_IS_STMT);
1713 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1714 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1715 DIVariable DV = Var->getVariable();
1716 // Variables with positive arg numbers are parameters.
1717 if (unsigned ArgNum = DV.getArgNumber()) {
1718 // Keep all parameters in order at the start of the variable list to ensure
1719 // function types are correct (no out-of-order parameters)
1721 // This could be improved by only doing it for optimized builds (unoptimized
1722 // builds have the right order to begin with), searching from the back (this
1723 // would catch the unoptimized case quickly), or doing a binary search
1724 // rather than linear search.
1725 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1726 while (I != Vars.end()) {
1727 unsigned CurNum = (*I)->getVariable().getArgNumber();
1728 // A local (non-parameter) variable has been found, insert immediately
1732 // A later indexed parameter has been found, insert immediately before it.
1733 if (CurNum > ArgNum)
1737 Vars.insert(I, Var);
1741 Vars.push_back(Var);
1744 // Gather and emit post-function debug information.
1745 void DwarfDebug::endFunction(const MachineFunction *MF) {
1746 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1748 // Define end label for subprogram.
1749 FunctionEndSym = Asm->GetTempSymbol("func_end",
1750 Asm->getFunctionNumber());
1751 // Assumes in correct section after the entry point.
1752 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1753 // Set DwarfCompileUnitID in MCContext to default value.
1754 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1756 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1757 collectVariableInfo(MF, ProcessedVars);
1759 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1760 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1761 assert(TheCU && "Unable to find compile unit!");
1763 // Construct abstract scopes.
1764 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1765 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1766 LexicalScope *AScope = AList[i];
1767 DISubprogram SP(AScope->getScopeNode());
1768 if (SP.isSubprogram()) {
1769 // Collect info for variables that were optimized out.
1770 DIArray Variables = SP.getVariables();
1771 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1772 DIVariable DV(Variables.getElement(i));
1773 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1775 // Check that DbgVariable for DV wasn't created earlier, when
1776 // findAbstractVariable() was called for inlined instance of DV.
1777 LLVMContext &Ctx = DV->getContext();
1778 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1779 if (AbstractVariables.lookup(CleanDV))
1781 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1782 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1785 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1786 constructScopeDIE(TheCU, AScope);
1789 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1791 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1792 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1795 for (ScopeVariablesMap::iterator
1796 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1797 DeleteContainerPointers(I->second);
1798 ScopeVariables.clear();
1799 DeleteContainerPointers(CurrentFnArguments);
1800 UserVariables.clear();
1802 AbstractVariables.clear();
1803 LabelsBeforeInsn.clear();
1804 LabelsAfterInsn.clear();
1808 // Register a source line with debug info. Returns the unique label that was
1809 // emitted and which provides correspondence to the source line list.
1810 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1816 DIDescriptor Scope(S);
1818 if (Scope.isCompileUnit()) {
1819 DICompileUnit CU(S);
1820 Fn = CU.getFilename();
1821 Dir = CU.getDirectory();
1822 } else if (Scope.isFile()) {
1824 Fn = F.getFilename();
1825 Dir = F.getDirectory();
1826 } else if (Scope.isSubprogram()) {
1828 Fn = SP.getFilename();
1829 Dir = SP.getDirectory();
1830 } else if (Scope.isLexicalBlockFile()) {
1831 DILexicalBlockFile DBF(S);
1832 Fn = DBF.getFilename();
1833 Dir = DBF.getDirectory();
1834 } else if (Scope.isLexicalBlock()) {
1835 DILexicalBlock DB(S);
1836 Fn = DB.getFilename();
1837 Dir = DB.getDirectory();
1839 llvm_unreachable("Unexpected scope info");
1841 Src = getOrCreateSourceID(Fn, Dir,
1842 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1844 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1847 //===----------------------------------------------------------------------===//
1849 //===----------------------------------------------------------------------===//
1851 // Compute the size and offset of a DIE.
1853 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1854 // Get the children.
1855 const std::vector<DIE *> &Children = Die->getChildren();
1857 // Record the abbreviation.
1858 assignAbbrevNumber(Die->getAbbrev());
1860 // Get the abbreviation for this DIE.
1861 unsigned AbbrevNumber = Die->getAbbrevNumber();
1862 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1865 Die->setOffset(Offset);
1867 // Start the size with the size of abbreviation code.
1868 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1870 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1871 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1873 // Size the DIE attribute values.
1874 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1875 // Size attribute value.
1876 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1878 // Size the DIE children if any.
1879 if (!Children.empty()) {
1880 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1881 "Children flag not set");
1883 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1884 Offset = computeSizeAndOffset(Children[j], Offset);
1886 // End of children marker.
1887 Offset += sizeof(int8_t);
1890 Die->setSize(Offset - Die->getOffset());
1894 // Compute the size and offset of all the DIEs.
1895 void DwarfUnits::computeSizeAndOffsets() {
1896 // Offset from the beginning of debug info section.
1897 unsigned SecOffset = 0;
1898 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1899 E = CUs.end(); I != E; ++I) {
1900 (*I)->setDebugInfoOffset(SecOffset);
1902 sizeof(int32_t) + // Length of Compilation Unit Info
1903 sizeof(int16_t) + // DWARF version number
1904 sizeof(int32_t) + // Offset Into Abbrev. Section
1905 sizeof(int8_t); // Pointer Size (in bytes)
1907 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1908 SecOffset += EndOffset;
1912 // Emit initial Dwarf sections with a label at the start of each one.
1913 void DwarfDebug::emitSectionLabels() {
1914 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1916 // Dwarf sections base addresses.
1917 DwarfInfoSectionSym =
1918 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1919 DwarfAbbrevSectionSym =
1920 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1921 if (useSplitDwarf())
1922 DwarfAbbrevDWOSectionSym =
1923 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1924 "section_abbrev_dwo");
1925 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1927 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1928 emitSectionSym(Asm, MacroInfo);
1930 DwarfLineSectionSym =
1931 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1932 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1933 if (HasDwarfPubSections) {
1934 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1935 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1937 DwarfStrSectionSym =
1938 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1939 if (useSplitDwarf()) {
1940 DwarfStrDWOSectionSym =
1941 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1942 DwarfAddrSectionSym =
1943 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1945 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1948 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1949 "section_debug_loc");
1951 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1952 emitSectionSym(Asm, TLOF.getDataSection());
1955 // Recursively emits a debug information entry.
1956 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1957 // Get the abbreviation for this DIE.
1958 unsigned AbbrevNumber = Die->getAbbrevNumber();
1959 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1961 // Emit the code (index) for the abbreviation.
1962 if (Asm->isVerbose())
1963 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1964 Twine::utohexstr(Die->getOffset()) + ":0x" +
1965 Twine::utohexstr(Die->getSize()) + " " +
1966 dwarf::TagString(Abbrev->getTag()));
1967 Asm->EmitULEB128(AbbrevNumber);
1969 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1970 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1972 // Emit the DIE attribute values.
1973 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1974 unsigned Attr = AbbrevData[i].getAttribute();
1975 unsigned Form = AbbrevData[i].getForm();
1976 assert(Form && "Too many attributes for DIE (check abbreviation)");
1978 if (Asm->isVerbose())
1979 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1982 case dwarf::DW_AT_abstract_origin: {
1983 DIEEntry *E = cast<DIEEntry>(Values[i]);
1984 DIE *Origin = E->getEntry();
1985 unsigned Addr = Origin->getOffset();
1986 if (Form == dwarf::DW_FORM_ref_addr) {
1987 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1988 // section. Origin->getOffset() returns the offset from start of the
1990 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1991 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1993 Asm->OutStreamer.EmitIntValue(Addr,
1994 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1997 case dwarf::DW_AT_ranges: {
1998 // DW_AT_range Value encodes offset in debug_range section.
1999 DIEInteger *V = cast<DIEInteger>(Values[i]);
2001 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
2002 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2006 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2008 DwarfDebugRangeSectionSym,
2013 case dwarf::DW_AT_location: {
2014 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2015 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2016 Asm->EmitLabelReference(L->getValue(), 4);
2018 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2020 Values[i]->EmitValue(Asm, Form);
2024 case dwarf::DW_AT_accessibility: {
2025 if (Asm->isVerbose()) {
2026 DIEInteger *V = cast<DIEInteger>(Values[i]);
2027 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2029 Values[i]->EmitValue(Asm, Form);
2033 // Emit an attribute using the defined form.
2034 Values[i]->EmitValue(Asm, Form);
2039 // Emit the DIE children if any.
2040 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2041 const std::vector<DIE *> &Children = Die->getChildren();
2043 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2044 emitDIE(Children[j], Abbrevs);
2046 if (Asm->isVerbose())
2047 Asm->OutStreamer.AddComment("End Of Children Mark");
2052 // Emit the various dwarf units to the unit section USection with
2053 // the abbreviations going into ASection.
2054 void DwarfUnits::emitUnits(DwarfDebug *DD,
2055 const MCSection *USection,
2056 const MCSection *ASection,
2057 const MCSymbol *ASectionSym) {
2058 Asm->OutStreamer.SwitchSection(USection);
2059 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2060 E = CUs.end(); I != E; ++I) {
2061 CompileUnit *TheCU = *I;
2062 DIE *Die = TheCU->getCUDie();
2064 // Emit the compile units header.
2066 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2067 TheCU->getUniqueID()));
2069 // Emit size of content not including length itself
2070 unsigned ContentSize = Die->getSize() +
2071 sizeof(int16_t) + // DWARF version number
2072 sizeof(int32_t) + // Offset Into Abbrev. Section
2073 sizeof(int8_t); // Pointer Size (in bytes)
2075 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2076 Asm->EmitInt32(ContentSize);
2077 Asm->OutStreamer.AddComment("DWARF version number");
2078 Asm->EmitInt16(DD->getDwarfVersion());
2079 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2080 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2082 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2083 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2085 DD->emitDIE(Die, Abbreviations);
2086 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2087 TheCU->getUniqueID()));
2091 /// For a given compile unit DIE, returns offset from beginning of debug info.
2092 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2093 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2094 "Input DIE should be compile unit in getCUOffset.");
2095 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2097 CompileUnit *TheCU = *I;
2098 if (TheCU->getCUDie() == Die)
2099 return TheCU->getDebugInfoOffset();
2101 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2104 // Emit the debug info section.
2105 void DwarfDebug::emitDebugInfo() {
2106 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2108 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2109 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2110 DwarfAbbrevSectionSym);
2113 // Emit the abbreviation section.
2114 void DwarfDebug::emitAbbreviations() {
2115 if (!useSplitDwarf())
2116 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2119 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2122 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2123 std::vector<DIEAbbrev *> *Abbrevs) {
2124 // Check to see if it is worth the effort.
2125 if (!Abbrevs->empty()) {
2126 // Start the debug abbrev section.
2127 Asm->OutStreamer.SwitchSection(Section);
2129 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2130 Asm->OutStreamer.EmitLabel(Begin);
2132 // For each abbrevation.
2133 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2134 // Get abbreviation data
2135 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2137 // Emit the abbrevations code (base 1 index.)
2138 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2140 // Emit the abbreviations data.
2144 // Mark end of abbreviations.
2145 Asm->EmitULEB128(0, "EOM(3)");
2147 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2148 Asm->OutStreamer.EmitLabel(End);
2152 // Emit the last address of the section and the end of the line matrix.
2153 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2154 // Define last address of section.
2155 Asm->OutStreamer.AddComment("Extended Op");
2158 Asm->OutStreamer.AddComment("Op size");
2159 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2160 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2161 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2163 Asm->OutStreamer.AddComment("Section end label");
2165 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2166 Asm->getDataLayout().getPointerSize());
2168 // Mark end of matrix.
2169 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2175 // Emit visible names into a hashed accelerator table section.
2176 void DwarfDebug::emitAccelNames() {
2177 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2178 dwarf::DW_FORM_data4));
2179 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2180 E = CUMap.end(); I != E; ++I) {
2181 CompileUnit *TheCU = I->second;
2182 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2183 for (StringMap<std::vector<DIE*> >::const_iterator
2184 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2185 StringRef Name = GI->getKey();
2186 const std::vector<DIE *> &Entities = GI->second;
2187 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2188 DE = Entities.end(); DI != DE; ++DI)
2189 AT.AddName(Name, (*DI));
2193 AT.FinalizeTable(Asm, "Names");
2194 Asm->OutStreamer.SwitchSection(
2195 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2196 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2197 Asm->OutStreamer.EmitLabel(SectionBegin);
2199 // Emit the full data.
2200 AT.Emit(Asm, SectionBegin, &InfoHolder);
2203 // Emit objective C classes and categories into a hashed accelerator table
2205 void DwarfDebug::emitAccelObjC() {
2206 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2207 dwarf::DW_FORM_data4));
2208 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2209 E = CUMap.end(); I != E; ++I) {
2210 CompileUnit *TheCU = I->second;
2211 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2212 for (StringMap<std::vector<DIE*> >::const_iterator
2213 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2214 StringRef Name = GI->getKey();
2215 const std::vector<DIE *> &Entities = GI->second;
2216 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2217 DE = Entities.end(); DI != DE; ++DI)
2218 AT.AddName(Name, (*DI));
2222 AT.FinalizeTable(Asm, "ObjC");
2223 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2224 .getDwarfAccelObjCSection());
2225 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2226 Asm->OutStreamer.EmitLabel(SectionBegin);
2228 // Emit the full data.
2229 AT.Emit(Asm, SectionBegin, &InfoHolder);
2232 // Emit namespace dies into a hashed accelerator table.
2233 void DwarfDebug::emitAccelNamespaces() {
2234 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2235 dwarf::DW_FORM_data4));
2236 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2237 E = CUMap.end(); I != E; ++I) {
2238 CompileUnit *TheCU = I->second;
2239 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2240 for (StringMap<std::vector<DIE*> >::const_iterator
2241 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2242 StringRef Name = GI->getKey();
2243 const std::vector<DIE *> &Entities = GI->second;
2244 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2245 DE = Entities.end(); DI != DE; ++DI)
2246 AT.AddName(Name, (*DI));
2250 AT.FinalizeTable(Asm, "namespac");
2251 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2252 .getDwarfAccelNamespaceSection());
2253 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2254 Asm->OutStreamer.EmitLabel(SectionBegin);
2256 // Emit the full data.
2257 AT.Emit(Asm, SectionBegin, &InfoHolder);
2260 // Emit type dies into a hashed accelerator table.
2261 void DwarfDebug::emitAccelTypes() {
2262 std::vector<DwarfAccelTable::Atom> Atoms;
2263 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2264 dwarf::DW_FORM_data4));
2265 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag,
2266 dwarf::DW_FORM_data2));
2267 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags,
2268 dwarf::DW_FORM_data1));
2269 DwarfAccelTable AT(Atoms);
2270 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2271 E = CUMap.end(); I != E; ++I) {
2272 CompileUnit *TheCU = I->second;
2273 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2274 = TheCU->getAccelTypes();
2275 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2276 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2277 StringRef Name = GI->getKey();
2278 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2279 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2280 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2281 AT.AddName(Name, (*DI).first, (*DI).second);
2285 AT.FinalizeTable(Asm, "types");
2286 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2287 .getDwarfAccelTypesSection());
2288 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2289 Asm->OutStreamer.EmitLabel(SectionBegin);
2291 // Emit the full data.
2292 AT.Emit(Asm, SectionBegin, &InfoHolder);
2295 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2297 void DwarfDebug::emitDebugPubNames() {
2298 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2299 const MCSection *PSec = Asm->getObjFileLowering().getDwarfPubNamesSection();
2301 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2302 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2303 CompileUnit *TheCU = I->second;
2304 unsigned ID = TheCU->getUniqueID();
2306 if (TheCU->getGlobalNames().empty())
2309 // Start the dwarf pubnames section.
2310 Asm->OutStreamer.SwitchSection(PSec);
2312 Asm->OutStreamer.AddComment("Length of Public Names Info");
2313 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2314 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2316 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2318 Asm->OutStreamer.AddComment("DWARF Version");
2319 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2321 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2322 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2323 DwarfInfoSectionSym);
2325 Asm->OutStreamer.AddComment("Compilation Unit Length");
2326 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2327 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2330 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2331 for (StringMap<DIE*>::const_iterator
2332 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2333 const char *Name = GI->getKeyData();
2334 const DIE *Entity = GI->second;
2336 Asm->OutStreamer.AddComment("DIE offset");
2337 Asm->EmitInt32(Entity->getOffset());
2339 if (Asm->isVerbose())
2340 Asm->OutStreamer.AddComment("External Name");
2341 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2344 Asm->OutStreamer.AddComment("End Mark");
2346 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2350 void DwarfDebug::emitDebugPubTypes() {
2351 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2352 E = CUMap.end(); I != E; ++I) {
2353 CompileUnit *TheCU = I->second;
2354 // Start the dwarf pubtypes section.
2355 Asm->OutStreamer.SwitchSection(
2356 Asm->getObjFileLowering().getDwarfPubTypesSection());
2357 Asm->OutStreamer.AddComment("Length of Public Types Info");
2358 Asm->EmitLabelDifference(
2359 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2360 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2362 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2363 TheCU->getUniqueID()));
2365 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2366 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2368 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2369 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2370 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2371 TheCU->getUniqueID()),
2372 DwarfInfoSectionSym);
2374 Asm->OutStreamer.AddComment("Compilation Unit Length");
2375 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2376 TheCU->getUniqueID()),
2377 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2378 TheCU->getUniqueID()),
2381 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2382 for (StringMap<DIE*>::const_iterator
2383 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2384 const char *Name = GI->getKeyData();
2385 DIE *Entity = GI->second;
2387 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2388 Asm->EmitInt32(Entity->getOffset());
2390 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2391 // Emit the name with a terminating null byte.
2392 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2395 Asm->OutStreamer.AddComment("End Mark");
2397 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2398 TheCU->getUniqueID()));
2402 // Emit strings into a string section.
2403 void DwarfUnits::emitStrings(const MCSection *StrSection,
2404 const MCSection *OffsetSection = NULL,
2405 const MCSymbol *StrSecSym = NULL) {
2407 if (StringPool.empty()) return;
2409 // Start the dwarf str section.
2410 Asm->OutStreamer.SwitchSection(StrSection);
2412 // Get all of the string pool entries and put them in an array by their ID so
2413 // we can sort them.
2414 SmallVector<std::pair<unsigned,
2415 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2417 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2418 I = StringPool.begin(), E = StringPool.end();
2420 Entries.push_back(std::make_pair(I->second.second, &*I));
2422 array_pod_sort(Entries.begin(), Entries.end());
2424 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2425 // Emit a label for reference from debug information entries.
2426 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2428 // Emit the string itself with a terminating null byte.
2429 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2430 Entries[i].second->getKeyLength()+1));
2433 // If we've got an offset section go ahead and emit that now as well.
2434 if (OffsetSection) {
2435 Asm->OutStreamer.SwitchSection(OffsetSection);
2436 unsigned offset = 0;
2437 unsigned size = 4; // FIXME: DWARF64 is 8.
2438 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2439 Asm->OutStreamer.EmitIntValue(offset, size);
2440 offset += Entries[i].second->getKeyLength() + 1;
2445 // Emit strings into a string section.
2446 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2448 if (AddressPool.empty()) return;
2450 // Start the dwarf addr section.
2451 Asm->OutStreamer.SwitchSection(AddrSection);
2453 // Order the address pool entries by ID
2454 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2456 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2457 E = AddressPool.end();
2459 Entries[I->second] = I->first;
2461 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2462 // Emit an expression for reference from debug information entries.
2463 if (const MCExpr *Expr = Entries[i])
2464 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2466 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2471 // Emit visible names into a debug str section.
2472 void DwarfDebug::emitDebugStr() {
2473 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2474 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2477 // Emit locations into the debug loc section.
2478 void DwarfDebug::emitDebugLoc() {
2479 if (DotDebugLocEntries.empty())
2482 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2483 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2485 DotDebugLocEntry &Entry = *I;
2486 if (I + 1 != DotDebugLocEntries.end())
2490 // Start the dwarf loc section.
2491 Asm->OutStreamer.SwitchSection(
2492 Asm->getObjFileLowering().getDwarfLocSection());
2493 unsigned char Size = Asm->getDataLayout().getPointerSize();
2494 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2496 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2497 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2498 I != E; ++I, ++index) {
2499 DotDebugLocEntry &Entry = *I;
2500 if (Entry.isMerged()) continue;
2501 if (Entry.isEmpty()) {
2502 Asm->OutStreamer.EmitIntValue(0, Size);
2503 Asm->OutStreamer.EmitIntValue(0, Size);
2504 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2506 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2507 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2508 DIVariable DV(Entry.getVariable());
2509 Asm->OutStreamer.AddComment("Loc expr size");
2510 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2511 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2512 Asm->EmitLabelDifference(end, begin, 2);
2513 Asm->OutStreamer.EmitLabel(begin);
2514 if (Entry.isInt()) {
2515 DIBasicType BTy(DV.getType());
2517 (BTy.getEncoding() == dwarf::DW_ATE_signed
2518 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2519 Asm->OutStreamer.AddComment("DW_OP_consts");
2520 Asm->EmitInt8(dwarf::DW_OP_consts);
2521 Asm->EmitSLEB128(Entry.getInt());
2523 Asm->OutStreamer.AddComment("DW_OP_constu");
2524 Asm->EmitInt8(dwarf::DW_OP_constu);
2525 Asm->EmitULEB128(Entry.getInt());
2527 } else if (Entry.isLocation()) {
2528 MachineLocation Loc = Entry.getLoc();
2529 if (!DV.hasComplexAddress())
2531 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2533 // Complex address entry.
2534 unsigned N = DV.getNumAddrElements();
2536 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2537 if (Loc.getOffset()) {
2539 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2540 Asm->OutStreamer.AddComment("DW_OP_deref");
2541 Asm->EmitInt8(dwarf::DW_OP_deref);
2542 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2543 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2544 Asm->EmitSLEB128(DV.getAddrElement(1));
2546 // If first address element is OpPlus then emit
2547 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2548 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2549 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2553 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2556 // Emit remaining complex address elements.
2557 for (; i < N; ++i) {
2558 uint64_t Element = DV.getAddrElement(i);
2559 if (Element == DIBuilder::OpPlus) {
2560 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2561 Asm->EmitULEB128(DV.getAddrElement(++i));
2562 } else if (Element == DIBuilder::OpDeref) {
2564 Asm->EmitInt8(dwarf::DW_OP_deref);
2566 llvm_unreachable("unknown Opcode found in complex address");
2570 // else ... ignore constant fp. There is not any good way to
2571 // to represent them here in dwarf.
2572 Asm->OutStreamer.EmitLabel(end);
2577 // Emit visible names into a debug aranges section.
2578 void DwarfDebug::emitDebugARanges() {
2579 // Start the dwarf aranges section.
2581 .SwitchSection(Asm->getObjFileLowering().getDwarfARangesSection());
2584 // Emit visible names into a debug ranges section.
2585 void DwarfDebug::emitDebugRanges() {
2586 // Start the dwarf ranges section.
2588 .SwitchSection(Asm->getObjFileLowering().getDwarfRangesSection());
2589 unsigned char Size = Asm->getDataLayout().getPointerSize();
2590 for (SmallVectorImpl<const MCSymbol *>::iterator
2591 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2594 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2596 Asm->OutStreamer.EmitIntValue(0, Size);
2600 // Emit visible names into a debug macinfo section.
2601 void DwarfDebug::emitDebugMacInfo() {
2602 if (const MCSection *LineInfo =
2603 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2604 // Start the dwarf macinfo section.
2605 Asm->OutStreamer.SwitchSection(LineInfo);
2609 // DWARF5 Experimental Separate Dwarf emitters.
2611 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2612 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2613 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2614 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2615 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2617 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2618 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2619 Asm, this, &SkeletonHolder);
2621 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2622 DICompileUnit(CU->getNode()).getSplitDebugFilename());
2624 // Relocate to the beginning of the addr_base section, else 0 for the
2625 // beginning of the one for this compile unit.
2626 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2627 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2628 DwarfAddrSectionSym);
2630 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2631 dwarf::DW_FORM_sec_offset, 0);
2633 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2634 // into an entity. We're using 0, or a NULL label for this.
2635 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2637 // DW_AT_stmt_list is a offset of line number information for this
2638 // compile unit in debug_line section.
2639 // FIXME: Should handle multiple compile units.
2640 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2641 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2642 DwarfLineSectionSym);
2644 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2646 if (!CompilationDir.empty())
2647 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2649 SkeletonHolder.addUnit(NewCU);
2650 SkeletonCUs.push_back(NewCU);
2655 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2656 assert(useSplitDwarf() && "No split dwarf debug info?");
2657 emitAbbrevs(Section, &SkeletonAbbrevs);
2660 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2661 // compile units that would normally be in debug_info.
2662 void DwarfDebug::emitDebugInfoDWO() {
2663 assert(useSplitDwarf() && "No split dwarf debug info?");
2664 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2665 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2666 DwarfAbbrevDWOSectionSym);
2669 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2670 // abbreviations for the .debug_info.dwo section.
2671 void DwarfDebug::emitDebugAbbrevDWO() {
2672 assert(useSplitDwarf() && "No split dwarf?");
2673 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2677 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2678 // string section and is identical in format to traditional .debug_str
2680 void DwarfDebug::emitDebugStrDWO() {
2681 assert(useSplitDwarf() && "No split dwarf?");
2682 const MCSection *OffSec = Asm->getObjFileLowering()
2683 .getDwarfStrOffDWOSection();
2684 const MCSymbol *StrSym = DwarfStrSectionSym;
2685 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),