DwarfDebug.cpp revision 5e06bb83f4d7b1b86659ad851324350afb04f5b0
1//===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing dwarf debug info into asm files.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "dwarfdebug"
15#include "DwarfDebug.h"
16#include "DIE.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"
46using namespace llvm;
47
48static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
49     cl::desc("Print DbgScope information for each machine instruction"));
50
51static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
52                                              cl::Hidden,
53     cl::desc("Disable debug info printing"));
54
55static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
56     cl::desc("Make an absence of debug location information explicit."),
57     cl::init(false));
58
59#ifndef NDEBUG
60STATISTIC(BlocksWithoutLineNo, "Number of blocks without any line number");
61#endif
62
63namespace {
64  const char *DWARFGroupName = "DWARF Emission";
65  const char *DbgTimerName = "DWARF Debug Writer";
66} // end anonymous namespace
67
68//===----------------------------------------------------------------------===//
69
70/// Configuration values for initial hash set sizes (log2).
71///
72static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
73
74namespace llvm {
75
76DIType DbgVariable::getType()               const {
77  DIType Ty = Var.getType();
78  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
79  // addresses instead.
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.
87
88       However, as far as the original *programmer* is concerned, the
89       variable should still have type 'SomeType', as originally declared.
90
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.
96
97       The original type 'SomeType' will be the type of the field named
98       'VarName' inside the __Block_byref_x_VarName struct.
99
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.  */
105    DIType subType = Ty;
106    unsigned tag = Ty.getTag();
107
108    if (tag == dwarf::DW_TAG_pointer_type) {
109      DIDerivedType DTy = DIDerivedType(Ty);
110      subType = DTy.getTypeDerivedFrom();
111    }
112
113    DICompositeType blockStruct = DICompositeType(subType);
114    DIArray Elements = blockStruct.getTypeArray();
115
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());
121    }
122    return Ty;
123  }
124  return Ty;
125}
126
127//===----------------------------------------------------------------------===//
128/// DbgRange - This is used to track range of instructions with identical
129/// debug info scope.
130///
131typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
132
133//===----------------------------------------------------------------------===//
134/// DbgScope - This class is used to track scope information.
135///
136class DbgScope {
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;
152public:
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) {}
157  virtual ~DbgScope();
158
159  // Accessors.
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; }
168
169  /// openInsnRange - This scope covers instruction range starting from MI.
170  void openInsnRange(const MachineInstr *MI) {
171    if (!FirstInsn)
172      FirstInsn = MI;
173
174    if (Parent)
175      Parent->openInsnRange(MI);
176  }
177
178  /// extendInsnRange - Extend the current instruction range covered by
179  /// this scope.
180  void extendInsnRange(const MachineInstr *MI) {
181    assert (FirstInsn && "MI Range is not open!");
182    LastInsn = MI;
183    if (Parent)
184      Parent->extendInsnRange(MI);
185  }
186
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));
193    FirstInsn = NULL;
194    LastInsn = NULL;
195    // If Parent dominates NewScope then do not close Parent's instruction
196    // range.
197    if (Parent && (!NewScope || !Parent->dominates(NewScope)))
198      Parent->closeInsnRange(NewScope);
199  }
200
201  void setAbstractScope() { AbstractScope = true; }
202  bool isAbstractScope() const { return AbstractScope; }
203
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) {
210    if (S == this)
211      return true;
212    if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
213      return true;
214    return false;
215  }
216
217  /// addScope - Add a scope to the scope.
218  ///
219  void addScope(DbgScope *S) { Scopes.push_back(S); }
220
221  /// addVariable - Add a variable to the scope.
222  ///
223  void addVariable(DbgVariable *V) { Variables.push_back(V); }
224
225#ifndef NDEBUG
226  void dump() const;
227#endif
228};
229
230} // end llvm namespace
231
232#ifndef NDEBUG
233void DbgScope::dump() const {
234  raw_ostream &err = dbgs();
235  err.indent(IndentLevel);
236  const MDNode *N = Desc;
237  N->dump();
238  if (AbstractScope)
239    err << "Abstract Scope\n";
240
241  IndentLevel += 2;
242  if (!Scopes.empty())
243    err << "Children ...\n";
244  for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
245    if (Scopes[i] != this)
246      Scopes[i]->dump();
247
248  IndentLevel -= 2;
249}
250#endif
251
252DbgScope::~DbgScope() {
253  for (unsigned j = 0, M = Variables.size(); j < M; ++j)
254    delete Variables[j];
255}
256
257DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
258  : Asm(A), MMI(Asm->MMI), FirstCU(0),
259    AbbreviationsSet(InitAbbreviationsSetSize),
260    CurrentFnDbgScope(0), PrevLabel(NULL) {
261  NextStringPoolNumber = 0;
262
263  DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
264  DwarfStrSectionSym = TextSectionSym = 0;
265  DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
266  FunctionBeginSym = FunctionEndSym = 0;
267  {
268    NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
269    beginModule(M);
270  }
271}
272DwarfDebug::~DwarfDebug() {
273}
274
275MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
276  std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
277  if (Entry.first) return Entry.first;
278
279  Entry.second = NextStringPoolNumber++;
280  return Entry.first = Asm->GetTempSymbol("string", Entry.second);
281}
282
283
284/// assignAbbrevNumber - Define a unique number for the abbreviation.
285///
286void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
287  // Profile the node so that we can make it unique.
288  FoldingSetNodeID ID;
289  Abbrev.Profile(ID);
290
291  // Check the set for priors.
292  DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
293
294  // If it's newly added.
295  if (InSet == &Abbrev) {
296    // Add to abbreviation list.
297    Abbreviations.push_back(&Abbrev);
298
299    // Assign the vector position + 1 as its number.
300    Abbrev.setNumber(Abbreviations.size());
301  } else {
302    // Assign existing abbreviation number.
303    Abbrev.setNumber(InSet->getNumber());
304  }
305}
306
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.
310static StringRef getRealLinkageName(StringRef LinkageName) {
311  char One = '\1';
312  if (LinkageName.startswith(StringRef(&One, 1)))
313    return LinkageName.substr(1);
314  return LinkageName;
315}
316
317/// createSubprogramDIE - Create new DIE using SP.
318DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
319  CompileUnit *SPCU = getCompileUnit(SP);
320  DIE *SPDie = SPCU->getDIE(SP);
321  if (SPDie)
322    return SPDie;
323
324  SPDie = new DIE(dwarf::DW_TAG_subprogram);
325
326  // DW_TAG_inlined_subroutine may refer to this DIE.
327  SPCU->insertDIE(SP, SPDie);
328
329  // Add to context owner.
330  SPCU->addToContextOwner(SPDie, SP.getContext());
331
332  // Add function template parameters.
333  SPCU->addTemplateParams(*SPDie, SP.getTemplateParams());
334
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())
338    return SPDie;
339
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,
343                    SP.getName());
344
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));
349
350  SPCU->addSourceLine(SPDie, SP);
351
352  if (SP.isPrototyped())
353    SPCU->addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
354
355  // Add Return Type.
356  DICompositeType SPTy = SP.getType();
357  DIArray Args = SPTy.getTypeArray();
358  unsigned SPTag = SPTy.getTag();
359
360  if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
361    SPCU->addType(SPDie, SPTy);
362  else
363    SPCU->addType(SPDie, DIType(Args.getElement(0)));
364
365  unsigned VK = SP.getVirtuality();
366  if (VK) {
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()));
374  }
375
376  if (!SP.isDefinition()) {
377    SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
378
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();
384
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);
393      }
394  }
395
396  if (SP.isArtificial())
397    SPCU->addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
398
399  if (!SP.isLocalToUnit())
400    SPCU->addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
401
402  if (SP.isOptimized())
403    SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
404
405  if (unsigned isa = Asm->getISAEncoding()) {
406    SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
407  }
408
409  return SPDie;
410}
411
412DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
413  assert(N && "Invalid Scope encoding!");
414
415  DbgScope *AScope = AbstractScopes.lookup(N);
416  if (AScope)
417    return AScope;
418
419  DbgScope *Parent = NULL;
420
421  DIDescriptor Scope(N);
422  if (Scope.isLexicalBlock()) {
423    DILexicalBlock DB(N);
424    DIDescriptor ParentDesc = DB.getContext();
425    Parent = getOrCreateAbstractScope(ParentDesc);
426  }
427
428  AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
429
430  if (Parent)
431    Parent->addScope(AScope);
432  AScope->setAbstractScope();
433  AbstractScopes[N] = AScope;
434  if (DIDescriptor(N).isSubprogram())
435    AbstractScopesList.push_back(AScope);
436  return AScope;
437}
438
439/// isSubprogramContext - Return true if Context is either a subprogram
440/// or another context nested inside a subprogram.
441static bool isSubprogramContext(const MDNode *Context) {
442  if (!Context)
443    return false;
444  DIDescriptor D(Context);
445  if (D.isSubprogram())
446    return true;
447  if (D.isType())
448    return isSubprogramContext(DIType(Context).getContext());
449  return false;
450}
451
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.
456DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
457  CompileUnit *SPCU = getCompileUnit(SPNode);
458  DIE *SPDie = SPCU->getDIE(SPNode);
459
460  assert(SPDie && "Unable to find subprogram DIE!");
461  DISubprogram SP(SPNode);
462
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));
468  else {
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);
478
479      // Add arguments.
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);
491        }
492      DIE *SPDeclDie = SPDie;
493      SPDie = new DIE(dwarf::DW_TAG_subprogram);
494      SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
495                        SPDeclDie);
496      SPCU->addDie(SPDie);
497    }
498  }
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);
504    SPCU->addDie(SPDie);
505  }
506
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);
514
515  return SPDie;
516}
517
518/// constructLexicalScope - Construct new DW_TAG_lexical_block
519/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
520DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
521
522  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
523  if (Scope->isAbstractScope())
524    return ScopeDIE;
525
526  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
527  if (Ranges.empty())
528    return 0;
529
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));
542    }
543    DebugRangeSymbols.push_back(NULL);
544    DebugRangeSymbols.push_back(NULL);
545    return ScopeDIE;
546  }
547
548  const MCSymbol *Start = getLabelBeforeInsn(RI->first);
549  const MCSymbol *End = getLabelAfterInsn(RI->second);
550
551  if (End == 0) return 0;
552
553  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
554  assert(End->isDefined() && "Invalid end label for an inlined scope!");
555
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);
558
559  return ScopeDIE;
560}
561
562/// constructInlinedScopeDIE - This scope represents inlined body of
563/// a function. Construct DIE to represent this concrete inlined copy
564/// of the function.
565DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
566
567  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
568  assert (Ranges.empty() == false
569          && "DbgScope does not have instruction markers!");
570
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);
578
579  if (StartLabel == 0 || EndLabel == 0) {
580    assert (0 && "Unexpected Start and End  labels for a inlined scope!");
581    return 0;
582  }
583  assert(StartLabel->isDefined() &&
584         "Invalid starting label for an inlined scope!");
585  assert(EndLabel->isDefined() &&
586         "Invalid end label for an inlined scope!");
587
588  if (!Scope->getScopeNode())
589    return NULL;
590  DIScope DS(Scope->getScopeNode());
591  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
592
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);
599
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);
602
603  InlinedSubprogramDIEs.insert(OriginDIE);
604
605  // Track the start label for this inlined function.
606  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
607    I = InlineInfo.find(InlinedSP);
608
609  if (I == InlineInfo.end()) {
610    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
611                                                             ScopeDIE));
612    InlinedSPNodes.push_back(InlinedSP);
613  } else
614    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
615
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());
619
620  return ScopeDIE;
621}
622
623
624/// constructVariableDIE - Construct a DIE for the given DbgVariable.
625DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
626  StringRef Name = DV->getName();
627  if (Name.empty())
628    return NULL;
629
630  // Translate tag to proper Dwarf tag.  The result variable is dropped for
631  // now.
632  unsigned Tag;
633  switch (DV->getTag()) {
634  case dwarf::DW_TAG_return_variable:
635    return NULL;
636  case dwarf::DW_TAG_arg_variable:
637    Tag = dwarf::DW_TAG_formal_parameter;
638    break;
639  case dwarf::DW_TAG_auto_variable:    // fall thru
640  default:
641    Tag = dwarf::DW_TAG_variable;
642    break;
643  }
644
645  // Define variable debug information entry.
646  DIE *VariableDie = new DIE(Tag);
647  CompileUnit *TheCU = getCompileUnit(DV->getVariable());
648  DIE *AbsDIE = NULL;
649  DenseMap<const DbgVariable *, const DbgVariable *>::iterator
650    V2AVI = VarToAbstractVarMap.find(DV);
651  if (V2AVI != VarToAbstractVarMap.end())
652    AbsDIE = V2AVI->second->getDIE();
653
654  if (AbsDIE)
655    TheCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
656                       dwarf::DW_FORM_ref4, AbsDIE);
657  else {
658    TheCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
659    TheCU->addSourceLine(VariableDie, DV->getVariable());
660
661    // Add variable type.
662    TheCU->addType(VariableDie, DV->getType());
663  }
664
665  if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
666    TheCU->addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
667  else if (DIVariable(DV->getVariable()).isArtificial())
668    TheCU->addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
669
670  if (Scope->isAbstractScope()) {
671    DV->setDIE(VariableDie);
672    return VariableDie;
673  }
674
675  // Add variable address.
676
677  unsigned Offset = DV->getDotDebugLocOffset();
678  if (Offset != ~0U) {
679    TheCU->addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
680             Asm->GetTempSymbol("debug_loc", Offset));
681    DV->setDIE(VariableDie);
682    UseDotDebugLocEntry.insert(VariableDie);
683    return VariableDie;
684  }
685
686  // Check if variable is described by a  DBG_VALUE instruction.
687  DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
688    DbgVariableToDbgInstMap.find(DV);
689  if (DVI != DbgVariableToDbgInstMap.end()) {
690    const MachineInstr *DVInsn = DVI->second;
691    bool updated = false;
692    // FIXME : Handle getNumOperands != 3
693    if (DVInsn->getNumOperands() == 3) {
694      if (DVInsn->getOperand(0).isReg()) {
695        const MachineOperand RegOp = DVInsn->getOperand(0);
696        const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
697        if (DVInsn->getOperand(1).isImm() &&
698            TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
699          TheCU->addVariableAddress(DV, VariableDie, DVInsn->getOperand(1).getImm());
700          updated = true;
701        } else
702          updated = TheCU->addRegisterAddress(VariableDie, RegOp);
703      }
704      else if (DVInsn->getOperand(0).isImm())
705        updated = TheCU->addConstantValue(VariableDie, DVInsn->getOperand(0));
706      else if (DVInsn->getOperand(0).isFPImm())
707        updated =
708          TheCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
709    } else {
710      MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
711      if (Location.getReg()) {
712        TheCU->addAddress(VariableDie, dwarf::DW_AT_location, Location);
713        updated = true;
714      }
715    }
716    if (!updated) {
717      // If variableDie is not updated then DBG_VALUE instruction does not
718      // have valid variable info.
719      delete VariableDie;
720      return NULL;
721    }
722    DV->setDIE(VariableDie);
723    return VariableDie;
724  }
725
726  // .. else use frame index, if available.
727  int FI = 0;
728  if (findVariableFrameIndex(DV, &FI))
729    TheCU->addVariableAddress(DV, VariableDie, FI);
730
731  DV->setDIE(VariableDie);
732  return VariableDie;
733
734}
735
736void CompileUnit::addPubTypes(DISubprogram SP) {
737  DICompositeType SPTy = SP.getType();
738  unsigned SPTag = SPTy.getTag();
739  if (SPTag != dwarf::DW_TAG_subroutine_type)
740    return;
741
742  DIArray Args = SPTy.getTypeArray();
743  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
744    DIType ATy(Args.getElement(i));
745    if (!ATy.Verify())
746      continue;
747    DICompositeType CATy = getDICompositeType(ATy);
748    if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
749        && !CATy.isForwardDecl()) {
750      if (DIEEntry *Entry = getDIEEntry(CATy))
751        addGlobalType(CATy.getName(), Entry->getEntry());
752    }
753  }
754}
755
756/// constructScopeDIE - Construct a DIE for this scope.
757DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
758  if (!Scope || !Scope->getScopeNode())
759    return NULL;
760
761  SmallVector <DIE *, 8> Children;
762
763  // Collect arguments for current function.
764  if (Scope == CurrentFnDbgScope)
765    for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
766      if (DbgVariable *ArgDV = CurrentFnArguments[i])
767        if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
768          Children.push_back(Arg);
769
770  // Collect lexical scope childrens first.
771  const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
772  for (unsigned i = 0, N = Variables.size(); i < N; ++i)
773    if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
774      Children.push_back(Variable);
775  const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
776  for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
777    if (DIE *Nested = constructScopeDIE(Scopes[j]))
778      Children.push_back(Nested);
779  DIScope DS(Scope->getScopeNode());
780  DIE *ScopeDIE = NULL;
781  if (Scope->getInlinedAt())
782    ScopeDIE = constructInlinedScopeDIE(Scope);
783  else if (DS.isSubprogram()) {
784    ProcessedSPNodes.insert(DS);
785    if (Scope->isAbstractScope()) {
786      ScopeDIE = getCompileUnit(DS)->getDIE(DS);
787      // Note down abstract DIE.
788      if (ScopeDIE)
789        AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
790    }
791    else
792      ScopeDIE = updateSubprogramScopeDIE(DS);
793  }
794  else {
795    // There is no need to emit empty lexical block DIE.
796    if (Children.empty())
797      return NULL;
798    ScopeDIE = constructLexicalScopeDIE(Scope);
799  }
800
801  if (!ScopeDIE) return NULL;
802
803  // Add children
804  for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
805         E = Children.end(); I != E; ++I)
806    ScopeDIE->addChild(*I);
807
808  if (DS.isSubprogram())
809    getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
810
811 return ScopeDIE;
812}
813
814/// GetOrCreateSourceID - Look up the source id with the given directory and
815/// source file names. If none currently exists, create a new id and insert it
816/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
817/// maps as well.
818
819unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
820                                         StringRef DirName) {
821  // If FE did not provide a file name, then assume stdin.
822  if (FileName.empty())
823    return GetOrCreateSourceID("<stdin>", StringRef());
824
825  // MCStream expects full path name as filename.
826  if (!DirName.empty() && !FileName.startswith("/")) {
827    std::string FullPathName(DirName.data());
828    if (!DirName.endswith("/"))
829      FullPathName += "/";
830    FullPathName += FileName.data();
831    // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
832    return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
833  }
834
835  StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
836  if (Entry.getValue())
837    return Entry.getValue();
838
839  unsigned SrcId = SourceIdMap.size();
840  Entry.setValue(SrcId);
841
842  // Print out a .file directive to specify files for .loc directives.
843  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
844
845  return SrcId;
846}
847
848/// getOrCreateNameSpace - Create a DIE for DINameSpace.
849DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
850  DIE *NDie = getDIE(NS);
851  if (NDie)
852    return NDie;
853  NDie = new DIE(dwarf::DW_TAG_namespace);
854  insertDIE(NS, NDie);
855  if (!NS.getName().empty())
856    addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
857  addSourceLine(NDie, NS);
858  addToContextOwner(NDie, NS.getContext());
859  return NDie;
860}
861
862/// constructCompileUnit - Create new CompileUnit for the given
863/// metadata node with tag DW_TAG_compile_unit.
864void DwarfDebug::constructCompileUnit(const MDNode *N) {
865  DICompileUnit DIUnit(N);
866  StringRef FN = DIUnit.getFilename();
867  StringRef Dir = DIUnit.getDirectory();
868  unsigned ID = GetOrCreateSourceID(FN, Dir);
869
870  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
871  CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
872  NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
873                   DIUnit.getProducer());
874  NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
875                 DIUnit.getLanguage());
876  NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
877  // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
878  // simplifies debug range entries.
879  NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
880  // DW_AT_stmt_list is a offset of line number information for this
881  // compile unit in debug_line section.
882  if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
883    NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
884                    Asm->GetTempSymbol("section_line"));
885  else
886    NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
887
888  if (!Dir.empty())
889    NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
890  if (DIUnit.isOptimized())
891    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
892
893  StringRef Flags = DIUnit.getFlags();
894  if (!Flags.empty())
895    NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
896
897  unsigned RVer = DIUnit.getRunTimeVersion();
898  if (RVer)
899    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
900            dwarf::DW_FORM_data1, RVer);
901
902  if (!FirstCU)
903    FirstCU = NewCU;
904  CUMap.insert(std::make_pair(N, NewCU));
905}
906
907/// getCompielUnit - Get CompileUnit DIE.
908CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
909  assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
910  DIDescriptor D(N);
911  const MDNode *CUNode = NULL;
912  if (D.isCompileUnit())
913    CUNode = N;
914  else if (D.isSubprogram())
915    CUNode = DISubprogram(N).getCompileUnit();
916  else if (D.isType())
917    CUNode = DIType(N).getCompileUnit();
918  else if (D.isGlobalVariable())
919    CUNode = DIGlobalVariable(N).getCompileUnit();
920  else if (D.isVariable())
921    CUNode = DIVariable(N).getCompileUnit();
922  else if (D.isNameSpace())
923    CUNode = DINameSpace(N).getCompileUnit();
924  else if (D.isFile())
925    CUNode = DIFile(N).getCompileUnit();
926  else
927    return FirstCU;
928
929  DenseMap<const MDNode *, CompileUnit *>::const_iterator I
930    = CUMap.find(CUNode);
931  if (I == CUMap.end())
932    return FirstCU;
933  return I->second;
934}
935
936/// isUnsignedDIType - Return true if type encoding is unsigned.
937static bool isUnsignedDIType(DIType Ty) {
938  DIDerivedType DTy(Ty);
939  if (DTy.Verify())
940    return isUnsignedDIType(DTy.getTypeDerivedFrom());
941
942  DIBasicType BTy(Ty);
943  if (BTy.Verify()) {
944    unsigned Encoding = BTy.getEncoding();
945    if (Encoding == dwarf::DW_ATE_unsigned ||
946        Encoding == dwarf::DW_ATE_unsigned_char)
947      return true;
948  }
949  return false;
950}
951
952// Return const exprssion if value is a GEP to access merged global
953// constant. e.g.
954// i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
955static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
956  const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
957  if (!CE || CE->getNumOperands() != 3 ||
958      CE->getOpcode() != Instruction::GetElementPtr)
959    return NULL;
960
961  // First operand points to a global value.
962  if (!isa<GlobalValue>(CE->getOperand(0)))
963    return NULL;
964
965  // Second operand is zero.
966  const ConstantInt *CI =
967    dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
968  if (!CI || !CI->isZero())
969    return NULL;
970
971  // Third operand is offset.
972  if (!isa<ConstantInt>(CE->getOperand(2)))
973    return NULL;
974
975  return CE;
976}
977
978/// constructGlobalVariableDIE - Construct global variable DIE.
979void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
980  DIGlobalVariable GV(N);
981
982  // If debug information is malformed then ignore it.
983  if (GV.Verify() == false)
984    return;
985
986  // Check for pre-existence.
987  CompileUnit *TheCU = getCompileUnit(N);
988  if (TheCU->getDIE(GV))
989    return;
990
991  DIType GTy = GV.getType();
992  DIE *VariableDIE = new DIE(GV.getTag());
993
994  bool isGlobalVariable = GV.getGlobal() != NULL;
995
996  // Add name.
997  TheCU->addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
998                   GV.getDisplayName());
999  StringRef LinkageName = GV.getLinkageName();
1000  if (!LinkageName.empty() && isGlobalVariable)
1001    TheCU->addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1002                     dwarf::DW_FORM_string,
1003                     getRealLinkageName(LinkageName));
1004  // Add type.
1005  TheCU->addType(VariableDIE, GTy);
1006  if (GTy.isCompositeType() && !GTy.getName().empty()
1007      && !GTy.isForwardDecl()) {
1008    DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1009    assert(Entry && "Missing global type!");
1010    TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1011  }
1012  // Add scoping info.
1013  if (!GV.isLocalToUnit()) {
1014    TheCU->addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1015    // Expose as global.
1016    TheCU->addGlobal(GV.getName(), VariableDIE);
1017  }
1018  // Add line number info.
1019  TheCU->addSourceLine(VariableDIE, GV);
1020  // Add to map.
1021  TheCU->insertDIE(N, VariableDIE);
1022  // Add to context owner.
1023  DIDescriptor GVContext = GV.getContext();
1024  TheCU->addToContextOwner(VariableDIE, GVContext);
1025  // Add location.
1026  if (isGlobalVariable) {
1027    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1028    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1029    TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1030             Asm->Mang->getSymbol(GV.getGlobal()));
1031    // Do not create specification DIE if context is either compile unit
1032    // or a subprogram.
1033    if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1034        !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1035      // Create specification DIE.
1036      DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1037      TheCU->addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1038                  dwarf::DW_FORM_ref4, VariableDIE);
1039      TheCU->addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1040      TheCU->addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1041      TheCU->addDie(VariableSpecDIE);
1042    } else {
1043      TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1044    }
1045  } else if (ConstantInt *CI =
1046             dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1047    TheCU->addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy));
1048  else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1049    // GV is a merged global.
1050    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1051    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1052    TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1053                    Asm->Mang->getSymbol(cast<GlobalValue>(CE->getOperand(0))));
1054    ConstantInt *CII = cast<ConstantInt>(CE->getOperand(2));
1055    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1056    TheCU->addUInt(Block, 0, dwarf::DW_FORM_udata, CII->getZExtValue());
1057    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1058    TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1059  }
1060
1061  return;
1062}
1063
1064/// construct SubprogramDIE - Construct subprogram DIE.
1065void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1066  DISubprogram SP(N);
1067
1068  // Check for pre-existence.
1069  CompileUnit *TheCU = getCompileUnit(N);
1070  if (TheCU->getDIE(N))
1071    return;
1072
1073  if (!SP.isDefinition())
1074    // This is a method declaration which will be handled while constructing
1075    // class type.
1076    return;
1077
1078  DIE *SubprogramDie = createSubprogramDIE(SP);
1079
1080  // Add to map.
1081  TheCU->insertDIE(N, SubprogramDie);
1082
1083  // Add to context owner.
1084  TheCU->addToContextOwner(SubprogramDie, SP.getContext());
1085
1086  // Expose as global.
1087  TheCU->addGlobal(SP.getName(), SubprogramDie);
1088
1089  return;
1090}
1091
1092/// beginModule - Emit all Dwarf sections that should come prior to the
1093/// content. Create global DIEs and emit initial debug info sections.
1094/// This is inovked by the target AsmPrinter.
1095void DwarfDebug::beginModule(Module *M) {
1096  if (DisableDebugInfoPrinting)
1097    return;
1098
1099  DebugInfoFinder DbgFinder;
1100  DbgFinder.processModule(*M);
1101
1102  bool HasDebugInfo = false;
1103
1104  // Scan all the compile-units to see if there are any marked as the main unit.
1105  // if not, we do not generate debug info.
1106  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1107       E = DbgFinder.compile_unit_end(); I != E; ++I) {
1108    if (DICompileUnit(*I).isMain()) {
1109      HasDebugInfo = true;
1110      break;
1111    }
1112  }
1113
1114  if (!HasDebugInfo) return;
1115
1116  // Tell MMI that we have debug info.
1117  MMI->setDebugInfoAvailability(true);
1118
1119  // Emit initial sections.
1120  EmitSectionLabels();
1121
1122  // Create all the compile unit DIEs.
1123  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1124         E = DbgFinder.compile_unit_end(); I != E; ++I)
1125    constructCompileUnit(*I);
1126
1127  // Create DIEs for each subprogram.
1128  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1129         E = DbgFinder.subprogram_end(); I != E; ++I)
1130    constructSubprogramDIE(*I);
1131
1132  // Create DIEs for each global variable.
1133  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1134         E = DbgFinder.global_variable_end(); I != E; ++I)
1135    constructGlobalVariableDIE(*I);
1136
1137  //getOrCreateTypeDIE
1138  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
1139    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1140      DIType Ty(NMD->getOperand(i));
1141      getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1142    }
1143
1144  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
1145    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1146      DIType Ty(NMD->getOperand(i));
1147      getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1148    }
1149
1150  // Prime section data.
1151  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1152}
1153
1154/// endModule - Emit all Dwarf sections that should come after the content.
1155///
1156void DwarfDebug::endModule() {
1157  if (!FirstCU) return;
1158  const Module *M = MMI->getModule();
1159  DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
1160  if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
1161    for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
1162      if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
1163      DISubprogram SP(AllSPs->getOperand(SI));
1164      if (!SP.Verify()) continue;
1165
1166      // Collect info for variables that were optimized out.
1167      if (!SP.isDefinition()) continue;
1168      StringRef FName = SP.getLinkageName();
1169      if (FName.empty())
1170        FName = SP.getName();
1171      NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
1172      if (!NMD) continue;
1173      unsigned E = NMD->getNumOperands();
1174      if (!E) continue;
1175      DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
1176      DeadFnScopeMap[SP] = Scope;
1177      for (unsigned I = 0; I != E; ++I) {
1178        DIVariable DV(NMD->getOperand(I));
1179        if (!DV.Verify()) continue;
1180        Scope->addVariable(new DbgVariable(DV));
1181      }
1182
1183      // Construct subprogram DIE and add variables DIEs.
1184      constructSubprogramDIE(SP);
1185      DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
1186      const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1187      for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1188        DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1189        if (VariableDIE)
1190          ScopeDIE->addChild(VariableDIE);
1191      }
1192    }
1193  }
1194
1195  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1196  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1197         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1198    DIE *ISP = *AI;
1199    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1200  }
1201
1202  for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1203         CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1204    DIE *SPDie = CI->first;
1205    const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1206    if (!N) continue;
1207    DIE *NDie = getCompileUnit(N)->getDIE(N);
1208    if (!NDie) continue;
1209    getCompileUnit(N)->addDIEEntry(SPDie, dwarf::DW_AT_containing_type,
1210                                   dwarf::DW_FORM_ref4, NDie);
1211  }
1212
1213  // Standard sections final addresses.
1214  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1215  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1216  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1217  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1218
1219  // End text sections.
1220  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1221    Asm->OutStreamer.SwitchSection(SectionMap[i]);
1222    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1223  }
1224
1225  // Emit common frame information.
1226  emitCommonDebugFrame();
1227
1228  // Emit function debug frame information
1229  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1230         E = DebugFrames.end(); I != E; ++I)
1231    emitFunctionDebugFrame(*I);
1232
1233  // Compute DIE offsets and sizes.
1234  computeSizeAndOffsets();
1235
1236  // Emit all the DIEs into a debug info section
1237  emitDebugInfo();
1238
1239  // Corresponding abbreviations into a abbrev section.
1240  emitAbbreviations();
1241
1242  // Emit info into a debug pubnames section.
1243  emitDebugPubNames();
1244
1245  // Emit info into a debug pubtypes section.
1246  emitDebugPubTypes();
1247
1248  // Emit info into a debug loc section.
1249  emitDebugLoc();
1250
1251  // Emit info into a debug aranges section.
1252  EmitDebugARanges();
1253
1254  // Emit info into a debug ranges section.
1255  emitDebugRanges();
1256
1257  // Emit info into a debug macinfo section.
1258  emitDebugMacInfo();
1259
1260  // Emit inline info.
1261  emitDebugInlineInfo();
1262
1263  // Emit info into a debug str section.
1264  emitDebugStr();
1265
1266  // clean up.
1267  DeleteContainerSeconds(DeadFnScopeMap);
1268  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1269         E = CUMap.end(); I != E; ++I)
1270    delete I->second;
1271  FirstCU = NULL;  // Reset for the next Module, if any.
1272}
1273
1274/// findAbstractVariable - Find abstract variable, if any, associated with Var.
1275DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1276                                              DebugLoc ScopeLoc) {
1277
1278  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1279  if (AbsDbgVariable)
1280    return AbsDbgVariable;
1281
1282  LLVMContext &Ctx = Var->getContext();
1283  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
1284  if (!Scope)
1285    return NULL;
1286
1287  AbsDbgVariable = new DbgVariable(Var);
1288  Scope->addVariable(AbsDbgVariable);
1289  AbstractVariables[Var] = AbsDbgVariable;
1290  return AbsDbgVariable;
1291}
1292
1293/// addCurrentFnArgument - If Var is an current function argument that add
1294/// it in CurrentFnArguments list.
1295bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1296                                      DbgVariable *Var, DbgScope *Scope) {
1297  if (Scope != CurrentFnDbgScope)
1298    return false;
1299  DIVariable DV = Var->getVariable();
1300  if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1301    return false;
1302  unsigned ArgNo = DV.getArgNumber();
1303  if (ArgNo == 0)
1304    return false;
1305
1306  size_t Size = CurrentFnArguments.size();
1307  if (Size == 0)
1308    CurrentFnArguments.resize(MF->getFunction()->arg_size());
1309  // llvm::Function argument size is not good indicator of how many
1310  // arguments does the function have at source level.
1311  if (ArgNo > Size)
1312    CurrentFnArguments.resize(ArgNo * 2);
1313  CurrentFnArguments[ArgNo - 1] = Var;
1314  return true;
1315}
1316
1317/// collectVariableInfoFromMMITable - Collect variable information from
1318/// side table maintained by MMI.
1319void
1320DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
1321                                   SmallPtrSet<const MDNode *, 16> &Processed) {
1322  const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1323  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1324  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1325         VE = VMap.end(); VI != VE; ++VI) {
1326    const MDNode *Var = VI->first;
1327    if (!Var) continue;
1328    Processed.insert(Var);
1329    DIVariable DV(Var);
1330    const std::pair<unsigned, DebugLoc> &VP = VI->second;
1331
1332    DbgScope *Scope = 0;
1333    if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
1334      Scope = ConcreteScopes.lookup(IA);
1335    if (Scope == 0)
1336      Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
1337
1338    // If variable scope is not found then skip this variable.
1339    if (Scope == 0)
1340      continue;
1341
1342    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1343    DbgVariable *RegVar = new DbgVariable(DV);
1344    recordVariableFrameIndex(RegVar, VP.first);
1345    if (!addCurrentFnArgument(MF, RegVar, Scope))
1346      Scope->addVariable(RegVar);
1347    if (AbsDbgVariable) {
1348      recordVariableFrameIndex(AbsDbgVariable, VP.first);
1349      VarToAbstractVarMap[RegVar] = AbsDbgVariable;
1350    }
1351  }
1352}
1353
1354/// isDbgValueInDefinedReg - Return true if debug value, encoded by
1355/// DBG_VALUE instruction, is in a defined reg.
1356static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1357  assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1358  return MI->getNumOperands() == 3 &&
1359         MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1360         MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1361}
1362
1363/// collectVariableInfo - Populate DbgScope entries with variables' info.
1364void
1365DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1366                                SmallPtrSet<const MDNode *, 16> &Processed) {
1367
1368  /// collection info from MMI table.
1369  collectVariableInfoFromMMITable(MF, Processed);
1370
1371  for (SmallVectorImpl<const MDNode*>::const_iterator
1372         UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1373         ++UVI) {
1374    const MDNode *Var = *UVI;
1375    if (Processed.count(Var))
1376      continue;
1377
1378    // History contains relevant DBG_VALUE instructions for Var and instructions
1379    // clobbering it.
1380    SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1381    if (History.empty())
1382      continue;
1383    const MachineInstr *MInsn = History.front();
1384
1385    DIVariable DV(Var);
1386    DbgScope *Scope = NULL;
1387    if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1388        DISubprogram(DV.getContext()).describes(MF->getFunction()))
1389      Scope = CurrentFnDbgScope;
1390    else
1391      Scope = findDbgScope(MInsn);
1392    // If variable scope is not found then skip this variable.
1393    if (!Scope)
1394      continue;
1395
1396    Processed.insert(DV);
1397    assert(MInsn->isDebugValue() && "History must begin with debug value");
1398    DbgVariable *RegVar = new DbgVariable(DV);
1399    if (!addCurrentFnArgument(MF, RegVar, Scope))
1400      Scope->addVariable(RegVar);
1401    if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1402      DbgVariableToDbgInstMap[AbsVar] = MInsn;
1403      VarToAbstractVarMap[RegVar] = AbsVar;
1404    }
1405
1406    // Simple ranges that are fully coalesced.
1407    if (History.size() <= 1 || (History.size() == 2 &&
1408                                MInsn->isIdenticalTo(History.back()))) {
1409      DbgVariableToDbgInstMap[RegVar] = MInsn;
1410      continue;
1411    }
1412
1413    // handle multiple DBG_VALUE instructions describing one variable.
1414    RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1415
1416    for (SmallVectorImpl<const MachineInstr*>::const_iterator
1417           HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1418      const MachineInstr *Begin = *HI;
1419      assert(Begin->isDebugValue() && "Invalid History entry");
1420      MachineLocation MLoc;
1421      if (Begin->getNumOperands() == 3) {
1422        if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
1423          MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
1424      } else
1425        MLoc = Asm->getDebugValueLocation(Begin);
1426
1427      // FIXME: emitDebugLoc only understands registers.
1428      if (!MLoc.getReg())
1429        continue;
1430
1431      // Compute the range for a register location.
1432      const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1433      const MCSymbol *SLabel = 0;
1434
1435      if (HI + 1 == HE)
1436        // If Begin is the last instruction in History then its value is valid
1437        // until the end of the function.
1438        SLabel = FunctionEndSym;
1439      else {
1440        const MachineInstr *End = HI[1];
1441        if (End->isDebugValue())
1442          SLabel = getLabelBeforeInsn(End);
1443        else {
1444          // End is a normal instruction clobbering the range.
1445          SLabel = getLabelAfterInsn(End);
1446          assert(SLabel && "Forgot label after clobber instruction");
1447          ++HI;
1448        }
1449      }
1450
1451      // The value is valid until the next DBG_VALUE or clobber.
1452      DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
1453    }
1454    DotDebugLocEntries.push_back(DotDebugLocEntry());
1455  }
1456
1457  // Collect info for variables that were optimized out.
1458  const Function *F = MF->getFunction();
1459  if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1460    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1461      DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1462      if (!DV || !Processed.insert(DV))
1463        continue;
1464      DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
1465      if (Scope)
1466        Scope->addVariable(new DbgVariable(DV));
1467    }
1468  }
1469}
1470
1471/// getLabelBeforeInsn - Return Label preceding the instruction.
1472const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1473  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1474  assert(Label && "Didn't insert label before instruction");
1475  return Label;
1476}
1477
1478/// getLabelAfterInsn - Return Label immediately following the instruction.
1479const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1480  return LabelsAfterInsn.lookup(MI);
1481}
1482
1483/// beginInstruction - Process beginning of an instruction.
1484void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1485  // Check if source location changes, but ignore DBG_VALUE locations.
1486  if (!MI->isDebugValue()) {
1487    DebugLoc DL = MI->getDebugLoc();
1488    if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1489      PrevInstLoc = DL;
1490      if (!DL.isUnknown()) {
1491        const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1492        recordSourceLine(DL.getLine(), DL.getCol(), Scope);
1493      } else
1494        recordSourceLine(0, 0, 0);
1495    }
1496  }
1497
1498  // Insert labels where requested.
1499  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1500    LabelsBeforeInsn.find(MI);
1501
1502  // No label needed.
1503  if (I == LabelsBeforeInsn.end())
1504    return;
1505
1506  // Label already assigned.
1507  if (I->second)
1508    return;
1509
1510  if (!PrevLabel) {
1511    PrevLabel = MMI->getContext().CreateTempSymbol();
1512    Asm->OutStreamer.EmitLabel(PrevLabel);
1513  }
1514  I->second = PrevLabel;
1515}
1516
1517/// endInstruction - Process end of an instruction.
1518void DwarfDebug::endInstruction(const MachineInstr *MI) {
1519  // Don't create a new label after DBG_VALUE instructions.
1520  // They don't generate code.
1521  if (!MI->isDebugValue())
1522    PrevLabel = 0;
1523
1524  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1525    LabelsAfterInsn.find(MI);
1526
1527  // No label needed.
1528  if (I == LabelsAfterInsn.end())
1529    return;
1530
1531  // Label already assigned.
1532  if (I->second)
1533    return;
1534
1535  // We need a label after this instruction.
1536  if (!PrevLabel) {
1537    PrevLabel = MMI->getContext().CreateTempSymbol();
1538    Asm->OutStreamer.EmitLabel(PrevLabel);
1539  }
1540  I->second = PrevLabel;
1541}
1542
1543/// getOrCreateDbgScope - Create DbgScope for the scope.
1544DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
1545                                          const MDNode *InlinedAt) {
1546  if (!InlinedAt) {
1547    DbgScope *WScope = DbgScopeMap.lookup(Scope);
1548    if (WScope)
1549      return WScope;
1550    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1551    DbgScopeMap.insert(std::make_pair(Scope, WScope));
1552    if (DIDescriptor(Scope).isLexicalBlock()) {
1553      DbgScope *Parent =
1554        getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
1555      WScope->setParent(Parent);
1556      Parent->addScope(WScope);
1557    }
1558
1559    if (!WScope->getParent()) {
1560      StringRef SPName = DISubprogram(Scope).getLinkageName();
1561      // We used to check only for a linkage name, but that fails
1562      // since we began omitting the linkage name for private
1563      // functions.  The new way is to check for the name in metadata,
1564      // but that's not supported in old .ll test cases.  Ergo, we
1565      // check both.
1566      if (SPName == Asm->MF->getFunction()->getName() ||
1567          DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
1568        CurrentFnDbgScope = WScope;
1569    }
1570
1571    return WScope;
1572  }
1573
1574  getOrCreateAbstractScope(Scope);
1575  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1576  if (WScope)
1577    return WScope;
1578
1579  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1580  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1581  DILocation DL(InlinedAt);
1582  DbgScope *Parent =
1583    getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
1584  WScope->setParent(Parent);
1585  Parent->addScope(WScope);
1586
1587  ConcreteScopes[InlinedAt] = WScope;
1588
1589  return WScope;
1590}
1591
1592/// hasValidLocation - Return true if debug location entry attached with
1593/// machine instruction encodes valid location info.
1594static bool hasValidLocation(LLVMContext &Ctx,
1595                             const MachineInstr *MInsn,
1596                             const MDNode *&Scope, const MDNode *&InlinedAt) {
1597  DebugLoc DL = MInsn->getDebugLoc();
1598  if (DL.isUnknown()) return false;
1599
1600  const MDNode *S = DL.getScope(Ctx);
1601
1602  // There is no need to create another DIE for compile unit. For all
1603  // other scopes, create one DbgScope now. This will be translated
1604  // into a scope DIE at the end.
1605  if (DIScope(S).isCompileUnit()) return false;
1606
1607  Scope = S;
1608  InlinedAt = DL.getInlinedAt(Ctx);
1609  return true;
1610}
1611
1612/// calculateDominanceGraph - Calculate dominance graph for DbgScope
1613/// hierarchy.
1614static void calculateDominanceGraph(DbgScope *Scope) {
1615  assert (Scope && "Unable to calculate scop edominance graph!");
1616  SmallVector<DbgScope *, 4> WorkStack;
1617  WorkStack.push_back(Scope);
1618  unsigned Counter = 0;
1619  while (!WorkStack.empty()) {
1620    DbgScope *WS = WorkStack.back();
1621    const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
1622    bool visitedChildren = false;
1623    for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1624           SE = Children.end(); SI != SE; ++SI) {
1625      DbgScope *ChildScope = *SI;
1626      if (!ChildScope->getDFSOut()) {
1627        WorkStack.push_back(ChildScope);
1628        visitedChildren = true;
1629        ChildScope->setDFSIn(++Counter);
1630        break;
1631      }
1632    }
1633    if (!visitedChildren) {
1634      WorkStack.pop_back();
1635      WS->setDFSOut(++Counter);
1636    }
1637  }
1638}
1639
1640/// printDbgScopeInfo - Print DbgScope info for each machine instruction.
1641static
1642void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
1643                       DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
1644{
1645#ifndef NDEBUG
1646  unsigned PrevDFSIn = 0;
1647  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1648       I != E; ++I) {
1649    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1650         II != IE; ++II) {
1651      const MachineInstr *MInsn = II;
1652      const MDNode *Scope = NULL;
1653      const MDNode *InlinedAt = NULL;
1654
1655      // Check if instruction has valid location information.
1656      if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1657        dbgs() << " [ ";
1658        if (InlinedAt)
1659          dbgs() << "*";
1660        DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
1661          MI2ScopeMap.find(MInsn);
1662        if (DI != MI2ScopeMap.end()) {
1663          DbgScope *S = DI->second;
1664          dbgs() << S->getDFSIn();
1665          PrevDFSIn = S->getDFSIn();
1666        } else
1667          dbgs() << PrevDFSIn;
1668      } else
1669        dbgs() << " [ x" << PrevDFSIn;
1670      dbgs() << " ]";
1671      MInsn->dump();
1672    }
1673    dbgs() << "\n";
1674  }
1675#endif
1676}
1677/// extractScopeInformation - Scan machine instructions in this function
1678/// and collect DbgScopes. Return true, if at least one scope was found.
1679bool DwarfDebug::extractScopeInformation() {
1680  // If scope information was extracted using .dbg intrinsics then there is not
1681  // any need to extract these information by scanning each instruction.
1682  if (!DbgScopeMap.empty())
1683    return false;
1684
1685  // Scan each instruction and create scopes. First build working set of scopes.
1686  LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1687  SmallVector<DbgRange, 4> MIRanges;
1688  DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
1689  const MDNode *PrevScope = NULL;
1690  const MDNode *PrevInlinedAt = NULL;
1691  const MachineInstr *RangeBeginMI = NULL;
1692  const MachineInstr *PrevMI = NULL;
1693  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
1694       I != E; ++I) {
1695    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1696         II != IE; ++II) {
1697      const MachineInstr *MInsn = II;
1698      const MDNode *Scope = NULL;
1699      const MDNode *InlinedAt = NULL;
1700
1701      // Check if instruction has valid location information.
1702      if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1703        PrevMI = MInsn;
1704        continue;
1705      }
1706
1707      // If scope has not changed then skip this instruction.
1708      if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
1709        PrevMI = MInsn;
1710        continue;
1711      }
1712
1713      // Ignore DBG_VALUE. It does not contribute any instruction in output.
1714      if (MInsn->isDebugValue())
1715        continue;
1716
1717      if (RangeBeginMI) {
1718        // If we have alread seen a beginning of a instruction range and
1719        // current instruction scope does not match scope of first instruction
1720        // in this range then create a new instruction range.
1721        DbgRange R(RangeBeginMI, PrevMI);
1722        MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
1723                                                        PrevInlinedAt);
1724        MIRanges.push_back(R);
1725      }
1726
1727      // This is a beginning of a new instruction range.
1728      RangeBeginMI = MInsn;
1729
1730      // Reset previous markers.
1731      PrevMI = MInsn;
1732      PrevScope = Scope;
1733      PrevInlinedAt = InlinedAt;
1734    }
1735  }
1736
1737  // Create last instruction range.
1738  if (RangeBeginMI && PrevMI && PrevScope) {
1739    DbgRange R(RangeBeginMI, PrevMI);
1740    MIRanges.push_back(R);
1741    MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
1742  }
1743
1744  if (!CurrentFnDbgScope)
1745    return false;
1746
1747  calculateDominanceGraph(CurrentFnDbgScope);
1748  if (PrintDbgScope)
1749    printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
1750
1751  // Find ranges of instructions covered by each DbgScope;
1752  DbgScope *PrevDbgScope = NULL;
1753  for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
1754         RE = MIRanges.end(); RI != RE; ++RI) {
1755    const DbgRange &R = *RI;
1756    DbgScope *S = MI2ScopeMap.lookup(R.first);
1757    assert (S && "Lost DbgScope for a machine instruction!");
1758    if (PrevDbgScope && !PrevDbgScope->dominates(S))
1759      PrevDbgScope->closeInsnRange(S);
1760    S->openInsnRange(R.first);
1761    S->extendInsnRange(R.second);
1762    PrevDbgScope = S;
1763  }
1764
1765  if (PrevDbgScope)
1766    PrevDbgScope->closeInsnRange();
1767
1768  identifyScopeMarkers();
1769
1770  return !DbgScopeMap.empty();
1771}
1772
1773/// identifyScopeMarkers() -
1774/// Each DbgScope has first instruction and last instruction to mark beginning
1775/// and end of a scope respectively. Create an inverse map that list scopes
1776/// starts (and ends) with an instruction. One instruction may start (or end)
1777/// multiple scopes. Ignore scopes that are not reachable.
1778void DwarfDebug::identifyScopeMarkers() {
1779  SmallVector<DbgScope *, 4> WorkList;
1780  WorkList.push_back(CurrentFnDbgScope);
1781  while (!WorkList.empty()) {
1782    DbgScope *S = WorkList.pop_back_val();
1783
1784    const SmallVector<DbgScope *, 4> &Children = S->getScopes();
1785    if (!Children.empty())
1786      for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1787             SE = Children.end(); SI != SE; ++SI)
1788        WorkList.push_back(*SI);
1789
1790    if (S->isAbstractScope())
1791      continue;
1792
1793    const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
1794    if (Ranges.empty())
1795      continue;
1796    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1797           RE = Ranges.end(); RI != RE; ++RI) {
1798      assert(RI->first && "DbgRange does not have first instruction!");
1799      assert(RI->second && "DbgRange does not have second instruction!");
1800      requestLabelBeforeInsn(RI->first);
1801      requestLabelAfterInsn(RI->second);
1802    }
1803  }
1804}
1805
1806/// FindFirstDebugLoc - Find the first debug location in the function. This
1807/// is intended to be an approximation for the source position of the
1808/// beginning of the function.
1809static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
1810  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1811       I != E; ++I)
1812    for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
1813         MBBI != MBBE; ++MBBI) {
1814      DebugLoc DL = MBBI->getDebugLoc();
1815      if (!DL.isUnknown())
1816        return DL;
1817    }
1818  return DebugLoc();
1819}
1820
1821#ifndef NDEBUG
1822/// CheckLineNumbers - Count basicblocks whose instructions do not have any
1823/// line number information.
1824static void CheckLineNumbers(const MachineFunction *MF) {
1825  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1826       I != E; ++I) {
1827    bool FoundLineNo = false;
1828    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1829         II != IE; ++II) {
1830      const MachineInstr *MI = II;
1831      if (!MI->getDebugLoc().isUnknown()) {
1832        FoundLineNo = true;
1833        break;
1834      }
1835    }
1836    if (!FoundLineNo && I->size())
1837      ++BlocksWithoutLineNo;
1838  }
1839}
1840#endif
1841
1842/// beginFunction - Gather pre-function debug information.  Assumes being
1843/// emitted immediately after the function entry point.
1844void DwarfDebug::beginFunction(const MachineFunction *MF) {
1845  if (!MMI->hasDebugInfo()) return;
1846  if (!extractScopeInformation()) return;
1847
1848#ifndef NDEBUG
1849  CheckLineNumbers(MF);
1850#endif
1851
1852  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1853                                        Asm->getFunctionNumber());
1854  // Assumes in correct section after the entry point.
1855  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1856
1857  // Emit label for the implicitly defined dbg.stoppoint at the start of the
1858  // function.
1859  DebugLoc FDL = FindFirstDebugLoc(MF);
1860  if (FDL.isUnknown()) return;
1861
1862  const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
1863  const MDNode *TheScope = 0;
1864
1865  DISubprogram SP = getDISubprogram(Scope);
1866  unsigned Line, Col;
1867  if (SP.Verify()) {
1868    Line = SP.getLineNumber();
1869    Col = 0;
1870    TheScope = SP;
1871  } else {
1872    Line = FDL.getLine();
1873    Col = FDL.getCol();
1874    TheScope = Scope;
1875  }
1876
1877  recordSourceLine(Line, Col, TheScope);
1878
1879  assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1880
1881  /// ProcessedArgs - Collection of arguments already processed.
1882  SmallPtrSet<const MDNode *, 8> ProcessedArgs;
1883
1884  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1885
1886  /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1887  std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1888
1889  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1890       I != E; ++I) {
1891    bool AtBlockEntry = true;
1892    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1893         II != IE; ++II) {
1894      const MachineInstr *MI = II;
1895
1896      if (MI->isDebugValue()) {
1897        assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1898
1899        // Keep track of user variables.
1900        const MDNode *Var =
1901          MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1902
1903        // Variable is in a register, we need to check for clobbers.
1904        if (isDbgValueInDefinedReg(MI))
1905          LiveUserVar[MI->getOperand(0).getReg()] = Var;
1906
1907        // Check the history of this variable.
1908        SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1909        if (History.empty()) {
1910          UserVariables.push_back(Var);
1911          // The first mention of a function argument gets the FunctionBeginSym
1912          // label, so arguments are visible when breaking at function entry.
1913          DIVariable DV(Var);
1914          if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1915              DISubprogram(getDISubprogram(DV.getContext()))
1916                .describes(MF->getFunction()))
1917            LabelsBeforeInsn[MI] = FunctionBeginSym;
1918        } else {
1919          // We have seen this variable before. Try to coalesce DBG_VALUEs.
1920          const MachineInstr *Prev = History.back();
1921          if (Prev->isDebugValue()) {
1922            // Coalesce identical entries at the end of History.
1923            if (History.size() >= 2 &&
1924                Prev->isIdenticalTo(History[History.size() - 2]))
1925              History.pop_back();
1926
1927            // Terminate old register assignments that don't reach MI;
1928            MachineFunction::const_iterator PrevMBB = Prev->getParent();
1929            if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1930                isDbgValueInDefinedReg(Prev)) {
1931              // Previous register assignment needs to terminate at the end of
1932              // its basic block.
1933              MachineBasicBlock::const_iterator LastMI =
1934                PrevMBB->getLastNonDebugInstr();
1935              if (LastMI == PrevMBB->end())
1936                // Drop DBG_VALUE for empty range.
1937                History.pop_back();
1938              else {
1939                // Terminate after LastMI.
1940                History.push_back(LastMI);
1941              }
1942            }
1943          }
1944        }
1945        History.push_back(MI);
1946      } else {
1947        // Not a DBG_VALUE instruction.
1948        if (!MI->isLabel())
1949          AtBlockEntry = false;
1950
1951        // Check if the instruction clobbers any registers with debug vars.
1952        for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1953               MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1954          if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1955            continue;
1956          for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1957               unsigned Reg = *AI; ++AI) {
1958            const MDNode *Var = LiveUserVar[Reg];
1959            if (!Var)
1960              continue;
1961            // Reg is now clobbered.
1962            LiveUserVar[Reg] = 0;
1963
1964            // Was MD last defined by a DBG_VALUE referring to Reg?
1965            DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1966            if (HistI == DbgValues.end())
1967              continue;
1968            SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1969            if (History.empty())
1970              continue;
1971            const MachineInstr *Prev = History.back();
1972            // Sanity-check: Register assignments are terminated at the end of
1973            // their block.
1974            if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1975              continue;
1976            // Is the variable still in Reg?
1977            if (!isDbgValueInDefinedReg(Prev) ||
1978                Prev->getOperand(0).getReg() != Reg)
1979              continue;
1980            // Var is clobbered. Make sure the next instruction gets a label.
1981            History.push_back(MI);
1982          }
1983        }
1984      }
1985    }
1986  }
1987
1988  for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1989       I != E; ++I) {
1990    SmallVectorImpl<const MachineInstr*> &History = I->second;
1991    if (History.empty())
1992      continue;
1993
1994    // Make sure the final register assignments are terminated.
1995    const MachineInstr *Prev = History.back();
1996    if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1997      const MachineBasicBlock *PrevMBB = Prev->getParent();
1998      MachineBasicBlock::const_iterator LastMI = PrevMBB->getLastNonDebugInstr();
1999      if (LastMI == PrevMBB->end())
2000        // Drop DBG_VALUE for empty range.
2001        History.pop_back();
2002      else {
2003        // Terminate after LastMI.
2004        History.push_back(LastMI);
2005      }
2006    }
2007    // Request labels for the full history.
2008    for (unsigned i = 0, e = History.size(); i != e; ++i) {
2009      const MachineInstr *MI = History[i];
2010      if (MI->isDebugValue())
2011        requestLabelBeforeInsn(MI);
2012      else
2013        requestLabelAfterInsn(MI);
2014    }
2015  }
2016
2017  PrevInstLoc = DebugLoc();
2018  PrevLabel = FunctionBeginSym;
2019}
2020
2021/// endFunction - Gather and emit post-function debug information.
2022///
2023void DwarfDebug::endFunction(const MachineFunction *MF) {
2024  if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2025
2026  if (CurrentFnDbgScope) {
2027
2028    // Define end label for subprogram.
2029    FunctionEndSym = Asm->GetTempSymbol("func_end",
2030                                        Asm->getFunctionNumber());
2031    // Assumes in correct section after the entry point.
2032    Asm->OutStreamer.EmitLabel(FunctionEndSym);
2033
2034    SmallPtrSet<const MDNode *, 16> ProcessedVars;
2035    collectVariableInfo(MF, ProcessedVars);
2036
2037    // Construct abstract scopes.
2038    for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2039           AE = AbstractScopesList.end(); AI != AE; ++AI) {
2040      DISubprogram SP((*AI)->getScopeNode());
2041      if (SP.Verify()) {
2042        // Collect info for variables that were optimized out.
2043        StringRef FName = SP.getLinkageName();
2044        if (FName.empty())
2045          FName = SP.getName();
2046        if (NamedMDNode *NMD =
2047            getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
2048          for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2049          DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2050          if (!DV || !ProcessedVars.insert(DV))
2051            continue;
2052          DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2053          if (Scope)
2054            Scope->addVariable(new DbgVariable(DV));
2055          }
2056        }
2057      }
2058      if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2059        constructScopeDIE(*AI);
2060    }
2061
2062    DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2063
2064    if (!DisableFramePointerElim(*MF))
2065      getCompileUnit(CurrentFnDbgScope->getScopeNode())->addUInt(CurFnDIE,
2066                                                                 dwarf::DW_AT_APPLE_omit_frame_ptr,
2067                                                                 dwarf::DW_FORM_flag, 1);
2068
2069
2070    DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2071                                                 MMI->getFrameMoves()));
2072  }
2073
2074  // Clear debug info
2075  CurrentFnDbgScope = NULL;
2076  DeleteContainerPointers(CurrentFnArguments);
2077  DbgVariableToFrameIndexMap.clear();
2078  VarToAbstractVarMap.clear();
2079  DbgVariableToDbgInstMap.clear();
2080  DeleteContainerSeconds(DbgScopeMap);
2081  UserVariables.clear();
2082  DbgValues.clear();
2083  ConcreteScopes.clear();
2084  DeleteContainerSeconds(AbstractScopes);
2085  AbstractScopesList.clear();
2086  AbstractVariables.clear();
2087  LabelsBeforeInsn.clear();
2088  LabelsAfterInsn.clear();
2089  PrevLabel = NULL;
2090}
2091
2092/// recordVariableFrameIndex - Record a variable's index.
2093void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2094  assert (V && "Invalid DbgVariable!");
2095  DbgVariableToFrameIndexMap[V] = Index;
2096}
2097
2098/// findVariableFrameIndex - Return true if frame index for the variable
2099/// is found. Update FI to hold value of the index.
2100bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2101  assert (V && "Invalid DbgVariable!");
2102  DenseMap<const DbgVariable *, int>::iterator I =
2103    DbgVariableToFrameIndexMap.find(V);
2104  if (I == DbgVariableToFrameIndexMap.end())
2105    return false;
2106  *FI = I->second;
2107  return true;
2108}
2109
2110/// findDbgScope - Find DbgScope for the debug loc attached with an
2111/// instruction.
2112DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2113  DbgScope *Scope = NULL;
2114  LLVMContext &Ctx =
2115    MInsn->getParent()->getParent()->getFunction()->getContext();
2116  DebugLoc DL = MInsn->getDebugLoc();
2117
2118  if (DL.isUnknown())
2119    return Scope;
2120
2121  if (const MDNode *IA = DL.getInlinedAt(Ctx))
2122    Scope = ConcreteScopes.lookup(IA);
2123  if (Scope == 0)
2124    Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2125
2126  return Scope;
2127}
2128
2129
2130/// recordSourceLine - Register a source line with debug info. Returns the
2131/// unique label that was emitted and which provides correspondence to
2132/// the source line list.
2133void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S){
2134  StringRef Fn;
2135  StringRef Dir;
2136  unsigned Src = 1;
2137  if (S) {
2138    DIDescriptor Scope(S);
2139
2140    if (Scope.isCompileUnit()) {
2141      DICompileUnit CU(S);
2142      Fn = CU.getFilename();
2143      Dir = CU.getDirectory();
2144    } else if (Scope.isFile()) {
2145      DIFile F(S);
2146      Fn = F.getFilename();
2147      Dir = F.getDirectory();
2148    } else if (Scope.isSubprogram()) {
2149      DISubprogram SP(S);
2150      Fn = SP.getFilename();
2151      Dir = SP.getDirectory();
2152    } else if (Scope.isLexicalBlock()) {
2153      DILexicalBlock DB(S);
2154      Fn = DB.getFilename();
2155      Dir = DB.getDirectory();
2156    } else
2157      assert(0 && "Unexpected scope info");
2158
2159    Src = GetOrCreateSourceID(Fn, Dir);
2160  }
2161  Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, DWARF2_FLAG_IS_STMT,
2162                                         0, 0, Fn);
2163}
2164
2165//===----------------------------------------------------------------------===//
2166// Emit Methods
2167//===----------------------------------------------------------------------===//
2168
2169/// computeSizeAndOffset - Compute the size and offset of a DIE.
2170///
2171unsigned
2172DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2173  // Get the children.
2174  const std::vector<DIE *> &Children = Die->getChildren();
2175
2176  // If not last sibling and has children then add sibling offset attribute.
2177  if (!Last && !Children.empty())
2178    Die->addSiblingOffset(DIEValueAllocator);
2179
2180  // Record the abbreviation.
2181  assignAbbrevNumber(Die->getAbbrev());
2182
2183  // Get the abbreviation for this DIE.
2184  unsigned AbbrevNumber = Die->getAbbrevNumber();
2185  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2186
2187  // Set DIE offset
2188  Die->setOffset(Offset);
2189
2190  // Start the size with the size of abbreviation code.
2191  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2192
2193  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2194  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2195
2196  // Size the DIE attribute values.
2197  for (unsigned i = 0, N = Values.size(); i < N; ++i)
2198    // Size attribute value.
2199    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2200
2201  // Size the DIE children if any.
2202  if (!Children.empty()) {
2203    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2204           "Children flag not set");
2205
2206    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2207      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2208
2209    // End of children marker.
2210    Offset += sizeof(int8_t);
2211  }
2212
2213  Die->setSize(Offset - Die->getOffset());
2214  return Offset;
2215}
2216
2217/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2218///
2219void DwarfDebug::computeSizeAndOffsets() {
2220  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2221         E = CUMap.end(); I != E; ++I) {
2222    // Compute size of compile unit header.
2223    unsigned Offset =
2224      sizeof(int32_t) + // Length of Compilation Unit Info
2225      sizeof(int16_t) + // DWARF version number
2226      sizeof(int32_t) + // Offset Into Abbrev. Section
2227      sizeof(int8_t);   // Pointer Size (in bytes)
2228    computeSizeAndOffset(I->second->getCUDie(), Offset, true);
2229  }
2230}
2231
2232/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2233/// temporary label to it if SymbolStem is specified.
2234static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2235                                const char *SymbolStem = 0) {
2236  Asm->OutStreamer.SwitchSection(Section);
2237  if (!SymbolStem) return 0;
2238
2239  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2240  Asm->OutStreamer.EmitLabel(TmpSym);
2241  return TmpSym;
2242}
2243
2244/// EmitSectionLabels - Emit initial Dwarf sections with a label at
2245/// the start of each one.
2246void DwarfDebug::EmitSectionLabels() {
2247  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2248
2249  // Dwarf sections base addresses.
2250  if (Asm->MAI->doesDwarfRequireFrameSection()) {
2251    DwarfFrameSectionSym =
2252      EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2253   }
2254
2255  DwarfInfoSectionSym =
2256    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2257  DwarfAbbrevSectionSym =
2258    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2259  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2260
2261  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2262    EmitSectionSym(Asm, MacroInfo);
2263
2264  EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2265  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2266  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2267  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2268  DwarfStrSectionSym =
2269    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2270  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2271                                             "debug_range");
2272
2273  DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
2274                                           "section_debug_loc");
2275
2276  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2277  EmitSectionSym(Asm, TLOF.getDataSection());
2278}
2279
2280/// emitDIE - Recusively Emits a debug information entry.
2281///
2282void DwarfDebug::emitDIE(DIE *Die) {
2283  // Get the abbreviation for this DIE.
2284  unsigned AbbrevNumber = Die->getAbbrevNumber();
2285  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2286
2287  // Emit the code (index) for the abbreviation.
2288  if (Asm->isVerbose())
2289    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2290                                Twine::utohexstr(Die->getOffset()) + ":0x" +
2291                                Twine::utohexstr(Die->getSize()) + " " +
2292                                dwarf::TagString(Abbrev->getTag()));
2293  Asm->EmitULEB128(AbbrevNumber);
2294
2295  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2296  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2297
2298  // Emit the DIE attribute values.
2299  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2300    unsigned Attr = AbbrevData[i].getAttribute();
2301    unsigned Form = AbbrevData[i].getForm();
2302    assert(Form && "Too many attributes for DIE (check abbreviation)");
2303
2304    if (Asm->isVerbose())
2305      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2306
2307    switch (Attr) {
2308    case dwarf::DW_AT_sibling:
2309      Asm->EmitInt32(Die->getSiblingOffset());
2310      break;
2311    case dwarf::DW_AT_abstract_origin: {
2312      DIEEntry *E = cast<DIEEntry>(Values[i]);
2313      DIE *Origin = E->getEntry();
2314      unsigned Addr = Origin->getOffset();
2315      Asm->EmitInt32(Addr);
2316      break;
2317    }
2318    case dwarf::DW_AT_ranges: {
2319      // DW_AT_range Value encodes offset in debug_range section.
2320      DIEInteger *V = cast<DIEInteger>(Values[i]);
2321
2322      if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
2323        Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2324                                 V->getValue(),
2325                                 4);
2326      } else {
2327        Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2328                                       V->getValue(),
2329                                       DwarfDebugRangeSectionSym,
2330                                       4);
2331      }
2332      break;
2333    }
2334    case dwarf::DW_AT_location: {
2335      if (UseDotDebugLocEntry.count(Die) != 0) {
2336        DIELabel *L = cast<DIELabel>(Values[i]);
2337        Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2338      } else
2339        Values[i]->EmitValue(Asm, Form);
2340      break;
2341    }
2342    case dwarf::DW_AT_accessibility: {
2343      if (Asm->isVerbose()) {
2344        DIEInteger *V = cast<DIEInteger>(Values[i]);
2345        Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2346      }
2347      Values[i]->EmitValue(Asm, Form);
2348      break;
2349    }
2350    default:
2351      // Emit an attribute using the defined form.
2352      Values[i]->EmitValue(Asm, Form);
2353      break;
2354    }
2355  }
2356
2357  // Emit the DIE children if any.
2358  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2359    const std::vector<DIE *> &Children = Die->getChildren();
2360
2361    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2362      emitDIE(Children[j]);
2363
2364    if (Asm->isVerbose())
2365      Asm->OutStreamer.AddComment("End Of Children Mark");
2366    Asm->EmitInt8(0);
2367  }
2368}
2369
2370/// emitDebugInfo - Emit the debug info section.
2371///
2372void DwarfDebug::emitDebugInfo() {
2373  // Start debug info section.
2374  Asm->OutStreamer.SwitchSection(
2375                            Asm->getObjFileLowering().getDwarfInfoSection());
2376  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2377         E = CUMap.end(); I != E; ++I) {
2378    CompileUnit *TheCU = I->second;
2379    DIE *Die = TheCU->getCUDie();
2380
2381    // Emit the compile units header.
2382    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2383                                                  TheCU->getID()));
2384
2385    // Emit size of content not including length itself
2386    unsigned ContentSize = Die->getSize() +
2387      sizeof(int16_t) + // DWARF version number
2388      sizeof(int32_t) + // Offset Into Abbrev. Section
2389      sizeof(int8_t);   // Pointer Size (in bytes)
2390
2391    Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2392    Asm->EmitInt32(ContentSize);
2393    Asm->OutStreamer.AddComment("DWARF version number");
2394    Asm->EmitInt16(dwarf::DWARF_VERSION);
2395    Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2396    Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2397                           DwarfAbbrevSectionSym);
2398    Asm->OutStreamer.AddComment("Address Size (in bytes)");
2399    Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2400
2401    emitDIE(Die);
2402    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
2403  }
2404}
2405
2406/// emitAbbreviations - Emit the abbreviation section.
2407///
2408void DwarfDebug::emitAbbreviations() const {
2409  // Check to see if it is worth the effort.
2410  if (!Abbreviations.empty()) {
2411    // Start the debug abbrev section.
2412    Asm->OutStreamer.SwitchSection(
2413                            Asm->getObjFileLowering().getDwarfAbbrevSection());
2414
2415    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2416
2417    // For each abbrevation.
2418    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2419      // Get abbreviation data
2420      const DIEAbbrev *Abbrev = Abbreviations[i];
2421
2422      // Emit the abbrevations code (base 1 index.)
2423      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2424
2425      // Emit the abbreviations data.
2426      Abbrev->Emit(Asm);
2427    }
2428
2429    // Mark end of abbreviations.
2430    Asm->EmitULEB128(0, "EOM(3)");
2431
2432    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2433  }
2434}
2435
2436/// emitEndOfLineMatrix - Emit the last address of the section and the end of
2437/// the line matrix.
2438///
2439void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2440  // Define last address of section.
2441  Asm->OutStreamer.AddComment("Extended Op");
2442  Asm->EmitInt8(0);
2443
2444  Asm->OutStreamer.AddComment("Op size");
2445  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2446  Asm->OutStreamer.AddComment("DW_LNE_set_address");
2447  Asm->EmitInt8(dwarf::DW_LNE_set_address);
2448
2449  Asm->OutStreamer.AddComment("Section end label");
2450
2451  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2452                                   Asm->getTargetData().getPointerSize(),
2453                                   0/*AddrSpace*/);
2454
2455  // Mark end of matrix.
2456  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2457  Asm->EmitInt8(0);
2458  Asm->EmitInt8(1);
2459  Asm->EmitInt8(1);
2460}
2461
2462/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2463///
2464void DwarfDebug::emitCommonDebugFrame() {
2465  if (!Asm->MAI->doesDwarfRequireFrameSection())
2466    return;
2467
2468  int stackGrowth = Asm->getTargetData().getPointerSize();
2469  if (Asm->TM.getFrameLowering()->getStackGrowthDirection() ==
2470      TargetFrameLowering::StackGrowsDown)
2471    stackGrowth *= -1;
2472
2473  // Start the dwarf frame section.
2474  Asm->OutStreamer.SwitchSection(
2475                              Asm->getObjFileLowering().getDwarfFrameSection());
2476
2477  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
2478  Asm->OutStreamer.AddComment("Length of Common Information Entry");
2479  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
2480                           Asm->GetTempSymbol("debug_frame_common_begin"), 4);
2481
2482  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
2483  Asm->OutStreamer.AddComment("CIE Identifier Tag");
2484  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2485  Asm->OutStreamer.AddComment("CIE Version");
2486  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2487  Asm->OutStreamer.AddComment("CIE Augmentation");
2488  Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
2489  Asm->EmitULEB128(1, "CIE Code Alignment Factor");
2490  Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
2491  Asm->OutStreamer.AddComment("CIE RA Column");
2492  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
2493  const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
2494  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2495
2496  std::vector<MachineMove> Moves;
2497  TFI->getInitialFrameState(Moves);
2498
2499  Asm->EmitFrameMoves(Moves, 0, false);
2500
2501  Asm->EmitAlignment(2);
2502  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
2503}
2504
2505/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2506/// section.
2507void DwarfDebug::
2508emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2509  if (!Asm->MAI->doesDwarfRequireFrameSection())
2510    return;
2511
2512  // Start the dwarf frame section.
2513  Asm->OutStreamer.SwitchSection(
2514                              Asm->getObjFileLowering().getDwarfFrameSection());
2515
2516  Asm->OutStreamer.AddComment("Length of Frame Information Entry");
2517  MCSymbol *DebugFrameBegin =
2518    Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
2519  MCSymbol *DebugFrameEnd =
2520    Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
2521  Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
2522
2523  Asm->OutStreamer.EmitLabel(DebugFrameBegin);
2524
2525  Asm->OutStreamer.AddComment("FDE CIE offset");
2526  Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
2527                         DwarfFrameSectionSym);
2528
2529  Asm->OutStreamer.AddComment("FDE initial location");
2530  MCSymbol *FuncBeginSym =
2531    Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
2532  Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
2533                                   Asm->getTargetData().getPointerSize(),
2534                                   0/*AddrSpace*/);
2535
2536
2537  Asm->OutStreamer.AddComment("FDE address range");
2538  Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
2539                           FuncBeginSym, Asm->getTargetData().getPointerSize());
2540
2541  Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
2542
2543  Asm->EmitAlignment(2);
2544  Asm->OutStreamer.EmitLabel(DebugFrameEnd);
2545}
2546
2547/// emitDebugPubNames - Emit visible names into a debug pubnames section.
2548///
2549void DwarfDebug::emitDebugPubNames() {
2550  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2551         E = CUMap.end(); I != E; ++I) {
2552    CompileUnit *TheCU = I->second;
2553    // Start the dwarf pubnames section.
2554    Asm->OutStreamer.SwitchSection(
2555      Asm->getObjFileLowering().getDwarfPubNamesSection());
2556
2557    Asm->OutStreamer.AddComment("Length of Public Names Info");
2558    Asm->EmitLabelDifference(
2559      Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
2560      Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
2561
2562    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
2563                                                  TheCU->getID()));
2564
2565    Asm->OutStreamer.AddComment("DWARF Version");
2566    Asm->EmitInt16(dwarf::DWARF_VERSION);
2567
2568    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2569    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2570                           DwarfInfoSectionSym);
2571
2572    Asm->OutStreamer.AddComment("Compilation Unit Length");
2573    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2574                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
2575                             4);
2576
2577    const StringMap<DIE*> &Globals = TheCU->getGlobals();
2578    for (StringMap<DIE*>::const_iterator
2579           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2580      const char *Name = GI->getKeyData();
2581      DIE *Entity = GI->second;
2582
2583      Asm->OutStreamer.AddComment("DIE offset");
2584      Asm->EmitInt32(Entity->getOffset());
2585
2586      if (Asm->isVerbose())
2587        Asm->OutStreamer.AddComment("External Name");
2588      Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2589    }
2590
2591    Asm->OutStreamer.AddComment("End Mark");
2592    Asm->EmitInt32(0);
2593    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
2594                                                TheCU->getID()));
2595  }
2596}
2597
2598void DwarfDebug::emitDebugPubTypes() {
2599  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2600         E = CUMap.end(); I != E; ++I) {
2601    CompileUnit *TheCU = I->second;
2602    // Start the dwarf pubnames section.
2603    Asm->OutStreamer.SwitchSection(
2604      Asm->getObjFileLowering().getDwarfPubTypesSection());
2605    Asm->OutStreamer.AddComment("Length of Public Types Info");
2606    Asm->EmitLabelDifference(
2607      Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
2608      Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
2609
2610    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2611                                                  TheCU->getID()));
2612
2613    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2614    Asm->EmitInt16(dwarf::DWARF_VERSION);
2615
2616    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2617    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2618                           DwarfInfoSectionSym);
2619
2620    Asm->OutStreamer.AddComment("Compilation Unit Length");
2621    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2622                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
2623                             4);
2624
2625    const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2626    for (StringMap<DIE*>::const_iterator
2627           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2628      const char *Name = GI->getKeyData();
2629      DIE * Entity = GI->second;
2630
2631      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2632      Asm->EmitInt32(Entity->getOffset());
2633
2634      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2635      Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2636    }
2637
2638    Asm->OutStreamer.AddComment("End Mark");
2639    Asm->EmitInt32(0);
2640    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2641                                                  TheCU->getID()));
2642  }
2643}
2644
2645/// emitDebugStr - Emit visible names into a debug str section.
2646///
2647void DwarfDebug::emitDebugStr() {
2648  // Check to see if it is worth the effort.
2649  if (StringPool.empty()) return;
2650
2651  // Start the dwarf str section.
2652  Asm->OutStreamer.SwitchSection(
2653                                Asm->getObjFileLowering().getDwarfStrSection());
2654
2655  // Get all of the string pool entries and put them in an array by their ID so
2656  // we can sort them.
2657  SmallVector<std::pair<unsigned,
2658      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2659
2660  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2661       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2662    Entries.push_back(std::make_pair(I->second.second, &*I));
2663
2664  array_pod_sort(Entries.begin(), Entries.end());
2665
2666  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2667    // Emit a label for reference from debug information entries.
2668    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2669
2670    // Emit the string itself.
2671    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
2672  }
2673}
2674
2675/// emitDebugLoc - Emit visible names into a debug loc section.
2676///
2677void DwarfDebug::emitDebugLoc() {
2678  if (DotDebugLocEntries.empty())
2679    return;
2680
2681  for (SmallVector<DotDebugLocEntry, 4>::iterator
2682         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2683       I != E; ++I) {
2684    DotDebugLocEntry &Entry = *I;
2685    if (I + 1 != DotDebugLocEntries.end())
2686      Entry.Merge(I+1);
2687  }
2688
2689  // Start the dwarf loc section.
2690  Asm->OutStreamer.SwitchSection(
2691    Asm->getObjFileLowering().getDwarfLocSection());
2692  unsigned char Size = Asm->getTargetData().getPointerSize();
2693  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2694  unsigned index = 1;
2695  for (SmallVector<DotDebugLocEntry, 4>::iterator
2696         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2697       I != E; ++I, ++index) {
2698    DotDebugLocEntry &Entry = *I;
2699    if (Entry.isMerged()) continue;
2700    if (Entry.isEmpty()) {
2701      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2702      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2703      Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2704    } else {
2705      Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2706      Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2707      Asm->EmitDwarfRegOp(Entry.Loc);
2708    }
2709  }
2710}
2711
2712/// EmitDebugARanges - Emit visible names into a debug aranges section.
2713///
2714void DwarfDebug::EmitDebugARanges() {
2715  // Start the dwarf aranges section.
2716  Asm->OutStreamer.SwitchSection(
2717                          Asm->getObjFileLowering().getDwarfARangesSection());
2718}
2719
2720/// emitDebugRanges - Emit visible names into a debug ranges section.
2721///
2722void DwarfDebug::emitDebugRanges() {
2723  // Start the dwarf ranges section.
2724  Asm->OutStreamer.SwitchSection(
2725    Asm->getObjFileLowering().getDwarfRangesSection());
2726  unsigned char Size = Asm->getTargetData().getPointerSize();
2727  for (SmallVector<const MCSymbol *, 8>::iterator
2728         I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2729       I != E; ++I) {
2730    if (*I)
2731      Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2732    else
2733      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2734  }
2735}
2736
2737/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2738///
2739void DwarfDebug::emitDebugMacInfo() {
2740  if (const MCSection *LineInfo =
2741      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2742    // Start the dwarf macinfo section.
2743    Asm->OutStreamer.SwitchSection(LineInfo);
2744  }
2745}
2746
2747/// emitDebugInlineInfo - Emit inline info using following format.
2748/// Section Header:
2749/// 1. length of section
2750/// 2. Dwarf version number
2751/// 3. address size.
2752///
2753/// Entries (one "entry" for each function that was inlined):
2754///
2755/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2756///   otherwise offset into __debug_str for regular function name.
2757/// 2. offset into __debug_str section for regular function name.
2758/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2759/// instances for the function.
2760///
2761/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2762/// inlined instance; the die_offset points to the inlined_subroutine die in the
2763/// __debug_info section, and the low_pc is the starting address for the
2764/// inlining instance.
2765void DwarfDebug::emitDebugInlineInfo() {
2766  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2767    return;
2768
2769  if (!FirstCU)
2770    return;
2771
2772  Asm->OutStreamer.SwitchSection(
2773                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
2774
2775  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2776  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2777                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2778
2779  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2780
2781  Asm->OutStreamer.AddComment("Dwarf Version");
2782  Asm->EmitInt16(dwarf::DWARF_VERSION);
2783  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2784  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2785
2786  for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2787         E = InlinedSPNodes.end(); I != E; ++I) {
2788
2789    const MDNode *Node = *I;
2790    DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2791      = InlineInfo.find(Node);
2792    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2793    DISubprogram SP(Node);
2794    StringRef LName = SP.getLinkageName();
2795    StringRef Name = SP.getName();
2796
2797    Asm->OutStreamer.AddComment("MIPS linkage name");
2798    if (LName.empty()) {
2799      Asm->OutStreamer.EmitBytes(Name, 0);
2800      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2801    } else
2802      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2803                             DwarfStrSectionSym);
2804
2805    Asm->OutStreamer.AddComment("Function name");
2806    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2807    Asm->EmitULEB128(Labels.size(), "Inline count");
2808
2809    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2810           LE = Labels.end(); LI != LE; ++LI) {
2811      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2812      Asm->EmitInt32(LI->second->getOffset());
2813
2814      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2815      Asm->OutStreamer.EmitSymbolValue(LI->first,
2816                                       Asm->getTargetData().getPointerSize(),0);
2817    }
2818  }
2819
2820  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2821}
2822