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"
17 #include "DwarfCompileUnit.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/Mangler.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Analysis/DebugInfo.h"
35 #include "llvm/Analysis/DIBuilder.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/Path.h"
48 static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
49 cl::desc("Print DbgScope information for each machine instruction"));
51 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
53 cl::desc("Disable debug info printing"));
55 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
56 cl::desc("Make an absence of debug location information explicit."),
60 STATISTIC(BlocksWithoutLineNo, "Number of blocks without any line number");
64 const char *DWARFGroupName = "DWARF Emission";
65 const char *DbgTimerName = "DWARF Debug Writer";
66 } // end anonymous namespace
68 //===----------------------------------------------------------------------===//
70 /// Configuration values for initial hash set sizes (log2).
72 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
76 DIType DbgVariable::getType() const {
77 DIType Ty = Var.getType();
78 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
80 if (Var.isBlockByrefVariable()) {
81 /* Byref variables, in Blocks, are declared by the programmer as
82 "SomeType VarName;", but the compiler creates a
83 __Block_byref_x_VarName struct, and gives the variable VarName
84 either the struct, or a pointer to the struct, as its type. This
85 is necessary for various behind-the-scenes things the compiler
86 needs to do with by-reference variables in blocks.
88 However, as far as the original *programmer* is concerned, the
89 variable should still have type 'SomeType', as originally declared.
91 The following function dives into the __Block_byref_x_VarName
92 struct to find the original type of the variable. This will be
93 passed back to the code generating the type for the Debug
94 Information Entry for the variable 'VarName'. 'VarName' will then
95 have the original type 'SomeType' in its debug information.
97 The original type 'SomeType' will be the type of the field named
98 'VarName' inside the __Block_byref_x_VarName struct.
100 NOTE: In order for this to not completely fail on the debugger
101 side, the Debug Information Entry for the variable VarName needs to
102 have a DW_AT_location that tells the debugger how to unwind through
103 the pointers and __Block_byref_x_VarName struct to find the actual
104 value of the variable. The function addBlockByrefType does this. */
106 unsigned tag = Ty.getTag();
108 if (tag == dwarf::DW_TAG_pointer_type) {
109 DIDerivedType DTy = DIDerivedType(Ty);
110 subType = DTy.getTypeDerivedFrom();
113 DICompositeType blockStruct = DICompositeType(subType);
114 DIArray Elements = blockStruct.getTypeArray();
116 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
117 DIDescriptor Element = Elements.getElement(i);
118 DIDerivedType DT = DIDerivedType(Element);
119 if (getName() == DT.getName())
120 return (DT.getTypeDerivedFrom());
127 //===----------------------------------------------------------------------===//
128 /// DbgRange - This is used to track range of instructions with identical
129 /// debug info scope.
131 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
133 //===----------------------------------------------------------------------===//
134 /// DbgScope - This class is used to track scope information.
137 DbgScope *Parent; // Parent to this scope.
138 DIDescriptor Desc; // Debug info descriptor for scope.
139 // Location at which this scope is inlined.
140 AssertingVH<const MDNode> InlinedAtLocation;
141 bool AbstractScope; // Abstract Scope
142 const MachineInstr *LastInsn; // Last instruction of this scope.
143 const MachineInstr *FirstInsn; // First instruction of this scope.
144 unsigned DFSIn, DFSOut;
145 // Scopes defined in scope. Contents not owned.
146 SmallVector<DbgScope *, 4> Scopes;
147 // Variables declared in scope. Contents owned.
148 SmallVector<DbgVariable *, 8> Variables;
149 SmallVector<DbgRange, 4> Ranges;
150 // Private state for dump()
151 mutable unsigned IndentLevel;
153 DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
154 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
155 LastInsn(0), FirstInsn(0),
156 DFSIn(0), DFSOut(0), IndentLevel(0) {}
160 DbgScope *getParent() const { return Parent; }
161 void setParent(DbgScope *P) { Parent = P; }
162 DIDescriptor getDesc() const { return Desc; }
163 const MDNode *getInlinedAt() const { return InlinedAtLocation; }
164 const MDNode *getScopeNode() const { return Desc; }
165 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
166 const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
167 const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
169 /// openInsnRange - This scope covers instruction range starting from MI.
170 void openInsnRange(const MachineInstr *MI) {
175 Parent->openInsnRange(MI);
178 /// extendInsnRange - Extend the current instruction range covered by
180 void extendInsnRange(const MachineInstr *MI) {
181 assert (FirstInsn && "MI Range is not open!");
184 Parent->extendInsnRange(MI);
187 /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
188 /// until now. This is used when a new scope is encountered while walking
189 /// machine instructions.
190 void closeInsnRange(DbgScope *NewScope = NULL) {
191 assert (LastInsn && "Last insn missing!");
192 Ranges.push_back(DbgRange(FirstInsn, LastInsn));
195 // If Parent dominates NewScope then do not close Parent's instruction
197 if (Parent && (!NewScope || !Parent->dominates(NewScope)))
198 Parent->closeInsnRange(NewScope);
201 void setAbstractScope() { AbstractScope = true; }
202 bool isAbstractScope() const { return AbstractScope; }
204 // Depth First Search support to walk and mainpluate DbgScope hierarchy.
205 unsigned getDFSOut() const { return DFSOut; }
206 void setDFSOut(unsigned O) { DFSOut = O; }
207 unsigned getDFSIn() const { return DFSIn; }
208 void setDFSIn(unsigned I) { DFSIn = I; }
209 bool dominates(const DbgScope *S) {
212 if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
217 /// addScope - Add a scope to the scope.
219 void addScope(DbgScope *S) { Scopes.push_back(S); }
221 /// addVariable - Add a variable to the scope.
223 void addVariable(DbgVariable *V) { Variables.push_back(V); }
230 } // end llvm namespace
233 void DbgScope::dump() const {
234 raw_ostream &err = dbgs();
235 err.indent(IndentLevel);
236 const MDNode *N = Desc;
239 err << "Abstract Scope\n";
243 err << "Children ...\n";
244 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
245 if (Scopes[i] != this)
252 DbgScope::~DbgScope() {
253 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
257 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
258 : Asm(A), MMI(Asm->MMI), FirstCU(0),
259 AbbreviationsSet(InitAbbreviationsSetSize),
260 CurrentFnDbgScope(0), PrevLabel(NULL) {
261 NextStringPoolNumber = 0;
263 DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
264 DwarfStrSectionSym = TextSectionSym = 0;
265 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
266 FunctionBeginSym = FunctionEndSym = 0;
268 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
272 DwarfDebug::~DwarfDebug() {
275 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
276 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
277 if (Entry.first) return Entry.first;
279 Entry.second = NextStringPoolNumber++;
280 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
284 /// assignAbbrevNumber - Define a unique number for the abbreviation.
286 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
287 // Profile the node so that we can make it unique.
291 // Check the set for priors.
292 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
294 // If it's newly added.
295 if (InSet == &Abbrev) {
296 // Add to abbreviation list.
297 Abbreviations.push_back(&Abbrev);
299 // Assign the vector position + 1 as its number.
300 Abbrev.setNumber(Abbreviations.size());
302 // Assign existing abbreviation number.
303 Abbrev.setNumber(InSet->getNumber());
307 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
308 /// printer to not emit usual symbol prefix before the symbol name is used then
309 /// return linkage name after skipping this special LLVM prefix.
310 static StringRef getRealLinkageName(StringRef LinkageName) {
312 if (LinkageName.startswith(StringRef(&One, 1)))
313 return LinkageName.substr(1);
317 /// createSubprogramDIE - Create new DIE using SP.
318 DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
319 CompileUnit *SPCU = getCompileUnit(SP);
320 DIE *SPDie = SPCU->getDIE(SP);
324 SPDie = new DIE(dwarf::DW_TAG_subprogram);
326 // DW_TAG_inlined_subroutine may refer to this DIE.
327 SPCU->insertDIE(SP, SPDie);
329 // Add to context owner.
330 SPCU->addToContextOwner(SPDie, SP.getContext());
332 // Add function template parameters.
333 SPCU->addTemplateParams(*SPDie, SP.getTemplateParams());
335 // If this DIE is going to refer declaration info using AT_specification
336 // then there is no need to add other attributes.
337 if (SP.getFunctionDeclaration().isSubprogram())
340 // Constructors and operators for anonymous aggregates do not have names.
341 if (!SP.getName().empty())
342 SPCU->addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
345 StringRef LinkageName = SP.getLinkageName();
346 if (!LinkageName.empty())
347 SPCU->addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
348 getRealLinkageName(LinkageName));
350 SPCU->addSourceLine(SPDie, SP);
352 if (SP.isPrototyped())
353 SPCU->addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
356 DICompositeType SPTy = SP.getType();
357 DIArray Args = SPTy.getTypeArray();
358 unsigned SPTag = SPTy.getTag();
360 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
361 SPCU->addType(SPDie, SPTy);
363 SPCU->addType(SPDie, DIType(Args.getElement(0)));
365 unsigned VK = SP.getVirtuality();
367 SPCU->addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
368 DIEBlock *Block = SPCU->getDIEBlock();
369 SPCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
370 SPCU->addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
371 SPCU->addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
372 ContainingTypeMap.insert(std::make_pair(SPDie,
373 SP.getContainingType()));
376 if (!SP.isDefinition()) {
377 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
379 // Add arguments. Do not add arguments for subprogram definition. They will
380 // be handled while processing variables.
381 DICompositeType SPTy = SP.getType();
382 DIArray Args = SPTy.getTypeArray();
383 unsigned SPTag = SPTy.getTag();
385 if (SPTag == dwarf::DW_TAG_subroutine_type)
386 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
387 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
388 DIType ATy = DIType(DIType(Args.getElement(i)));
389 SPCU->addType(Arg, ATy);
390 if (ATy.isArtificial())
391 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
392 SPDie->addChild(Arg);
396 if (SP.isArtificial())
397 SPCU->addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
399 if (!SP.isLocalToUnit())
400 SPCU->addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
402 if (SP.isOptimized())
403 SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
405 if (unsigned isa = Asm->getISAEncoding()) {
406 SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
412 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
413 assert(N && "Invalid Scope encoding!");
415 DbgScope *AScope = AbstractScopes.lookup(N);
419 DbgScope *Parent = NULL;
421 DIDescriptor Scope(N);
422 if (Scope.isLexicalBlock()) {
423 DILexicalBlock DB(N);
424 DIDescriptor ParentDesc = DB.getContext();
425 Parent = getOrCreateAbstractScope(ParentDesc);
428 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
431 Parent->addScope(AScope);
432 AScope->setAbstractScope();
433 AbstractScopes[N] = AScope;
434 if (DIDescriptor(N).isSubprogram())
435 AbstractScopesList.push_back(AScope);
439 /// isSubprogramContext - Return true if Context is either a subprogram
440 /// or another context nested inside a subprogram.
441 static bool isSubprogramContext(const MDNode *Context) {
444 DIDescriptor D(Context);
445 if (D.isSubprogram())
448 return isSubprogramContext(DIType(Context).getContext());
452 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
453 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
454 /// If there are global variables in this scope then create and insert
455 /// DIEs for these variables.
456 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
457 CompileUnit *SPCU = getCompileUnit(SPNode);
458 DIE *SPDie = SPCU->getDIE(SPNode);
460 assert(SPDie && "Unable to find subprogram DIE!");
461 DISubprogram SP(SPNode);
463 DISubprogram SPDecl = SP.getFunctionDeclaration();
464 if (SPDecl.isSubprogram())
465 // Refer function declaration directly.
466 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
467 createSubprogramDIE(SPDecl));
469 // There is not any need to generate specification DIE for a function
470 // defined at compile unit level. If a function is defined inside another
471 // function then gdb prefers the definition at top level and but does not
472 // expect specification DIE in parent function. So avoid creating
473 // specification DIE for a function defined inside a function.
474 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
475 !SP.getContext().isFile() &&
476 !isSubprogramContext(SP.getContext())) {
477 SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
480 DICompositeType SPTy = SP.getType();
481 DIArray Args = SPTy.getTypeArray();
482 unsigned SPTag = SPTy.getTag();
483 if (SPTag == dwarf::DW_TAG_subroutine_type)
484 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
485 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
486 DIType ATy = DIType(DIType(Args.getElement(i)));
487 SPCU->addType(Arg, ATy);
488 if (ATy.isArtificial())
489 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
490 SPDie->addChild(Arg);
492 DIE *SPDeclDie = SPDie;
493 SPDie = new DIE(dwarf::DW_TAG_subprogram);
494 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
499 // Pick up abstract subprogram DIE.
500 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
501 SPDie = new DIE(dwarf::DW_TAG_subprogram);
502 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
503 dwarf::DW_FORM_ref4, AbsSPDIE);
507 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
508 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
509 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
510 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
511 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
512 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
513 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
518 /// constructLexicalScope - Construct new DW_TAG_lexical_block
519 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
520 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
522 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
523 if (Scope->isAbstractScope())
526 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
530 CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode());
531 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
532 if (Ranges.size() > 1) {
533 // .debug_range section has not been laid out yet. Emit offset in
534 // .debug_range as a uint, size 4, for now. emitDIE will handle
535 // DW_AT_ranges appropriately.
536 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
537 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
538 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
539 RE = Ranges.end(); RI != RE; ++RI) {
540 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
541 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
543 DebugRangeSymbols.push_back(NULL);
544 DebugRangeSymbols.push_back(NULL);
548 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
549 const MCSymbol *End = getLabelAfterInsn(RI->second);
551 if (End == 0) return 0;
553 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
554 assert(End->isDefined() && "Invalid end label for an inlined scope!");
556 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
557 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
562 /// constructInlinedScopeDIE - This scope represents inlined body of
563 /// a function. Construct DIE to represent this concrete inlined copy
565 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
567 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
568 assert (Ranges.empty() == false
569 && "DbgScope does not have instruction markers!");
571 // FIXME : .debug_inlined section specification does not clearly state how
572 // to emit inlined scope that is split into multiple instruction ranges.
573 // For now, use first instruction range and emit low_pc/high_pc pair and
574 // corresponding .debug_inlined section entry for this pair.
575 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
576 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
577 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
579 if (StartLabel == 0 || EndLabel == 0) {
580 assert (0 && "Unexpected Start and End labels for a inlined scope!");
583 assert(StartLabel->isDefined() &&
584 "Invalid starting label for an inlined scope!");
585 assert(EndLabel->isDefined() &&
586 "Invalid end label for an inlined scope!");
588 if (!Scope->getScopeNode())
590 DIScope DS(Scope->getScopeNode());
591 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
593 DISubprogram InlinedSP = getDISubprogram(DS);
594 CompileUnit *TheCU = getCompileUnit(InlinedSP);
595 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
596 assert(OriginDIE && "Unable to find Origin DIE!");
597 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
598 dwarf::DW_FORM_ref4, OriginDIE);
600 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
601 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
603 InlinedSubprogramDIEs.insert(OriginDIE);
605 // Track the start label for this inlined function.
606 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
607 I = InlineInfo.find(InlinedSP);
609 if (I == InlineInfo.end()) {
610 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
612 InlinedSPNodes.push_back(InlinedSP);
614 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
616 DILocation DL(Scope->getInlinedAt());
617 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
618 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
624 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
625 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
626 StringRef Name = DV->getName();
630 // Translate tag to proper Dwarf tag. The result variable is dropped for
633 switch (DV->getTag()) {
634 case dwarf::DW_TAG_return_variable:
636 case dwarf::DW_TAG_arg_variable:
637 Tag = dwarf::DW_TAG_formal_parameter;
639 case dwarf::DW_TAG_auto_variable: // fall thru
641 Tag = dwarf::DW_TAG_variable;
645 // Define variable debug information entry.
646 DIE *VariableDie = new DIE(Tag);
647 CompileUnit *VariableCU = getCompileUnit(DV->getVariable());
649 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
650 V2AVI = VarToAbstractVarMap.find(DV);
651 if (V2AVI != VarToAbstractVarMap.end())
652 AbsDIE = V2AVI->second->getDIE();
655 VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
656 dwarf::DW_FORM_ref4, AbsDIE);
658 VariableCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
660 VariableCU->addSourceLine(VariableDie, DV->getVariable());
662 // Add variable type.
663 VariableCU->addType(VariableDie, DV->getType());
666 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
667 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
668 dwarf::DW_FORM_flag, 1);
669 else if (DIVariable(DV->getVariable()).isArtificial())
670 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
671 dwarf::DW_FORM_flag, 1);
673 if (Scope->isAbstractScope()) {
674 DV->setDIE(VariableDie);
678 // Add variable address.
680 unsigned Offset = DV->getDotDebugLocOffset();
682 VariableCU->addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
683 Asm->GetTempSymbol("debug_loc", Offset));
684 DV->setDIE(VariableDie);
685 UseDotDebugLocEntry.insert(VariableDie);
689 // Check if variable is described by a DBG_VALUE instruction.
690 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
691 DbgVariableToDbgInstMap.find(DV);
692 if (DVI != DbgVariableToDbgInstMap.end()) {
693 const MachineInstr *DVInsn = DVI->second;
694 bool updated = false;
695 // FIXME : Handle getNumOperands != 3
696 if (DVInsn->getNumOperands() == 3) {
697 if (DVInsn->getOperand(0).isReg()) {
698 const MachineOperand RegOp = DVInsn->getOperand(0);
699 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
700 if (DVInsn->getOperand(1).isImm() &&
701 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
702 unsigned FrameReg = 0;
703 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
705 TFI->getFrameIndexReference(*Asm->MF,
706 DVInsn->getOperand(1).getImm(),
708 MachineLocation Location(FrameReg, Offset);
709 VariableCU->addVariableAddress(DV, VariableDie, Location);
711 } else if (RegOp.getReg())
712 VariableCU->addVariableAddress(DV, VariableDie,
713 MachineLocation(RegOp.getReg()));
716 else if (DVInsn->getOperand(0).isImm())
717 updated = VariableCU->addConstantValue(VariableDie,
718 DVInsn->getOperand(0));
719 else if (DVInsn->getOperand(0).isFPImm())
721 VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
723 VariableCU->addVariableAddress(DV, VariableDie,
724 Asm->getDebugValueLocation(DVInsn));
728 // If variableDie is not updated then DBG_VALUE instruction does not
729 // have valid variable info.
733 DV->setDIE(VariableDie);
737 // .. else use frame index, if available.
739 if (findVariableFrameIndex(DV, &FI)) {
740 unsigned FrameReg = 0;
741 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
743 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
744 MachineLocation Location(FrameReg, Offset);
745 VariableCU->addVariableAddress(DV, VariableDie, Location);
748 DV->setDIE(VariableDie);
753 void CompileUnit::addPubTypes(DISubprogram SP) {
754 DICompositeType SPTy = SP.getType();
755 unsigned SPTag = SPTy.getTag();
756 if (SPTag != dwarf::DW_TAG_subroutine_type)
759 DIArray Args = SPTy.getTypeArray();
760 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
761 DIType ATy(Args.getElement(i));
764 DICompositeType CATy = getDICompositeType(ATy);
765 if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
766 && !CATy.isForwardDecl()) {
767 if (DIEEntry *Entry = getDIEEntry(CATy))
768 addGlobalType(CATy.getName(), Entry->getEntry());
773 /// constructScopeDIE - Construct a DIE for this scope.
774 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
775 if (!Scope || !Scope->getScopeNode())
778 SmallVector <DIE *, 8> Children;
780 // Collect arguments for current function.
781 if (Scope == CurrentFnDbgScope)
782 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
783 if (DbgVariable *ArgDV = CurrentFnArguments[i])
784 if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
785 Children.push_back(Arg);
787 // Collect lexical scope childrens first.
788 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
789 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
790 if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
791 Children.push_back(Variable);
792 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
793 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
794 if (DIE *Nested = constructScopeDIE(Scopes[j]))
795 Children.push_back(Nested);
796 DIScope DS(Scope->getScopeNode());
797 DIE *ScopeDIE = NULL;
798 if (Scope->getInlinedAt())
799 ScopeDIE = constructInlinedScopeDIE(Scope);
800 else if (DS.isSubprogram()) {
801 ProcessedSPNodes.insert(DS);
802 if (Scope->isAbstractScope()) {
803 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
804 // Note down abstract DIE.
806 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
809 ScopeDIE = updateSubprogramScopeDIE(DS);
812 // There is no need to emit empty lexical block DIE.
813 if (Children.empty())
815 ScopeDIE = constructLexicalScopeDIE(Scope);
818 if (!ScopeDIE) return NULL;
821 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
822 E = Children.end(); I != E; ++I)
823 ScopeDIE->addChild(*I);
825 if (DS.isSubprogram())
826 getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
831 /// GetOrCreateSourceID - Look up the source id with the given directory and
832 /// source file names. If none currently exists, create a new id and insert it
833 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
836 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
838 // If FE did not provide a file name, then assume stdin.
839 if (FileName.empty())
840 return GetOrCreateSourceID("<stdin>", StringRef());
842 // MCStream expects full path name as filename.
843 if (!DirName.empty() && !FileName.startswith("/")) {
844 std::string FullPathName(DirName.data());
845 if (!DirName.endswith("/"))
847 FullPathName += FileName.data();
848 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
849 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
852 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
853 if (Entry.getValue())
854 return Entry.getValue();
856 unsigned SrcId = SourceIdMap.size();
857 Entry.setValue(SrcId);
859 // Print out a .file directive to specify files for .loc directives.
860 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
865 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
866 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
867 DIE *NDie = getDIE(NS);
870 NDie = new DIE(dwarf::DW_TAG_namespace);
872 if (!NS.getName().empty())
873 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
874 addSourceLine(NDie, NS);
875 addToContextOwner(NDie, NS.getContext());
879 /// constructCompileUnit - Create new CompileUnit for the given
880 /// metadata node with tag DW_TAG_compile_unit.
881 void DwarfDebug::constructCompileUnit(const MDNode *N) {
882 DICompileUnit DIUnit(N);
883 StringRef FN = DIUnit.getFilename();
884 StringRef Dir = DIUnit.getDirectory();
885 unsigned ID = GetOrCreateSourceID(FN, Dir);
887 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
888 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
889 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
890 DIUnit.getProducer());
891 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
892 DIUnit.getLanguage());
893 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
894 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
895 // simplifies debug range entries.
896 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
897 // DW_AT_stmt_list is a offset of line number information for this
898 // compile unit in debug_line section.
899 if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
900 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
901 Asm->GetTempSymbol("section_line"));
903 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
906 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
907 if (DIUnit.isOptimized())
908 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
910 StringRef Flags = DIUnit.getFlags();
912 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
914 unsigned RVer = DIUnit.getRunTimeVersion();
916 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
917 dwarf::DW_FORM_data1, RVer);
921 CUMap.insert(std::make_pair(N, NewCU));
924 /// getCompielUnit - Get CompileUnit DIE.
925 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
926 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
928 const MDNode *CUNode = NULL;
929 if (D.isCompileUnit())
931 else if (D.isSubprogram())
932 CUNode = DISubprogram(N).getCompileUnit();
934 CUNode = DIType(N).getCompileUnit();
935 else if (D.isGlobalVariable())
936 CUNode = DIGlobalVariable(N).getCompileUnit();
937 else if (D.isVariable())
938 CUNode = DIVariable(N).getCompileUnit();
939 else if (D.isNameSpace())
940 CUNode = DINameSpace(N).getCompileUnit();
942 CUNode = DIFile(N).getCompileUnit();
946 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
947 = CUMap.find(CUNode);
948 if (I == CUMap.end())
953 /// isUnsignedDIType - Return true if type encoding is unsigned.
954 static bool isUnsignedDIType(DIType Ty) {
955 DIDerivedType DTy(Ty);
957 return isUnsignedDIType(DTy.getTypeDerivedFrom());
961 unsigned Encoding = BTy.getEncoding();
962 if (Encoding == dwarf::DW_ATE_unsigned ||
963 Encoding == dwarf::DW_ATE_unsigned_char)
969 // Return const exprssion if value is a GEP to access merged global
971 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
972 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
973 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
974 if (!CE || CE->getNumOperands() != 3 ||
975 CE->getOpcode() != Instruction::GetElementPtr)
978 // First operand points to a global value.
979 if (!isa<GlobalValue>(CE->getOperand(0)))
982 // Second operand is zero.
983 const ConstantInt *CI =
984 dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
985 if (!CI || !CI->isZero())
988 // Third operand is offset.
989 if (!isa<ConstantInt>(CE->getOperand(2)))
995 /// constructGlobalVariableDIE - Construct global variable DIE.
996 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
997 DIGlobalVariable GV(N);
999 // If debug information is malformed then ignore it.
1000 if (GV.Verify() == false)
1003 // Check for pre-existence.
1004 CompileUnit *TheCU = getCompileUnit(N);
1005 if (TheCU->getDIE(GV))
1008 DIType GTy = GV.getType();
1009 DIE *VariableDIE = new DIE(GV.getTag());
1011 bool isGlobalVariable = GV.getGlobal() != NULL;
1014 TheCU->addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1015 GV.getDisplayName());
1016 StringRef LinkageName = GV.getLinkageName();
1017 if (!LinkageName.empty() && isGlobalVariable)
1018 TheCU->addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1019 dwarf::DW_FORM_string,
1020 getRealLinkageName(LinkageName));
1022 TheCU->addType(VariableDIE, GTy);
1023 if (GTy.isCompositeType() && !GTy.getName().empty()
1024 && !GTy.isForwardDecl()) {
1025 DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1026 assert(Entry && "Missing global type!");
1027 TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1029 // Add scoping info.
1030 if (!GV.isLocalToUnit()) {
1031 TheCU->addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1032 // Expose as global.
1033 TheCU->addGlobal(GV.getName(), VariableDIE);
1035 // Add line number info.
1036 TheCU->addSourceLine(VariableDIE, GV);
1038 TheCU->insertDIE(N, VariableDIE);
1039 // Add to context owner.
1040 DIDescriptor GVContext = GV.getContext();
1041 TheCU->addToContextOwner(VariableDIE, GVContext);
1043 if (isGlobalVariable) {
1044 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1045 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1046 TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1047 Asm->Mang->getSymbol(GV.getGlobal()));
1048 // Do not create specification DIE if context is either compile unit
1050 if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1051 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1052 // Create specification DIE.
1053 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1054 TheCU->addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1055 dwarf::DW_FORM_ref4, VariableDIE);
1056 TheCU->addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1057 TheCU->addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1058 TheCU->addDie(VariableSpecDIE);
1060 TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1062 } else if (ConstantInt *CI =
1063 dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1064 TheCU->addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy));
1065 else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1066 // GV is a merged global.
1067 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1068 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1069 TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1070 Asm->Mang->getSymbol(cast<GlobalValue>(CE->getOperand(0))));
1071 ConstantInt *CII = cast<ConstantInt>(CE->getOperand(2));
1072 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1073 TheCU->addUInt(Block, 0, dwarf::DW_FORM_udata, CII->getZExtValue());
1074 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1075 TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1081 /// construct SubprogramDIE - Construct subprogram DIE.
1082 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1085 // Check for pre-existence.
1086 CompileUnit *TheCU = getCompileUnit(N);
1087 if (TheCU->getDIE(N))
1090 if (!SP.isDefinition())
1091 // This is a method declaration which will be handled while constructing
1095 DIE *SubprogramDie = createSubprogramDIE(SP);
1098 TheCU->insertDIE(N, SubprogramDie);
1100 // Add to context owner.
1101 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
1103 // Expose as global.
1104 TheCU->addGlobal(SP.getName(), SubprogramDie);
1109 /// beginModule - Emit all Dwarf sections that should come prior to the
1110 /// content. Create global DIEs and emit initial debug info sections.
1111 /// This is inovked by the target AsmPrinter.
1112 void DwarfDebug::beginModule(Module *M) {
1113 if (DisableDebugInfoPrinting)
1116 bool HasDebugInfo = false;
1118 // If module has named metadata anchors then use them, otherwise scan the module
1119 // using debug info finder to collect debug info.
1120 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
1122 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
1123 HasDebugInfo = true;
1124 constructCompileUnit(CU_Nodes->getOperand(i));
1129 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
1130 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
1131 constructGlobalVariableDIE(NMD->getOperand(i));
1133 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
1134 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
1135 constructSubprogramDIE(NMD->getOperand(i));
1139 DebugInfoFinder DbgFinder;
1140 DbgFinder.processModule(*M);
1142 // Scan all the compile-units to see if there are any marked as the main unit.
1143 // if not, we do not generate debug info.
1144 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1145 E = DbgFinder.compile_unit_end(); I != E; ++I) {
1146 if (DICompileUnit(*I).isMain()) {
1147 HasDebugInfo = true;
1152 // Create all the compile unit DIEs.
1153 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1154 E = DbgFinder.compile_unit_end(); I != E; ++I)
1155 constructCompileUnit(*I);
1157 // Create DIEs for each global variable.
1158 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1159 E = DbgFinder.global_variable_end(); I != E; ++I)
1160 constructGlobalVariableDIE(*I);
1162 // Create DIEs for each subprogram.
1163 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1164 E = DbgFinder.subprogram_end(); I != E; ++I)
1165 constructSubprogramDIE(*I);
1168 if (!HasDebugInfo) return;
1170 // Tell MMI that we have debug info.
1171 MMI->setDebugInfoAvailability(true);
1173 // Emit initial sections.
1174 EmitSectionLabels();
1176 //getOrCreateTypeDIE
1177 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
1178 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1179 DIType Ty(NMD->getOperand(i));
1180 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1183 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
1184 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1185 DIType Ty(NMD->getOperand(i));
1186 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1189 // Prime section data.
1190 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1193 /// endModule - Emit all Dwarf sections that should come after the content.
1195 void DwarfDebug::endModule() {
1196 if (!FirstCU) return;
1197 const Module *M = MMI->getModule();
1198 DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
1199 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
1200 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
1201 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
1202 DISubprogram SP(AllSPs->getOperand(SI));
1203 if (!SP.Verify()) continue;
1205 // Collect info for variables that were optimized out.
1206 if (!SP.isDefinition()) continue;
1207 StringRef FName = SP.getLinkageName();
1209 FName = SP.getName();
1210 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
1212 unsigned E = NMD->getNumOperands();
1214 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
1215 DeadFnScopeMap[SP] = Scope;
1216 for (unsigned I = 0; I != E; ++I) {
1217 DIVariable DV(NMD->getOperand(I));
1218 if (!DV.Verify()) continue;
1219 Scope->addVariable(new DbgVariable(DV));
1222 // Construct subprogram DIE and add variables DIEs.
1223 constructSubprogramDIE(SP);
1224 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
1225 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1226 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1227 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1229 ScopeDIE->addChild(VariableDIE);
1234 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1235 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1236 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1238 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1241 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1242 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1243 DIE *SPDie = CI->first;
1244 const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1246 DIE *NDie = getCompileUnit(N)->getDIE(N);
1247 if (!NDie) continue;
1248 getCompileUnit(N)->addDIEEntry(SPDie, dwarf::DW_AT_containing_type,
1249 dwarf::DW_FORM_ref4, NDie);
1252 // Standard sections final addresses.
1253 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1254 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1255 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1256 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1258 // End text sections.
1259 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1260 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1261 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1264 // Emit common frame information.
1265 emitCommonDebugFrame();
1267 // Emit function debug frame information
1268 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1269 E = DebugFrames.end(); I != E; ++I)
1270 emitFunctionDebugFrame(*I);
1272 // Compute DIE offsets and sizes.
1273 computeSizeAndOffsets();
1275 // Emit all the DIEs into a debug info section
1278 // Corresponding abbreviations into a abbrev section.
1279 emitAbbreviations();
1281 // Emit info into a debug pubnames section.
1282 emitDebugPubNames();
1284 // Emit info into a debug pubtypes section.
1285 emitDebugPubTypes();
1287 // Emit info into a debug loc section.
1290 // Emit info into a debug aranges section.
1293 // Emit info into a debug ranges section.
1296 // Emit info into a debug macinfo section.
1299 // Emit inline info.
1300 emitDebugInlineInfo();
1302 // Emit info into a debug str section.
1306 DeleteContainerSeconds(DeadFnScopeMap);
1307 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1308 E = CUMap.end(); I != E; ++I)
1310 FirstCU = NULL; // Reset for the next Module, if any.
1313 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1314 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1315 DebugLoc ScopeLoc) {
1317 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1319 return AbsDbgVariable;
1321 LLVMContext &Ctx = Var->getContext();
1322 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
1326 AbsDbgVariable = new DbgVariable(Var);
1327 Scope->addVariable(AbsDbgVariable);
1328 AbstractVariables[Var] = AbsDbgVariable;
1329 return AbsDbgVariable;
1332 /// addCurrentFnArgument - If Var is an current function argument that add
1333 /// it in CurrentFnArguments list.
1334 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1335 DbgVariable *Var, DbgScope *Scope) {
1336 if (Scope != CurrentFnDbgScope)
1338 DIVariable DV = Var->getVariable();
1339 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1341 unsigned ArgNo = DV.getArgNumber();
1345 size_t Size = CurrentFnArguments.size();
1347 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1348 // llvm::Function argument size is not good indicator of how many
1349 // arguments does the function have at source level.
1351 CurrentFnArguments.resize(ArgNo * 2);
1352 CurrentFnArguments[ArgNo - 1] = Var;
1356 /// collectVariableInfoFromMMITable - Collect variable information from
1357 /// side table maintained by MMI.
1359 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
1360 SmallPtrSet<const MDNode *, 16> &Processed) {
1361 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1362 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1363 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1364 VE = VMap.end(); VI != VE; ++VI) {
1365 const MDNode *Var = VI->first;
1367 Processed.insert(Var);
1369 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1371 DbgScope *Scope = 0;
1372 if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
1373 Scope = ConcreteScopes.lookup(IA);
1375 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
1377 // If variable scope is not found then skip this variable.
1381 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1382 DbgVariable *RegVar = new DbgVariable(DV);
1383 recordVariableFrameIndex(RegVar, VP.first);
1384 if (!addCurrentFnArgument(MF, RegVar, Scope))
1385 Scope->addVariable(RegVar);
1386 if (AbsDbgVariable) {
1387 recordVariableFrameIndex(AbsDbgVariable, VP.first);
1388 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
1393 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
1394 /// DBG_VALUE instruction, is in a defined reg.
1395 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1396 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1397 return MI->getNumOperands() == 3 &&
1398 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1399 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1402 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1404 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1405 SmallPtrSet<const MDNode *, 16> &Processed) {
1407 /// collection info from MMI table.
1408 collectVariableInfoFromMMITable(MF, Processed);
1410 for (SmallVectorImpl<const MDNode*>::const_iterator
1411 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1413 const MDNode *Var = *UVI;
1414 if (Processed.count(Var))
1417 // History contains relevant DBG_VALUE instructions for Var and instructions
1419 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1420 if (History.empty())
1422 const MachineInstr *MInsn = History.front();
1425 DbgScope *Scope = NULL;
1426 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1427 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1428 Scope = CurrentFnDbgScope;
1430 Scope = findDbgScope(MInsn);
1431 // If variable scope is not found then skip this variable.
1435 Processed.insert(DV);
1436 assert(MInsn->isDebugValue() && "History must begin with debug value");
1437 DbgVariable *RegVar = new DbgVariable(DV);
1438 if (!addCurrentFnArgument(MF, RegVar, Scope))
1439 Scope->addVariable(RegVar);
1440 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1441 DbgVariableToDbgInstMap[AbsVar] = MInsn;
1442 VarToAbstractVarMap[RegVar] = AbsVar;
1445 // Simple ranges that are fully coalesced.
1446 if (History.size() <= 1 || (History.size() == 2 &&
1447 MInsn->isIdenticalTo(History.back()))) {
1448 DbgVariableToDbgInstMap[RegVar] = MInsn;
1452 // handle multiple DBG_VALUE instructions describing one variable.
1453 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1455 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1456 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1457 const MachineInstr *Begin = *HI;
1458 assert(Begin->isDebugValue() && "Invalid History entry");
1459 MachineLocation MLoc;
1460 if (Begin->getNumOperands() == 3) {
1461 if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
1462 MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
1464 MLoc = Asm->getDebugValueLocation(Begin);
1466 // FIXME: emitDebugLoc only understands registers.
1470 // Compute the range for a register location.
1471 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1472 const MCSymbol *SLabel = 0;
1475 // If Begin is the last instruction in History then its value is valid
1476 // until the end of the function.
1477 SLabel = FunctionEndSym;
1479 const MachineInstr *End = HI[1];
1480 if (End->isDebugValue())
1481 SLabel = getLabelBeforeInsn(End);
1483 // End is a normal instruction clobbering the range.
1484 SLabel = getLabelAfterInsn(End);
1485 assert(SLabel && "Forgot label after clobber instruction");
1490 // The value is valid until the next DBG_VALUE or clobber.
1491 DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc, Var));
1493 DotDebugLocEntries.push_back(DotDebugLocEntry());
1496 // Collect info for variables that were optimized out.
1497 const Function *F = MF->getFunction();
1498 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1499 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1500 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1501 if (!DV || !Processed.insert(DV))
1503 DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
1505 Scope->addVariable(new DbgVariable(DV));
1510 /// getLabelBeforeInsn - Return Label preceding the instruction.
1511 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1512 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1513 assert(Label && "Didn't insert label before instruction");
1517 /// getLabelAfterInsn - Return Label immediately following the instruction.
1518 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1519 return LabelsAfterInsn.lookup(MI);
1522 /// beginInstruction - Process beginning of an instruction.
1523 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1524 // Check if source location changes, but ignore DBG_VALUE locations.
1525 if (!MI->isDebugValue()) {
1526 DebugLoc DL = MI->getDebugLoc();
1527 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1529 if (!DL.isUnknown()) {
1530 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1531 recordSourceLine(DL.getLine(), DL.getCol(), Scope);
1533 recordSourceLine(0, 0, 0);
1537 // Insert labels where requested.
1538 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1539 LabelsBeforeInsn.find(MI);
1542 if (I == LabelsBeforeInsn.end())
1545 // Label already assigned.
1550 PrevLabel = MMI->getContext().CreateTempSymbol();
1551 Asm->OutStreamer.EmitLabel(PrevLabel);
1553 I->second = PrevLabel;
1556 /// endInstruction - Process end of an instruction.
1557 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1558 // Don't create a new label after DBG_VALUE instructions.
1559 // They don't generate code.
1560 if (!MI->isDebugValue())
1563 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1564 LabelsAfterInsn.find(MI);
1567 if (I == LabelsAfterInsn.end())
1570 // Label already assigned.
1574 // We need a label after this instruction.
1576 PrevLabel = MMI->getContext().CreateTempSymbol();
1577 Asm->OutStreamer.EmitLabel(PrevLabel);
1579 I->second = PrevLabel;
1582 /// getOrCreateDbgScope - Create DbgScope for the scope.
1583 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
1584 const MDNode *InlinedAt) {
1586 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1589 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1590 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1591 if (DIDescriptor(Scope).isLexicalBlock()) {
1593 getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
1594 WScope->setParent(Parent);
1595 Parent->addScope(WScope);
1598 if (!WScope->getParent()) {
1599 StringRef SPName = DISubprogram(Scope).getLinkageName();
1600 // We used to check only for a linkage name, but that fails
1601 // since we began omitting the linkage name for private
1602 // functions. The new way is to check for the name in metadata,
1603 // but that's not supported in old .ll test cases. Ergo, we
1605 if (SPName == Asm->MF->getFunction()->getName() ||
1606 DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
1607 CurrentFnDbgScope = WScope;
1613 getOrCreateAbstractScope(Scope);
1614 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1618 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1619 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1620 DILocation DL(InlinedAt);
1622 getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
1623 WScope->setParent(Parent);
1624 Parent->addScope(WScope);
1626 ConcreteScopes[InlinedAt] = WScope;
1631 /// hasValidLocation - Return true if debug location entry attached with
1632 /// machine instruction encodes valid location info.
1633 static bool hasValidLocation(LLVMContext &Ctx,
1634 const MachineInstr *MInsn,
1635 const MDNode *&Scope, const MDNode *&InlinedAt) {
1636 DebugLoc DL = MInsn->getDebugLoc();
1637 if (DL.isUnknown()) return false;
1639 const MDNode *S = DL.getScope(Ctx);
1641 // There is no need to create another DIE for compile unit. For all
1642 // other scopes, create one DbgScope now. This will be translated
1643 // into a scope DIE at the end.
1644 if (DIScope(S).isCompileUnit()) return false;
1647 InlinedAt = DL.getInlinedAt(Ctx);
1651 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
1653 static void calculateDominanceGraph(DbgScope *Scope) {
1654 assert (Scope && "Unable to calculate scop edominance graph!");
1655 SmallVector<DbgScope *, 4> WorkStack;
1656 WorkStack.push_back(Scope);
1657 unsigned Counter = 0;
1658 while (!WorkStack.empty()) {
1659 DbgScope *WS = WorkStack.back();
1660 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
1661 bool visitedChildren = false;
1662 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1663 SE = Children.end(); SI != SE; ++SI) {
1664 DbgScope *ChildScope = *SI;
1665 if (!ChildScope->getDFSOut()) {
1666 WorkStack.push_back(ChildScope);
1667 visitedChildren = true;
1668 ChildScope->setDFSIn(++Counter);
1672 if (!visitedChildren) {
1673 WorkStack.pop_back();
1674 WS->setDFSOut(++Counter);
1679 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
1681 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
1682 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
1685 unsigned PrevDFSIn = 0;
1686 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1688 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1690 const MachineInstr *MInsn = II;
1691 const MDNode *Scope = NULL;
1692 const MDNode *InlinedAt = NULL;
1694 // Check if instruction has valid location information.
1695 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1699 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
1700 MI2ScopeMap.find(MInsn);
1701 if (DI != MI2ScopeMap.end()) {
1702 DbgScope *S = DI->second;
1703 dbgs() << S->getDFSIn();
1704 PrevDFSIn = S->getDFSIn();
1706 dbgs() << PrevDFSIn;
1708 dbgs() << " [ x" << PrevDFSIn;
1716 /// extractScopeInformation - Scan machine instructions in this function
1717 /// and collect DbgScopes. Return true, if at least one scope was found.
1718 bool DwarfDebug::extractScopeInformation() {
1719 // If scope information was extracted using .dbg intrinsics then there is not
1720 // any need to extract these information by scanning each instruction.
1721 if (!DbgScopeMap.empty())
1724 // Scan each instruction and create scopes. First build working set of scopes.
1725 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1726 SmallVector<DbgRange, 4> MIRanges;
1727 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
1728 const MDNode *PrevScope = NULL;
1729 const MDNode *PrevInlinedAt = NULL;
1730 const MachineInstr *RangeBeginMI = NULL;
1731 const MachineInstr *PrevMI = NULL;
1732 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
1734 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1736 const MachineInstr *MInsn = II;
1737 const MDNode *Scope = NULL;
1738 const MDNode *InlinedAt = NULL;
1740 // Check if instruction has valid location information.
1741 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1746 // If scope has not changed then skip this instruction.
1747 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
1752 // Ignore DBG_VALUE. It does not contribute any instruction in output.
1753 if (MInsn->isDebugValue())
1757 // If we have alread seen a beginning of a instruction range and
1758 // current instruction scope does not match scope of first instruction
1759 // in this range then create a new instruction range.
1760 DbgRange R(RangeBeginMI, PrevMI);
1761 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
1763 MIRanges.push_back(R);
1766 // This is a beginning of a new instruction range.
1767 RangeBeginMI = MInsn;
1769 // Reset previous markers.
1772 PrevInlinedAt = InlinedAt;
1776 // Create last instruction range.
1777 if (RangeBeginMI && PrevMI && PrevScope) {
1778 DbgRange R(RangeBeginMI, PrevMI);
1779 MIRanges.push_back(R);
1780 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
1783 if (!CurrentFnDbgScope)
1786 calculateDominanceGraph(CurrentFnDbgScope);
1788 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
1790 // Find ranges of instructions covered by each DbgScope;
1791 DbgScope *PrevDbgScope = NULL;
1792 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
1793 RE = MIRanges.end(); RI != RE; ++RI) {
1794 const DbgRange &R = *RI;
1795 DbgScope *S = MI2ScopeMap.lookup(R.first);
1796 assert (S && "Lost DbgScope for a machine instruction!");
1797 if (PrevDbgScope && !PrevDbgScope->dominates(S))
1798 PrevDbgScope->closeInsnRange(S);
1799 S->openInsnRange(R.first);
1800 S->extendInsnRange(R.second);
1805 PrevDbgScope->closeInsnRange();
1807 identifyScopeMarkers();
1809 return !DbgScopeMap.empty();
1812 /// identifyScopeMarkers() -
1813 /// Each DbgScope has first instruction and last instruction to mark beginning
1814 /// and end of a scope respectively. Create an inverse map that list scopes
1815 /// starts (and ends) with an instruction. One instruction may start (or end)
1816 /// multiple scopes. Ignore scopes that are not reachable.
1817 void DwarfDebug::identifyScopeMarkers() {
1818 SmallVector<DbgScope *, 4> WorkList;
1819 WorkList.push_back(CurrentFnDbgScope);
1820 while (!WorkList.empty()) {
1821 DbgScope *S = WorkList.pop_back_val();
1823 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
1824 if (!Children.empty())
1825 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1826 SE = Children.end(); SI != SE; ++SI)
1827 WorkList.push_back(*SI);
1829 if (S->isAbstractScope())
1832 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
1835 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1836 RE = Ranges.end(); RI != RE; ++RI) {
1837 assert(RI->first && "DbgRange does not have first instruction!");
1838 assert(RI->second && "DbgRange does not have second instruction!");
1839 requestLabelBeforeInsn(RI->first);
1840 requestLabelAfterInsn(RI->second);
1845 /// FindFirstDebugLoc - Find the first debug location in the function. This
1846 /// is intended to be an approximation for the source position of the
1847 /// beginning of the function.
1848 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
1849 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1851 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
1852 MBBI != MBBE; ++MBBI) {
1853 DebugLoc DL = MBBI->getDebugLoc();
1854 if (!DL.isUnknown())
1861 /// CheckLineNumbers - Count basicblocks whose instructions do not have any
1862 /// line number information.
1863 static void CheckLineNumbers(const MachineFunction *MF) {
1864 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1866 bool FoundLineNo = false;
1867 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1869 const MachineInstr *MI = II;
1870 if (!MI->getDebugLoc().isUnknown()) {
1875 if (!FoundLineNo && I->size())
1876 ++BlocksWithoutLineNo;
1881 /// beginFunction - Gather pre-function debug information. Assumes being
1882 /// emitted immediately after the function entry point.
1883 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1884 if (!MMI->hasDebugInfo()) return;
1885 if (!extractScopeInformation()) return;
1888 CheckLineNumbers(MF);
1891 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1892 Asm->getFunctionNumber());
1893 // Assumes in correct section after the entry point.
1894 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1896 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1898 DebugLoc FDL = FindFirstDebugLoc(MF);
1899 if (FDL.isUnknown()) return;
1901 const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
1902 const MDNode *TheScope = 0;
1904 DISubprogram SP = getDISubprogram(Scope);
1907 Line = SP.getLineNumber();
1911 Line = FDL.getLine();
1916 recordSourceLine(Line, Col, TheScope);
1918 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1920 /// ProcessedArgs - Collection of arguments already processed.
1921 SmallPtrSet<const MDNode *, 8> ProcessedArgs;
1923 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1925 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1926 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1928 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1930 bool AtBlockEntry = true;
1931 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1933 const MachineInstr *MI = II;
1935 if (MI->isDebugValue()) {
1936 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1938 // Keep track of user variables.
1940 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1942 // Variable is in a register, we need to check for clobbers.
1943 if (isDbgValueInDefinedReg(MI))
1944 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1946 // Check the history of this variable.
1947 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1948 if (History.empty()) {
1949 UserVariables.push_back(Var);
1950 // The first mention of a function argument gets the FunctionBeginSym
1951 // label, so arguments are visible when breaking at function entry.
1953 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1954 DISubprogram(getDISubprogram(DV.getContext()))
1955 .describes(MF->getFunction()))
1956 LabelsBeforeInsn[MI] = FunctionBeginSym;
1958 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1959 const MachineInstr *Prev = History.back();
1960 if (Prev->isDebugValue()) {
1961 // Coalesce identical entries at the end of History.
1962 if (History.size() >= 2 &&
1963 Prev->isIdenticalTo(History[History.size() - 2]))
1966 // Terminate old register assignments that don't reach MI;
1967 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1968 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1969 isDbgValueInDefinedReg(Prev)) {
1970 // Previous register assignment needs to terminate at the end of
1972 MachineBasicBlock::const_iterator LastMI =
1973 PrevMBB->getLastNonDebugInstr();
1974 if (LastMI == PrevMBB->end())
1975 // Drop DBG_VALUE for empty range.
1978 // Terminate after LastMI.
1979 History.push_back(LastMI);
1984 History.push_back(MI);
1986 // Not a DBG_VALUE instruction.
1988 AtBlockEntry = false;
1990 // Check if the instruction clobbers any registers with debug vars.
1991 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1992 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1993 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1995 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1996 unsigned Reg = *AI; ++AI) {
1997 const MDNode *Var = LiveUserVar[Reg];
2000 // Reg is now clobbered.
2001 LiveUserVar[Reg] = 0;
2003 // Was MD last defined by a DBG_VALUE referring to Reg?
2004 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
2005 if (HistI == DbgValues.end())
2007 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
2008 if (History.empty())
2010 const MachineInstr *Prev = History.back();
2011 // Sanity-check: Register assignments are terminated at the end of
2013 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
2015 // Is the variable still in Reg?
2016 if (!isDbgValueInDefinedReg(Prev) ||
2017 Prev->getOperand(0).getReg() != Reg)
2019 // Var is clobbered. Make sure the next instruction gets a label.
2020 History.push_back(MI);
2027 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
2029 SmallVectorImpl<const MachineInstr*> &History = I->second;
2030 if (History.empty())
2033 // Make sure the final register assignments are terminated.
2034 const MachineInstr *Prev = History.back();
2035 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
2036 const MachineBasicBlock *PrevMBB = Prev->getParent();
2037 MachineBasicBlock::const_iterator LastMI = PrevMBB->getLastNonDebugInstr();
2038 if (LastMI == PrevMBB->end())
2039 // Drop DBG_VALUE for empty range.
2042 // Terminate after LastMI.
2043 History.push_back(LastMI);
2046 // Request labels for the full history.
2047 for (unsigned i = 0, e = History.size(); i != e; ++i) {
2048 const MachineInstr *MI = History[i];
2049 if (MI->isDebugValue())
2050 requestLabelBeforeInsn(MI);
2052 requestLabelAfterInsn(MI);
2056 PrevInstLoc = DebugLoc();
2057 PrevLabel = FunctionBeginSym;
2060 /// endFunction - Gather and emit post-function debug information.
2062 void DwarfDebug::endFunction(const MachineFunction *MF) {
2063 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2065 if (CurrentFnDbgScope) {
2067 // Define end label for subprogram.
2068 FunctionEndSym = Asm->GetTempSymbol("func_end",
2069 Asm->getFunctionNumber());
2070 // Assumes in correct section after the entry point.
2071 Asm->OutStreamer.EmitLabel(FunctionEndSym);
2073 SmallPtrSet<const MDNode *, 16> ProcessedVars;
2074 collectVariableInfo(MF, ProcessedVars);
2076 // Construct abstract scopes.
2077 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2078 AE = AbstractScopesList.end(); AI != AE; ++AI) {
2079 DISubprogram SP((*AI)->getScopeNode());
2081 // Collect info for variables that were optimized out.
2082 StringRef FName = SP.getLinkageName();
2084 FName = SP.getName();
2085 if (NamedMDNode *NMD =
2086 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
2087 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2088 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2089 if (!DV || !ProcessedVars.insert(DV))
2091 DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2093 Scope->addVariable(new DbgVariable(DV));
2097 if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2098 constructScopeDIE(*AI);
2101 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2103 if (!DisableFramePointerElim(*MF))
2104 getCompileUnit(CurrentFnDbgScope->getScopeNode())->addUInt(CurFnDIE,
2105 dwarf::DW_AT_APPLE_omit_frame_ptr,
2106 dwarf::DW_FORM_flag, 1);
2109 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2110 MMI->getFrameMoves()));
2114 CurrentFnDbgScope = NULL;
2115 DeleteContainerPointers(CurrentFnArguments);
2116 DbgVariableToFrameIndexMap.clear();
2117 VarToAbstractVarMap.clear();
2118 DbgVariableToDbgInstMap.clear();
2119 DeleteContainerSeconds(DbgScopeMap);
2120 UserVariables.clear();
2122 ConcreteScopes.clear();
2123 DeleteContainerSeconds(AbstractScopes);
2124 AbstractScopesList.clear();
2125 AbstractVariables.clear();
2126 LabelsBeforeInsn.clear();
2127 LabelsAfterInsn.clear();
2131 /// recordVariableFrameIndex - Record a variable's index.
2132 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2133 assert (V && "Invalid DbgVariable!");
2134 DbgVariableToFrameIndexMap[V] = Index;
2137 /// findVariableFrameIndex - Return true if frame index for the variable
2138 /// is found. Update FI to hold value of the index.
2139 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2140 assert (V && "Invalid DbgVariable!");
2141 DenseMap<const DbgVariable *, int>::iterator I =
2142 DbgVariableToFrameIndexMap.find(V);
2143 if (I == DbgVariableToFrameIndexMap.end())
2149 /// findDbgScope - Find DbgScope for the debug loc attached with an
2151 DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2152 DbgScope *Scope = NULL;
2154 MInsn->getParent()->getParent()->getFunction()->getContext();
2155 DebugLoc DL = MInsn->getDebugLoc();
2160 if (const MDNode *IA = DL.getInlinedAt(Ctx))
2161 Scope = ConcreteScopes.lookup(IA);
2163 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2169 /// recordSourceLine - Register a source line with debug info. Returns the
2170 /// unique label that was emitted and which provides correspondence to
2171 /// the source line list.
2172 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S){
2177 DIDescriptor Scope(S);
2179 if (Scope.isCompileUnit()) {
2180 DICompileUnit CU(S);
2181 Fn = CU.getFilename();
2182 Dir = CU.getDirectory();
2183 } else if (Scope.isFile()) {
2185 Fn = F.getFilename();
2186 Dir = F.getDirectory();
2187 } else if (Scope.isSubprogram()) {
2189 Fn = SP.getFilename();
2190 Dir = SP.getDirectory();
2191 } else if (Scope.isLexicalBlock()) {
2192 DILexicalBlock DB(S);
2193 Fn = DB.getFilename();
2194 Dir = DB.getDirectory();
2196 assert(0 && "Unexpected scope info");
2198 Src = GetOrCreateSourceID(Fn, Dir);
2200 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, DWARF2_FLAG_IS_STMT,
2204 //===----------------------------------------------------------------------===//
2206 //===----------------------------------------------------------------------===//
2208 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2211 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2212 // Get the children.
2213 const std::vector<DIE *> &Children = Die->getChildren();
2215 // If not last sibling and has children then add sibling offset attribute.
2216 if (!Last && !Children.empty())
2217 Die->addSiblingOffset(DIEValueAllocator);
2219 // Record the abbreviation.
2220 assignAbbrevNumber(Die->getAbbrev());
2222 // Get the abbreviation for this DIE.
2223 unsigned AbbrevNumber = Die->getAbbrevNumber();
2224 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2227 Die->setOffset(Offset);
2229 // Start the size with the size of abbreviation code.
2230 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2232 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2233 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2235 // Size the DIE attribute values.
2236 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2237 // Size attribute value.
2238 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2240 // Size the DIE children if any.
2241 if (!Children.empty()) {
2242 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2243 "Children flag not set");
2245 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2246 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2248 // End of children marker.
2249 Offset += sizeof(int8_t);
2252 Die->setSize(Offset - Die->getOffset());
2256 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2258 void DwarfDebug::computeSizeAndOffsets() {
2259 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2260 E = CUMap.end(); I != E; ++I) {
2261 // Compute size of compile unit header.
2263 sizeof(int32_t) + // Length of Compilation Unit Info
2264 sizeof(int16_t) + // DWARF version number
2265 sizeof(int32_t) + // Offset Into Abbrev. Section
2266 sizeof(int8_t); // Pointer Size (in bytes)
2267 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
2271 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2272 /// temporary label to it if SymbolStem is specified.
2273 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2274 const char *SymbolStem = 0) {
2275 Asm->OutStreamer.SwitchSection(Section);
2276 if (!SymbolStem) return 0;
2278 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2279 Asm->OutStreamer.EmitLabel(TmpSym);
2283 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2284 /// the start of each one.
2285 void DwarfDebug::EmitSectionLabels() {
2286 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2288 // Dwarf sections base addresses.
2289 if (Asm->MAI->doesDwarfRequireFrameSection()) {
2290 DwarfFrameSectionSym =
2291 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2294 DwarfInfoSectionSym =
2295 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2296 DwarfAbbrevSectionSym =
2297 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2298 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2300 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2301 EmitSectionSym(Asm, MacroInfo);
2303 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2304 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2305 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2306 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2307 DwarfStrSectionSym =
2308 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2309 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2312 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
2313 "section_debug_loc");
2315 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2316 EmitSectionSym(Asm, TLOF.getDataSection());
2319 /// emitDIE - Recusively Emits a debug information entry.
2321 void DwarfDebug::emitDIE(DIE *Die) {
2322 // Get the abbreviation for this DIE.
2323 unsigned AbbrevNumber = Die->getAbbrevNumber();
2324 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2326 // Emit the code (index) for the abbreviation.
2327 if (Asm->isVerbose())
2328 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2329 Twine::utohexstr(Die->getOffset()) + ":0x" +
2330 Twine::utohexstr(Die->getSize()) + " " +
2331 dwarf::TagString(Abbrev->getTag()));
2332 Asm->EmitULEB128(AbbrevNumber);
2334 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2335 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2337 // Emit the DIE attribute values.
2338 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2339 unsigned Attr = AbbrevData[i].getAttribute();
2340 unsigned Form = AbbrevData[i].getForm();
2341 assert(Form && "Too many attributes for DIE (check abbreviation)");
2343 if (Asm->isVerbose())
2344 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2347 case dwarf::DW_AT_sibling:
2348 Asm->EmitInt32(Die->getSiblingOffset());
2350 case dwarf::DW_AT_abstract_origin: {
2351 DIEEntry *E = cast<DIEEntry>(Values[i]);
2352 DIE *Origin = E->getEntry();
2353 unsigned Addr = Origin->getOffset();
2354 Asm->EmitInt32(Addr);
2357 case dwarf::DW_AT_ranges: {
2358 // DW_AT_range Value encodes offset in debug_range section.
2359 DIEInteger *V = cast<DIEInteger>(Values[i]);
2361 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
2362 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2366 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2368 DwarfDebugRangeSectionSym,
2373 case dwarf::DW_AT_location: {
2374 if (UseDotDebugLocEntry.count(Die) != 0) {
2375 DIELabel *L = cast<DIELabel>(Values[i]);
2376 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2378 Values[i]->EmitValue(Asm, Form);
2381 case dwarf::DW_AT_accessibility: {
2382 if (Asm->isVerbose()) {
2383 DIEInteger *V = cast<DIEInteger>(Values[i]);
2384 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2386 Values[i]->EmitValue(Asm, Form);
2390 // Emit an attribute using the defined form.
2391 Values[i]->EmitValue(Asm, Form);
2396 // Emit the DIE children if any.
2397 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2398 const std::vector<DIE *> &Children = Die->getChildren();
2400 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2401 emitDIE(Children[j]);
2403 if (Asm->isVerbose())
2404 Asm->OutStreamer.AddComment("End Of Children Mark");
2409 /// emitDebugInfo - Emit the debug info section.
2411 void DwarfDebug::emitDebugInfo() {
2412 // Start debug info section.
2413 Asm->OutStreamer.SwitchSection(
2414 Asm->getObjFileLowering().getDwarfInfoSection());
2415 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2416 E = CUMap.end(); I != E; ++I) {
2417 CompileUnit *TheCU = I->second;
2418 DIE *Die = TheCU->getCUDie();
2420 // Emit the compile units header.
2421 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2424 // Emit size of content not including length itself
2425 unsigned ContentSize = Die->getSize() +
2426 sizeof(int16_t) + // DWARF version number
2427 sizeof(int32_t) + // Offset Into Abbrev. Section
2428 sizeof(int8_t); // Pointer Size (in bytes)
2430 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2431 Asm->EmitInt32(ContentSize);
2432 Asm->OutStreamer.AddComment("DWARF version number");
2433 Asm->EmitInt16(dwarf::DWARF_VERSION);
2434 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2435 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2436 DwarfAbbrevSectionSym);
2437 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2438 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2441 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
2445 /// emitAbbreviations - Emit the abbreviation section.
2447 void DwarfDebug::emitAbbreviations() const {
2448 // Check to see if it is worth the effort.
2449 if (!Abbreviations.empty()) {
2450 // Start the debug abbrev section.
2451 Asm->OutStreamer.SwitchSection(
2452 Asm->getObjFileLowering().getDwarfAbbrevSection());
2454 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2456 // For each abbrevation.
2457 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2458 // Get abbreviation data
2459 const DIEAbbrev *Abbrev = Abbreviations[i];
2461 // Emit the abbrevations code (base 1 index.)
2462 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2464 // Emit the abbreviations data.
2468 // Mark end of abbreviations.
2469 Asm->EmitULEB128(0, "EOM(3)");
2471 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2475 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2476 /// the line matrix.
2478 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2479 // Define last address of section.
2480 Asm->OutStreamer.AddComment("Extended Op");
2483 Asm->OutStreamer.AddComment("Op size");
2484 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2485 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2486 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2488 Asm->OutStreamer.AddComment("Section end label");
2490 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2491 Asm->getTargetData().getPointerSize(),
2494 // Mark end of matrix.
2495 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2501 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2503 void DwarfDebug::emitCommonDebugFrame() {
2504 if (!Asm->MAI->doesDwarfRequireFrameSection())
2507 int stackGrowth = Asm->getTargetData().getPointerSize();
2508 if (Asm->TM.getFrameLowering()->getStackGrowthDirection() ==
2509 TargetFrameLowering::StackGrowsDown)
2512 // Start the dwarf frame section.
2513 Asm->OutStreamer.SwitchSection(
2514 Asm->getObjFileLowering().getDwarfFrameSection());
2516 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
2517 Asm->OutStreamer.AddComment("Length of Common Information Entry");
2518 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
2519 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
2521 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
2522 Asm->OutStreamer.AddComment("CIE Identifier Tag");
2523 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2524 Asm->OutStreamer.AddComment("CIE Version");
2525 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2526 Asm->OutStreamer.AddComment("CIE Augmentation");
2527 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
2528 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
2529 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
2530 Asm->OutStreamer.AddComment("CIE RA Column");
2531 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
2532 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
2533 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2535 std::vector<MachineMove> Moves;
2536 TFI->getInitialFrameState(Moves);
2538 Asm->EmitFrameMoves(Moves, 0, false);
2540 Asm->EmitAlignment(2);
2541 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
2544 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2547 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2548 if (!Asm->MAI->doesDwarfRequireFrameSection())
2551 // Start the dwarf frame section.
2552 Asm->OutStreamer.SwitchSection(
2553 Asm->getObjFileLowering().getDwarfFrameSection());
2555 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
2556 MCSymbol *DebugFrameBegin =
2557 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
2558 MCSymbol *DebugFrameEnd =
2559 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
2560 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
2562 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
2564 Asm->OutStreamer.AddComment("FDE CIE offset");
2565 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
2566 DwarfFrameSectionSym);
2568 Asm->OutStreamer.AddComment("FDE initial location");
2569 MCSymbol *FuncBeginSym =
2570 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
2571 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
2572 Asm->getTargetData().getPointerSize(),
2576 Asm->OutStreamer.AddComment("FDE address range");
2577 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
2578 FuncBeginSym, Asm->getTargetData().getPointerSize());
2580 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
2582 Asm->EmitAlignment(2);
2583 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
2586 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2588 void DwarfDebug::emitDebugPubNames() {
2589 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2590 E = CUMap.end(); I != E; ++I) {
2591 CompileUnit *TheCU = I->second;
2592 // Start the dwarf pubnames section.
2593 Asm->OutStreamer.SwitchSection(
2594 Asm->getObjFileLowering().getDwarfPubNamesSection());
2596 Asm->OutStreamer.AddComment("Length of Public Names Info");
2597 Asm->EmitLabelDifference(
2598 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
2599 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
2601 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
2604 Asm->OutStreamer.AddComment("DWARF Version");
2605 Asm->EmitInt16(dwarf::DWARF_VERSION);
2607 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2608 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2609 DwarfInfoSectionSym);
2611 Asm->OutStreamer.AddComment("Compilation Unit Length");
2612 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2613 Asm->GetTempSymbol("info_begin", TheCU->getID()),
2616 const StringMap<DIE*> &Globals = TheCU->getGlobals();
2617 for (StringMap<DIE*>::const_iterator
2618 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2619 const char *Name = GI->getKeyData();
2620 DIE *Entity = GI->second;
2622 Asm->OutStreamer.AddComment("DIE offset");
2623 Asm->EmitInt32(Entity->getOffset());
2625 if (Asm->isVerbose())
2626 Asm->OutStreamer.AddComment("External Name");
2627 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2630 Asm->OutStreamer.AddComment("End Mark");
2632 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
2637 void DwarfDebug::emitDebugPubTypes() {
2638 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2639 E = CUMap.end(); I != E; ++I) {
2640 CompileUnit *TheCU = I->second;
2641 // Start the dwarf pubnames section.
2642 Asm->OutStreamer.SwitchSection(
2643 Asm->getObjFileLowering().getDwarfPubTypesSection());
2644 Asm->OutStreamer.AddComment("Length of Public Types Info");
2645 Asm->EmitLabelDifference(
2646 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
2647 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
2649 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2652 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2653 Asm->EmitInt16(dwarf::DWARF_VERSION);
2655 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2656 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2657 DwarfInfoSectionSym);
2659 Asm->OutStreamer.AddComment("Compilation Unit Length");
2660 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2661 Asm->GetTempSymbol("info_begin", TheCU->getID()),
2664 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2665 for (StringMap<DIE*>::const_iterator
2666 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2667 const char *Name = GI->getKeyData();
2668 DIE * Entity = GI->second;
2670 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2671 Asm->EmitInt32(Entity->getOffset());
2673 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2674 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2677 Asm->OutStreamer.AddComment("End Mark");
2679 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2684 /// emitDebugStr - Emit visible names into a debug str section.
2686 void DwarfDebug::emitDebugStr() {
2687 // Check to see if it is worth the effort.
2688 if (StringPool.empty()) return;
2690 // Start the dwarf str section.
2691 Asm->OutStreamer.SwitchSection(
2692 Asm->getObjFileLowering().getDwarfStrSection());
2694 // Get all of the string pool entries and put them in an array by their ID so
2695 // we can sort them.
2696 SmallVector<std::pair<unsigned,
2697 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2699 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2700 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2701 Entries.push_back(std::make_pair(I->second.second, &*I));
2703 array_pod_sort(Entries.begin(), Entries.end());
2705 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2706 // Emit a label for reference from debug information entries.
2707 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2709 // Emit the string itself.
2710 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
2714 /// emitDebugLoc - Emit visible names into a debug loc section.
2716 void DwarfDebug::emitDebugLoc() {
2717 if (DotDebugLocEntries.empty())
2720 for (SmallVector<DotDebugLocEntry, 4>::iterator
2721 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2723 DotDebugLocEntry &Entry = *I;
2724 if (I + 1 != DotDebugLocEntries.end())
2728 // Start the dwarf loc section.
2729 Asm->OutStreamer.SwitchSection(
2730 Asm->getObjFileLowering().getDwarfLocSection());
2731 unsigned char Size = Asm->getTargetData().getPointerSize();
2732 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2734 for (SmallVector<DotDebugLocEntry, 4>::iterator
2735 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2736 I != E; ++I, ++index) {
2737 DotDebugLocEntry &Entry = *I;
2738 if (Entry.isMerged()) continue;
2739 if (Entry.isEmpty()) {
2740 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2741 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2742 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2744 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2745 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2746 DIVariable DV(Entry.Variable);
2747 if (DV.hasComplexAddress()) {
2748 unsigned N = DV.getNumAddrElements();
2750 Asm->OutStreamer.AddComment("Loc expr size");
2751 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2752 // If first address element is OpPlus then emit
2753 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2754 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2755 Asm->EmitInt16(Asm->getDwarfRegOpSize(Loc) + N - 2);
2756 Asm->EmitDwarfRegOp(Loc);
2757 // Asm->EmitULEB128(DV.getAddrElement(1));
2760 Asm->EmitInt16(Asm->getDwarfRegOpSize(Entry.Loc) + N);
2761 Asm->EmitDwarfRegOp(Entry.Loc);
2764 // Emit remaining complex address elements.
2765 for (; i < N; ++i) {
2766 uint64_t Element = DV.getAddrElement(i);
2767 if (Element == DIBuilder::OpPlus) {
2768 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2769 Asm->EmitULEB128(DV.getAddrElement(++i));
2770 } else if (Element == DIBuilder::OpDeref)
2771 Asm->EmitInt8(dwarf::DW_OP_deref);
2772 else llvm_unreachable("unknown Opcode found in complex address");
2775 Asm->OutStreamer.AddComment("Loc expr size");
2776 Asm->EmitInt16(Asm->getDwarfRegOpSize(Entry.Loc));
2777 Asm->EmitDwarfRegOp(Entry.Loc);
2783 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2785 void DwarfDebug::EmitDebugARanges() {
2786 // Start the dwarf aranges section.
2787 Asm->OutStreamer.SwitchSection(
2788 Asm->getObjFileLowering().getDwarfARangesSection());
2791 /// emitDebugRanges - Emit visible names into a debug ranges section.
2793 void DwarfDebug::emitDebugRanges() {
2794 // Start the dwarf ranges section.
2795 Asm->OutStreamer.SwitchSection(
2796 Asm->getObjFileLowering().getDwarfRangesSection());
2797 unsigned char Size = Asm->getTargetData().getPointerSize();
2798 for (SmallVector<const MCSymbol *, 8>::iterator
2799 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2802 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2804 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2808 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2810 void DwarfDebug::emitDebugMacInfo() {
2811 if (const MCSection *LineInfo =
2812 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2813 // Start the dwarf macinfo section.
2814 Asm->OutStreamer.SwitchSection(LineInfo);
2818 /// emitDebugInlineInfo - Emit inline info using following format.
2820 /// 1. length of section
2821 /// 2. Dwarf version number
2822 /// 3. address size.
2824 /// Entries (one "entry" for each function that was inlined):
2826 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2827 /// otherwise offset into __debug_str for regular function name.
2828 /// 2. offset into __debug_str section for regular function name.
2829 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2830 /// instances for the function.
2832 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2833 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2834 /// __debug_info section, and the low_pc is the starting address for the
2835 /// inlining instance.
2836 void DwarfDebug::emitDebugInlineInfo() {
2837 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2843 Asm->OutStreamer.SwitchSection(
2844 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2846 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2847 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2848 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2850 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2852 Asm->OutStreamer.AddComment("Dwarf Version");
2853 Asm->EmitInt16(dwarf::DWARF_VERSION);
2854 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2855 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2857 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2858 E = InlinedSPNodes.end(); I != E; ++I) {
2860 const MDNode *Node = *I;
2861 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2862 = InlineInfo.find(Node);
2863 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2864 DISubprogram SP(Node);
2865 StringRef LName = SP.getLinkageName();
2866 StringRef Name = SP.getName();
2868 Asm->OutStreamer.AddComment("MIPS linkage name");
2869 if (LName.empty()) {
2870 Asm->OutStreamer.EmitBytes(Name, 0);
2871 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2873 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2874 DwarfStrSectionSym);
2876 Asm->OutStreamer.AddComment("Function name");
2877 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2878 Asm->EmitULEB128(Labels.size(), "Inline count");
2880 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2881 LE = Labels.end(); LI != LE; ++LI) {
2882 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2883 Asm->EmitInt32(LI->second->getOffset());
2885 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2886 Asm->OutStreamer.EmitSymbolValue(LI->first,
2887 Asm->getTargetData().getPointerSize(),0);
2891 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));