DwarfDebug.cpp revision 8b9df62d0227beab8c7adb487fb909e67bbc7237
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 absense 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
76//===----------------------------------------------------------------------===//
77/// DbgVariable - This class is used to track local variable information.
78///
79class DbgVariable {
80  DIVariable Var;                    // Variable Descriptor.
81  DIE *TheDIE;                       // Variable DIE.
82  unsigned DotDebugLocOffset;        // Offset in DotDebugLocEntries.
83public:
84  // AbsVar may be NULL.
85  DbgVariable(DIVariable V) : Var(V), TheDIE(0), DotDebugLocOffset(~0U) {}
86
87  // Accessors.
88  DIVariable getVariable()           const { return Var; }
89  void setDIE(DIE *D)                      { TheDIE = D; }
90  DIE *getDIE()                      const { return TheDIE; }
91  void setDotDebugLocOffset(unsigned O)    { DotDebugLocOffset = O; }
92  unsigned getDotDebugLocOffset()    const { return DotDebugLocOffset; }
93  StringRef getName()                const { return Var.getName(); }
94  unsigned getTag()                  const { return Var.getTag(); }
95  bool variableHasComplexAddress()   const {
96    assert(Var.Verify() && "Invalid complex DbgVariable!");
97    return Var.hasComplexAddress();
98  }
99  bool isBlockByrefVariable()        const {
100    assert(Var.Verify() && "Invalid complex DbgVariable!");
101    return Var.isBlockByrefVariable();
102  }
103  unsigned getNumAddrElements()      const {
104    assert(Var.Verify() && "Invalid complex DbgVariable!");
105    return Var.getNumAddrElements();
106  }
107  uint64_t getAddrElement(unsigned i) const {
108    return Var.getAddrElement(i);
109  }
110  DIType getType()               const {
111    DIType Ty = Var.getType();
112    // FIXME: isBlockByrefVariable should be reformulated in terms of complex
113    // addresses instead.
114    if (Var.isBlockByrefVariable()) {
115      /* Byref variables, in Blocks, are declared by the programmer as
116         "SomeType VarName;", but the compiler creates a
117         __Block_byref_x_VarName struct, and gives the variable VarName
118         either the struct, or a pointer to the struct, as its type.  This
119         is necessary for various behind-the-scenes things the compiler
120         needs to do with by-reference variables in blocks.
121
122         However, as far as the original *programmer* is concerned, the
123         variable should still have type 'SomeType', as originally declared.
124
125         The following function dives into the __Block_byref_x_VarName
126         struct to find the original type of the variable.  This will be
127         passed back to the code generating the type for the Debug
128         Information Entry for the variable 'VarName'.  'VarName' will then
129         have the original type 'SomeType' in its debug information.
130
131         The original type 'SomeType' will be the type of the field named
132         'VarName' inside the __Block_byref_x_VarName struct.
133
134         NOTE: In order for this to not completely fail on the debugger
135         side, the Debug Information Entry for the variable VarName needs to
136         have a DW_AT_location that tells the debugger how to unwind through
137         the pointers and __Block_byref_x_VarName struct to find the actual
138         value of the variable.  The function addBlockByrefType does this.  */
139      DIType subType = Ty;
140      unsigned tag = Ty.getTag();
141
142      if (tag == dwarf::DW_TAG_pointer_type) {
143        DIDerivedType DTy = DIDerivedType(Ty);
144        subType = DTy.getTypeDerivedFrom();
145      }
146
147      DICompositeType blockStruct = DICompositeType(subType);
148      DIArray Elements = blockStruct.getTypeArray();
149
150      for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
151        DIDescriptor Element = Elements.getElement(i);
152        DIDerivedType DT = DIDerivedType(Element);
153        if (getName() == DT.getName())
154          return (DT.getTypeDerivedFrom());
155      }
156      return Ty;
157    }
158    return Ty;
159  }
160};
161
162//===----------------------------------------------------------------------===//
163/// DbgRange - This is used to track range of instructions with identical
164/// debug info scope.
165///
166typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
167
168//===----------------------------------------------------------------------===//
169/// DbgScope - This class is used to track scope information.
170///
171class DbgScope {
172  DbgScope *Parent;                   // Parent to this scope.
173  DIDescriptor Desc;                  // Debug info descriptor for scope.
174  // Location at which this scope is inlined.
175  AssertingVH<const MDNode> InlinedAtLocation;
176  bool AbstractScope;                 // Abstract Scope
177  const MachineInstr *LastInsn;       // Last instruction of this scope.
178  const MachineInstr *FirstInsn;      // First instruction of this scope.
179  unsigned DFSIn, DFSOut;
180  // Scopes defined in scope.  Contents not owned.
181  SmallVector<DbgScope *, 4> Scopes;
182  // Variables declared in scope.  Contents owned.
183  SmallVector<DbgVariable *, 8> Variables;
184  SmallVector<DbgRange, 4> Ranges;
185  // Private state for dump()
186  mutable unsigned IndentLevel;
187public:
188  DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
189    : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
190      LastInsn(0), FirstInsn(0),
191      DFSIn(0), DFSOut(0), IndentLevel(0) {}
192  virtual ~DbgScope();
193
194  // Accessors.
195  DbgScope *getParent()          const { return Parent; }
196  void setParent(DbgScope *P)          { Parent = P; }
197  DIDescriptor getDesc()         const { return Desc; }
198  const MDNode *getInlinedAt()         const { return InlinedAtLocation; }
199  const MDNode *getScopeNode()         const { return Desc; }
200  const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
201  const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
202  const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
203
204  /// openInsnRange - This scope covers instruction range starting from MI.
205  void openInsnRange(const MachineInstr *MI) {
206    if (!FirstInsn)
207      FirstInsn = MI;
208
209    if (Parent)
210      Parent->openInsnRange(MI);
211  }
212
213  /// extendInsnRange - Extend the current instruction range covered by
214  /// this scope.
215  void extendInsnRange(const MachineInstr *MI) {
216    assert (FirstInsn && "MI Range is not open!");
217    LastInsn = MI;
218    if (Parent)
219      Parent->extendInsnRange(MI);
220  }
221
222  /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
223  /// until now. This is used when a new scope is encountered while walking
224  /// machine instructions.
225  void closeInsnRange(DbgScope *NewScope = NULL) {
226    assert (LastInsn && "Last insn missing!");
227    Ranges.push_back(DbgRange(FirstInsn, LastInsn));
228    FirstInsn = NULL;
229    LastInsn = NULL;
230    // If Parent dominates NewScope then do not close Parent's instruction
231    // range.
232    if (Parent && (!NewScope || !Parent->dominates(NewScope)))
233      Parent->closeInsnRange(NewScope);
234  }
235
236  void setAbstractScope() { AbstractScope = true; }
237  bool isAbstractScope() const { return AbstractScope; }
238
239  // Depth First Search support to walk and mainpluate DbgScope hierarchy.
240  unsigned getDFSOut() const { return DFSOut; }
241  void setDFSOut(unsigned O) { DFSOut = O; }
242  unsigned getDFSIn() const  { return DFSIn; }
243  void setDFSIn(unsigned I)  { DFSIn = I; }
244  bool dominates(const DbgScope *S) {
245    if (S == this)
246      return true;
247    if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
248      return true;
249    return false;
250  }
251
252  /// addScope - Add a scope to the scope.
253  ///
254  void addScope(DbgScope *S) { Scopes.push_back(S); }
255
256  /// addVariable - Add a variable to the scope.
257  ///
258  void addVariable(DbgVariable *V) { Variables.push_back(V); }
259
260#ifndef NDEBUG
261  void dump() const;
262#endif
263};
264
265} // end llvm namespace
266
267#ifndef NDEBUG
268void DbgScope::dump() const {
269  raw_ostream &err = dbgs();
270  err.indent(IndentLevel);
271  const MDNode *N = Desc;
272  N->dump();
273  if (AbstractScope)
274    err << "Abstract Scope\n";
275
276  IndentLevel += 2;
277  if (!Scopes.empty())
278    err << "Children ...\n";
279  for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
280    if (Scopes[i] != this)
281      Scopes[i]->dump();
282
283  IndentLevel -= 2;
284}
285#endif
286
287DbgScope::~DbgScope() {
288  for (unsigned j = 0, M = Variables.size(); j < M; ++j)
289    delete Variables[j];
290}
291
292DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
293  : Asm(A), MMI(Asm->MMI), FirstCU(0),
294    AbbreviationsSet(InitAbbreviationsSetSize),
295    CurrentFnDbgScope(0), PrevLabel(NULL) {
296  NextStringPoolNumber = 0;
297
298  DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
299  DwarfStrSectionSym = TextSectionSym = 0;
300  DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
301  FunctionBeginSym = FunctionEndSym = 0;
302  DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
303  {
304    NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
305    beginModule(M);
306  }
307}
308DwarfDebug::~DwarfDebug() {
309  for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
310    DIEBlocks[j]->~DIEBlock();
311}
312
313MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
314  std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
315  if (Entry.first) return Entry.first;
316
317  Entry.second = NextStringPoolNumber++;
318  return Entry.first = Asm->GetTempSymbol("string", Entry.second);
319}
320
321
322/// assignAbbrevNumber - Define a unique number for the abbreviation.
323///
324void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
325  // Profile the node so that we can make it unique.
326  FoldingSetNodeID ID;
327  Abbrev.Profile(ID);
328
329  // Check the set for priors.
330  DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
331
332  // If it's newly added.
333  if (InSet == &Abbrev) {
334    // Add to abbreviation list.
335    Abbreviations.push_back(&Abbrev);
336
337    // Assign the vector position + 1 as its number.
338    Abbrev.setNumber(Abbreviations.size());
339  } else {
340    // Assign existing abbreviation number.
341    Abbrev.setNumber(InSet->getNumber());
342  }
343}
344
345/// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
346/// information entry.
347DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
348  DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
349  return Value;
350}
351
352/// addUInt - Add an unsigned integer attribute data and value.
353///
354void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
355                         unsigned Form, uint64_t Integer) {
356  if (!Form) Form = DIEInteger::BestForm(false, Integer);
357  DIEValue *Value = Integer == 1 ?
358    DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
359  Die->addValue(Attribute, Form, Value);
360}
361
362/// addSInt - Add an signed integer attribute data and value.
363///
364void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
365                         unsigned Form, int64_t Integer) {
366  if (!Form) Form = DIEInteger::BestForm(true, Integer);
367  DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
368  Die->addValue(Attribute, Form, Value);
369}
370
371/// addString - Add a string attribute data and value. DIEString only
372/// keeps string reference.
373void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
374                           StringRef String) {
375  DIEValue *Value = new (DIEValueAllocator) DIEString(String);
376  Die->addValue(Attribute, Form, Value);
377}
378
379/// addLabel - Add a Dwarf label attribute data and value.
380///
381void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
382                          const MCSymbol *Label) {
383  DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
384  Die->addValue(Attribute, Form, Value);
385}
386
387/// addDelta - Add a label delta attribute data and value.
388///
389void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
390                          const MCSymbol *Hi, const MCSymbol *Lo) {
391  DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
392  Die->addValue(Attribute, Form, Value);
393}
394
395/// addDIEEntry - Add a DIE attribute data and value.
396///
397void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
398                             DIE *Entry) {
399  Die->addValue(Attribute, Form, createDIEEntry(Entry));
400}
401
402
403/// addBlock - Add block data.
404///
405void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
406                          DIEBlock *Block) {
407  Block->ComputeSize(Asm);
408  DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
409  Die->addValue(Attribute, Block->BestForm(), Block);
410}
411
412/// addSourceLine - Add location information to specified debug information
413/// entry.
414void DwarfDebug::addSourceLine(DIE *Die, DIVariable V) {
415  // Verify variable.
416  if (!V.Verify())
417    return;
418
419  unsigned Line = V.getLineNumber();
420  if (Line == 0)
421    return;
422  unsigned FileID = GetOrCreateSourceID(V.getContext().getFilename(),
423                                        V.getContext().getDirectory());
424  assert(FileID && "Invalid file id");
425  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
426  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
427}
428
429/// addSourceLine - Add location information to specified debug information
430/// entry.
431void DwarfDebug::addSourceLine(DIE *Die, DIGlobalVariable G) {
432  // Verify global variable.
433  if (!G.Verify())
434    return;
435
436  unsigned Line = G.getLineNumber();
437  if (Line == 0)
438    return;
439  unsigned FileID = GetOrCreateSourceID(G.getContext().getFilename(),
440                                        G.getContext().getDirectory());
441  assert(FileID && "Invalid file id");
442  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
443  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
444}
445
446/// addSourceLine - Add location information to specified debug information
447/// entry.
448void DwarfDebug::addSourceLine(DIE *Die, DISubprogram SP) {
449  // Verify subprogram.
450  if (!SP.Verify())
451    return;
452  // If the line number is 0, don't add it.
453  if (SP.getLineNumber() == 0)
454    return;
455
456  unsigned Line = SP.getLineNumber();
457  if (!SP.getContext().Verify())
458    return;
459  unsigned FileID = GetOrCreateSourceID(SP.getFilename(), SP.getDirectory());
460  assert(FileID && "Invalid file id");
461  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
462  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
463}
464
465/// addSourceLine - Add location information to specified debug information
466/// entry.
467void DwarfDebug::addSourceLine(DIE *Die, DIType Ty) {
468  // Verify type.
469  if (!Ty.Verify())
470    return;
471
472  unsigned Line = Ty.getLineNumber();
473  if (Line == 0 || !Ty.getContext().Verify())
474    return;
475  unsigned FileID = GetOrCreateSourceID(Ty.getFilename(), Ty.getDirectory());
476  assert(FileID && "Invalid file id");
477  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
478  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
479}
480
481/// addSourceLine - Add location information to specified debug information
482/// entry.
483void DwarfDebug::addSourceLine(DIE *Die, DINameSpace NS) {
484  // Verify namespace.
485  if (!NS.Verify())
486    return;
487
488  unsigned Line = NS.getLineNumber();
489  if (Line == 0)
490    return;
491  StringRef FN = NS.getFilename();
492
493  unsigned FileID = GetOrCreateSourceID(FN, NS.getDirectory());
494  assert(FileID && "Invalid file id");
495  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
496  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
497}
498
499/// addVariableAddress - Add DW_AT_location attribute for a DbgVariable based
500/// on provided frame index.
501void DwarfDebug::addVariableAddress(DbgVariable *&DV, DIE *Die, int64_t FI) {
502  MachineLocation Location;
503  unsigned FrameReg;
504  const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
505  int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
506  Location.set(FrameReg, Offset);
507
508  if (DV->variableHasComplexAddress())
509    addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
510  else if (DV->isBlockByrefVariable())
511    addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
512  else
513    addAddress(Die, dwarf::DW_AT_location, Location);
514}
515
516/// addComplexAddress - Start with the address based on the location provided,
517/// and generate the DWARF information necessary to find the actual variable
518/// given the extra address information encoded in the DIVariable, starting from
519/// the starting location.  Add the DWARF information to the die.
520///
521void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
522                                   unsigned Attribute,
523                                   const MachineLocation &Location) {
524  DIType Ty = DV->getType();
525
526  // Decode the original location, and use that as the start of the byref
527  // variable's location.
528  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
529  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
530  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
531
532  if (Location.isReg()) {
533    if (Reg < 32) {
534      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
535    } else {
536      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
537      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
538    }
539  } else {
540    if (Reg < 32)
541      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
542    else {
543      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
544      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
545    }
546
547    addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
548  }
549
550  for (unsigned i = 0, N = DV->getNumAddrElements(); i < N; ++i) {
551    uint64_t Element = DV->getAddrElement(i);
552
553    if (Element == DIBuilder::OpPlus) {
554      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
555      addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
556    } else if (Element == DIBuilder::OpDeref) {
557      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
558    } else llvm_unreachable("unknown DIBuilder Opcode");
559  }
560
561  // Now attach the location information to the DIE.
562  addBlock(Die, Attribute, 0, Block);
563}
564
565/* Byref variables, in Blocks, are declared by the programmer as "SomeType
566   VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
567   gives the variable VarName either the struct, or a pointer to the struct, as
568   its type.  This is necessary for various behind-the-scenes things the
569   compiler needs to do with by-reference variables in Blocks.
570
571   However, as far as the original *programmer* is concerned, the variable
572   should still have type 'SomeType', as originally declared.
573
574   The function getBlockByrefType dives into the __Block_byref_x_VarName
575   struct to find the original type of the variable, which is then assigned to
576   the variable's Debug Information Entry as its real type.  So far, so good.
577   However now the debugger will expect the variable VarName to have the type
578   SomeType.  So we need the location attribute for the variable to be an
579   expression that explains to the debugger how to navigate through the
580   pointers and struct to find the actual variable of type SomeType.
581
582   The following function does just that.  We start by getting
583   the "normal" location for the variable. This will be the location
584   of either the struct __Block_byref_x_VarName or the pointer to the
585   struct __Block_byref_x_VarName.
586
587   The struct will look something like:
588
589   struct __Block_byref_x_VarName {
590     ... <various fields>
591     struct __Block_byref_x_VarName *forwarding;
592     ... <various other fields>
593     SomeType VarName;
594     ... <maybe more fields>
595   };
596
597   If we are given the struct directly (as our starting point) we
598   need to tell the debugger to:
599
600   1).  Add the offset of the forwarding field.
601
602   2).  Follow that pointer to get the real __Block_byref_x_VarName
603   struct to use (the real one may have been copied onto the heap).
604
605   3).  Add the offset for the field VarName, to find the actual variable.
606
607   If we started with a pointer to the struct, then we need to
608   dereference that pointer first, before the other steps.
609   Translating this into DWARF ops, we will need to append the following
610   to the current location description for the variable:
611
612   DW_OP_deref                    -- optional, if we start with a pointer
613   DW_OP_plus_uconst <forward_fld_offset>
614   DW_OP_deref
615   DW_OP_plus_uconst <varName_fld_offset>
616
617   That is what this function does.  */
618
619/// addBlockByrefAddress - Start with the address based on the location
620/// provided, and generate the DWARF information necessary to find the
621/// actual Block variable (navigating the Block struct) based on the
622/// starting location.  Add the DWARF information to the die.  For
623/// more information, read large comment just above here.
624///
625void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
626                                      unsigned Attribute,
627                                      const MachineLocation &Location) {
628  DIType Ty = DV->getType();
629  DIType TmpTy = Ty;
630  unsigned Tag = Ty.getTag();
631  bool isPointer = false;
632
633  StringRef varName = DV->getName();
634
635  if (Tag == dwarf::DW_TAG_pointer_type) {
636    DIDerivedType DTy = DIDerivedType(Ty);
637    TmpTy = DTy.getTypeDerivedFrom();
638    isPointer = true;
639  }
640
641  DICompositeType blockStruct = DICompositeType(TmpTy);
642
643  // Find the __forwarding field and the variable field in the __Block_byref
644  // struct.
645  DIArray Fields = blockStruct.getTypeArray();
646  DIDescriptor varField = DIDescriptor();
647  DIDescriptor forwardingField = DIDescriptor();
648
649  for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
650    DIDescriptor Element = Fields.getElement(i);
651    DIDerivedType DT = DIDerivedType(Element);
652    StringRef fieldName = DT.getName();
653    if (fieldName == "__forwarding")
654      forwardingField = Element;
655    else if (fieldName == varName)
656      varField = Element;
657  }
658
659  // Get the offsets for the forwarding field and the variable field.
660  unsigned forwardingFieldOffset =
661    DIDerivedType(forwardingField).getOffsetInBits() >> 3;
662  unsigned varFieldOffset =
663    DIDerivedType(varField).getOffsetInBits() >> 3;
664
665  // Decode the original location, and use that as the start of the byref
666  // variable's location.
667  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
668  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
669  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
670
671  if (Location.isReg()) {
672    if (Reg < 32)
673      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
674    else {
675      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
676      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
677    }
678  } else {
679    if (Reg < 32)
680      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
681    else {
682      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
683      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
684    }
685
686    addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
687  }
688
689  // If we started with a pointer to the __Block_byref... struct, then
690  // the first thing we need to do is dereference the pointer (DW_OP_deref).
691  if (isPointer)
692    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
693
694  // Next add the offset for the '__forwarding' field:
695  // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
696  // adding the offset if it's 0.
697  if (forwardingFieldOffset > 0) {
698    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
699    addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
700  }
701
702  // Now dereference the __forwarding field to get to the real __Block_byref
703  // struct:  DW_OP_deref.
704  addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
705
706  // Now that we've got the real __Block_byref... struct, add the offset
707  // for the variable's field to get to the location of the actual variable:
708  // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
709  if (varFieldOffset > 0) {
710    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
711    addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
712  }
713
714  // Now attach the location information to the DIE.
715  addBlock(Die, Attribute, 0, Block);
716}
717
718/// addAddress - Add an address attribute to a die based on the location
719/// provided.
720void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
721                            const MachineLocation &Location) {
722  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
723  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
724  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
725
726  if (RI->getFrameRegister(*Asm->MF) == Location.getReg()
727      && Location.getOffset()) {
728    // If variable offset is based in frame register then use fbreg.
729    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
730    addSInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
731    addBlock(Die, Attribute, 0, Block);
732    return;
733  }
734
735  if (Location.isReg()) {
736    if (Reg < 32) {
737      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
738    } else {
739      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
740      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
741    }
742  } else {
743    if (Reg < 32) {
744      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
745    } else {
746      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
747      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
748    }
749
750    addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
751  }
752
753  addBlock(Die, Attribute, 0, Block);
754}
755
756/// addRegisterAddress - Add register location entry in variable DIE.
757bool DwarfDebug::addRegisterAddress(DIE *Die, const MachineOperand &MO) {
758  assert (MO.isReg() && "Invalid machine operand!");
759  if (!MO.getReg())
760    return false;
761  MachineLocation Location;
762  Location.set(MO.getReg());
763  addAddress(Die, dwarf::DW_AT_location, Location);
764  return true;
765}
766
767/// addConstantValue - Add constant value entry in variable DIE.
768bool DwarfDebug::addConstantValue(DIE *Die, const MachineOperand &MO) {
769  assert (MO.isImm() && "Invalid machine operand!");
770  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
771  unsigned Imm = MO.getImm();
772  addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
773  addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
774  return true;
775}
776
777/// addConstantFPValue - Add constant value entry in variable DIE.
778bool DwarfDebug::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
779  assert (MO.isFPImm() && "Invalid machine operand!");
780  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
781  APFloat FPImm = MO.getFPImm()->getValueAPF();
782
783  // Get the raw data form of the floating point.
784  const APInt FltVal = FPImm.bitcastToAPInt();
785  const char *FltPtr = (const char*)FltVal.getRawData();
786
787  int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
788  bool LittleEndian = Asm->getTargetData().isLittleEndian();
789  int Incr = (LittleEndian ? 1 : -1);
790  int Start = (LittleEndian ? 0 : NumBytes - 1);
791  int Stop = (LittleEndian ? NumBytes : -1);
792
793  // Output the constant to DWARF one byte at a time.
794  for (; Start != Stop; Start += Incr)
795    addUInt(Block, 0, dwarf::DW_FORM_data1,
796            (unsigned char)0xFF & FltPtr[Start]);
797
798  addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
799  return true;
800}
801
802/// addConstantValue - Add constant value entry in variable DIE.
803bool DwarfDebug::addConstantValue(DIE *Die, ConstantInt *CI,
804                                  bool Unsigned) {
805  if (CI->getBitWidth() <= 64) {
806    if (Unsigned)
807      addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
808              CI->getZExtValue());
809    else
810      addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
811              CI->getSExtValue());
812    return true;
813  }
814
815  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
816
817  // Get the raw data form of the large APInt.
818  const APInt Val = CI->getValue();
819  const char *Ptr = (const char*)Val.getRawData();
820
821  int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
822  bool LittleEndian = Asm->getTargetData().isLittleEndian();
823  int Incr = (LittleEndian ? 1 : -1);
824  int Start = (LittleEndian ? 0 : NumBytes - 1);
825  int Stop = (LittleEndian ? NumBytes : -1);
826
827  // Output the constant to DWARF one byte at a time.
828  for (; Start != Stop; Start += Incr)
829    addUInt(Block, 0, dwarf::DW_FORM_data1,
830            (unsigned char)0xFF & Ptr[Start]);
831
832  addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
833  return true;
834}
835
836/// addTemplateParams - Add template parameters in buffer.
837void DwarfDebug::addTemplateParams(DIE &Buffer, DIArray TParams) {
838  // Add template parameters.
839  for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
840    DIDescriptor Element = TParams.getElement(i);
841    if (Element.isTemplateTypeParameter())
842      Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
843                        DITemplateTypeParameter(Element)));
844    else if (Element.isTemplateValueParameter())
845      Buffer.addChild(getOrCreateTemplateValueParameterDIE(
846                        DITemplateValueParameter(Element)));
847  }
848
849}
850/// addToContextOwner - Add Die into the list of its context owner's children.
851void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
852  if (Context.isType()) {
853    DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
854    ContextDIE->addChild(Die);
855  } else if (Context.isNameSpace()) {
856    DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
857    ContextDIE->addChild(Die);
858  } else if (Context.isSubprogram()) {
859    DIE *ContextDIE = createSubprogramDIE(DISubprogram(Context));
860    ContextDIE->addChild(Die);
861  } else if (DIE *ContextDIE = getCompileUnit(Context)->getDIE(Context))
862    ContextDIE->addChild(Die);
863  else
864    getCompileUnit(Context)->addDie(Die);
865}
866
867/// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
868/// given DIType.
869DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
870  CompileUnit *TypeCU = getCompileUnit(Ty);
871  DIE *TyDIE = TypeCU->getDIE(Ty);
872  if (TyDIE)
873    return TyDIE;
874
875  // Create new type.
876  TyDIE = new DIE(dwarf::DW_TAG_base_type);
877  TypeCU->insertDIE(Ty, TyDIE);
878  if (Ty.isBasicType())
879    constructTypeDIE(*TyDIE, DIBasicType(Ty));
880  else if (Ty.isCompositeType())
881    constructTypeDIE(*TyDIE, DICompositeType(Ty));
882  else {
883    assert(Ty.isDerivedType() && "Unknown kind of DIType");
884    constructTypeDIE(*TyDIE, DIDerivedType(Ty));
885  }
886
887  addToContextOwner(TyDIE, Ty.getContext());
888  return TyDIE;
889}
890
891/// addType - Add a new type attribute to the specified entity.
892void DwarfDebug::addType(DIE *Entity, DIType Ty) {
893  if (!Ty.Verify())
894    return;
895
896  // Check for pre-existence.
897  CompileUnit *TypeCU = getCompileUnit(Ty);
898  DIEEntry *Entry = TypeCU->getDIEEntry(Ty);
899  // If it exists then use the existing value.
900  if (Entry) {
901    Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
902    return;
903  }
904
905  // Construct type.
906  DIE *Buffer = getOrCreateTypeDIE(Ty);
907
908  // Set up proxy.
909  Entry = createDIEEntry(Buffer);
910  TypeCU->insertDIEEntry(Ty, Entry);
911
912  Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
913}
914
915/// constructTypeDIE - Construct basic type die from DIBasicType.
916void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
917  // Get core information.
918  StringRef Name = BTy.getName();
919  Buffer.setTag(dwarf::DW_TAG_base_type);
920  addUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
921          BTy.getEncoding());
922
923  // Add name if not anonymous or intermediate type.
924  if (!Name.empty())
925    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
926  uint64_t Size = BTy.getSizeInBits() >> 3;
927  addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
928}
929
930/// constructTypeDIE - Construct derived type die from DIDerivedType.
931void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
932  // Get core information.
933  StringRef Name = DTy.getName();
934  uint64_t Size = DTy.getSizeInBits() >> 3;
935  unsigned Tag = DTy.getTag();
936
937  // FIXME - Workaround for templates.
938  if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
939
940  Buffer.setTag(Tag);
941
942  // Map to main type, void will not have a type.
943  DIType FromTy = DTy.getTypeDerivedFrom();
944  addType(&Buffer, FromTy);
945
946  // Add name if not anonymous or intermediate type.
947  if (!Name.empty())
948    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
949
950  // Add size if non-zero (derived types might be zero-sized.)
951  if (Size)
952    addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
953
954  // Add source line info if available and TyDesc is not a forward declaration.
955  if (!DTy.isForwardDecl())
956    addSourceLine(&Buffer, DTy);
957}
958
959/// constructTypeDIE - Construct type DIE from DICompositeType.
960void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
961  // Get core information.
962  StringRef Name = CTy.getName();
963
964  uint64_t Size = CTy.getSizeInBits() >> 3;
965  unsigned Tag = CTy.getTag();
966  Buffer.setTag(Tag);
967
968  switch (Tag) {
969  case dwarf::DW_TAG_vector_type:
970  case dwarf::DW_TAG_array_type:
971    constructArrayTypeDIE(Buffer, &CTy);
972    break;
973  case dwarf::DW_TAG_enumeration_type: {
974    DIArray Elements = CTy.getTypeArray();
975
976    // Add enumerators to enumeration type.
977    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
978      DIE *ElemDie = NULL;
979      DIDescriptor Enum(Elements.getElement(i));
980      if (Enum.isEnumerator()) {
981        ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
982        Buffer.addChild(ElemDie);
983      }
984    }
985  }
986    break;
987  case dwarf::DW_TAG_subroutine_type: {
988    // Add return type.
989    DIArray Elements = CTy.getTypeArray();
990    DIDescriptor RTy = Elements.getElement(0);
991    addType(&Buffer, DIType(RTy));
992
993    bool isPrototyped = true;
994    // Add arguments.
995    for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
996      DIDescriptor Ty = Elements.getElement(i);
997      if (Ty.isUnspecifiedParameter()) {
998        DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
999        Buffer.addChild(Arg);
1000        isPrototyped = false;
1001      } else {
1002        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1003        addType(Arg, DIType(Ty));
1004        Buffer.addChild(Arg);
1005      }
1006    }
1007    // Add prototype flag.
1008    if (isPrototyped)
1009      addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1010  }
1011    break;
1012  case dwarf::DW_TAG_structure_type:
1013  case dwarf::DW_TAG_union_type:
1014  case dwarf::DW_TAG_class_type: {
1015    // Add elements to structure type.
1016    DIArray Elements = CTy.getTypeArray();
1017
1018    // A forward struct declared type may not have elements available.
1019    unsigned N = Elements.getNumElements();
1020    if (N == 0)
1021      break;
1022
1023    // Add elements to structure type.
1024    for (unsigned i = 0; i < N; ++i) {
1025      DIDescriptor Element = Elements.getElement(i);
1026      DIE *ElemDie = NULL;
1027      if (Element.isSubprogram()) {
1028        DISubprogram SP(Element);
1029        ElemDie = createSubprogramDIE(DISubprogram(Element));
1030        if (SP.isProtected())
1031          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1032                  dwarf::DW_ACCESS_protected);
1033        else if (SP.isPrivate())
1034          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1035                  dwarf::DW_ACCESS_private);
1036        else
1037          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1038            dwarf::DW_ACCESS_public);
1039        if (SP.isExplicit())
1040          addUInt(ElemDie, dwarf::DW_AT_explicit, dwarf::DW_FORM_flag, 1);
1041      }
1042      else if (Element.isVariable()) {
1043        DIVariable DV(Element);
1044        ElemDie = new DIE(dwarf::DW_TAG_variable);
1045        addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1046                  DV.getName());
1047        addType(ElemDie, DV.getType());
1048        addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1049        addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1050        addSourceLine(ElemDie, DV);
1051      } else if (Element.isDerivedType())
1052        ElemDie = createMemberDIE(DIDerivedType(Element));
1053      else
1054        continue;
1055      Buffer.addChild(ElemDie);
1056    }
1057
1058    if (CTy.isAppleBlockExtension())
1059      addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1060
1061    unsigned RLang = CTy.getRunTimeLang();
1062    if (RLang)
1063      addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1064              dwarf::DW_FORM_data1, RLang);
1065
1066    DICompositeType ContainingType = CTy.getContainingType();
1067    if (DIDescriptor(ContainingType).isCompositeType())
1068      addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1069                  getOrCreateTypeDIE(DIType(ContainingType)));
1070    else {
1071      DIDescriptor Context = CTy.getContext();
1072      addToContextOwner(&Buffer, Context);
1073    }
1074
1075    if (Tag == dwarf::DW_TAG_class_type)
1076      addTemplateParams(Buffer, CTy.getTemplateParams());
1077
1078    break;
1079  }
1080  default:
1081    break;
1082  }
1083
1084  // Add name if not anonymous or intermediate type.
1085  if (!Name.empty())
1086    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1087
1088  if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
1089      || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1090    {
1091    // Add size if non-zero (derived types might be zero-sized.)
1092    if (Size)
1093      addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1094    else {
1095      // Add zero size if it is not a forward declaration.
1096      if (CTy.isForwardDecl())
1097        addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1098      else
1099        addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1100    }
1101
1102    // Add source line info if available.
1103    if (!CTy.isForwardDecl())
1104      addSourceLine(&Buffer, CTy);
1105  }
1106}
1107
1108/// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE
1109/// for the given DITemplateTypeParameter.
1110DIE *
1111DwarfDebug::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
1112  CompileUnit *TypeCU = getCompileUnit(TP);
1113  DIE *ParamDIE = TypeCU->getDIE(TP);
1114  if (ParamDIE)
1115    return ParamDIE;
1116
1117  ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
1118  addType(ParamDIE, TP.getType());
1119  addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TP.getName());
1120  return ParamDIE;
1121}
1122
1123/// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE
1124/// for the given DITemplateValueParameter.
1125DIE *
1126DwarfDebug::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV) {
1127  CompileUnit *TVCU = getCompileUnit(TPV);
1128  DIE *ParamDIE = TVCU->getDIE(TPV);
1129  if (ParamDIE)
1130    return ParamDIE;
1131
1132  ParamDIE = new DIE(dwarf::DW_TAG_template_value_parameter);
1133  addType(ParamDIE, TPV.getType());
1134  if (!TPV.getName().empty())
1135    addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TPV.getName());
1136  addUInt(ParamDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
1137          TPV.getValue());
1138  return ParamDIE;
1139}
1140
1141/// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1142void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1143  DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1144  addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1145  int64_t L = SR.getLo();
1146  int64_t H = SR.getHi();
1147
1148  // The L value defines the lower bounds which is typically zero for C/C++. The
1149  // H value is the upper bounds.  Values are 64 bit.  H - L + 1 is the size
1150  // of the array. If L > H then do not emit DW_AT_lower_bound and
1151  // DW_AT_upper_bound attributes. If L is zero and H is also zero then the
1152  // array has one element and in such case do not emit lower bound.
1153
1154  if (L > H) {
1155    Buffer.addChild(DW_Subrange);
1156    return;
1157  }
1158  if (L)
1159    addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1160  addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1161  Buffer.addChild(DW_Subrange);
1162}
1163
1164/// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1165void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1166                                       DICompositeType *CTy) {
1167  Buffer.setTag(dwarf::DW_TAG_array_type);
1168  if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1169    addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1170
1171  // Emit derived type.
1172  addType(&Buffer, CTy->getTypeDerivedFrom());
1173  DIArray Elements = CTy->getTypeArray();
1174
1175  // Get an anonymous type for index type.
1176  CompileUnit *TheCU = getCompileUnit(*CTy);
1177  DIE *IdxTy = TheCU->getIndexTyDie();
1178  if (!IdxTy) {
1179    // Construct an anonymous type for index type.
1180    IdxTy = new DIE(dwarf::DW_TAG_base_type);
1181    addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1182    addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1183            dwarf::DW_ATE_signed);
1184    TheCU->addDie(IdxTy);
1185    TheCU->setIndexTyDie(IdxTy);
1186  }
1187
1188  // Add subranges to array type.
1189  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1190    DIDescriptor Element = Elements.getElement(i);
1191    if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1192      constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1193  }
1194}
1195
1196/// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1197DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1198  DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1199  StringRef Name = ETy.getName();
1200  addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1201  int64_t Value = ETy.getEnumValue();
1202  addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1203  return Enumerator;
1204}
1205
1206/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1207/// printer to not emit usual symbol prefix before the symbol name is used then
1208/// return linkage name after skipping this special LLVM prefix.
1209static StringRef getRealLinkageName(StringRef LinkageName) {
1210  char One = '\1';
1211  if (LinkageName.startswith(StringRef(&One, 1)))
1212    return LinkageName.substr(1);
1213  return LinkageName;
1214}
1215
1216/// createMemberDIE - Create new member DIE.
1217DIE *DwarfDebug::createMemberDIE(DIDerivedType DT) {
1218  DIE *MemberDie = new DIE(DT.getTag());
1219  StringRef Name = DT.getName();
1220  if (!Name.empty())
1221    addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1222
1223  addType(MemberDie, DT.getTypeDerivedFrom());
1224
1225  addSourceLine(MemberDie, DT);
1226
1227  DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1228  addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1229
1230  uint64_t Size = DT.getSizeInBits();
1231  uint64_t FieldSize = DT.getOriginalTypeSize();
1232
1233  if (Size != FieldSize) {
1234    // Handle bitfield.
1235    addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1236    addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1237
1238    uint64_t Offset = DT.getOffsetInBits();
1239    uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1240    uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1241    uint64_t FieldOffset = (HiMark - FieldSize);
1242    Offset -= FieldOffset;
1243
1244    // Maybe we need to work from the other end.
1245    if (Asm->getTargetData().isLittleEndian())
1246      Offset = FieldSize - (Offset + Size);
1247    addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1248
1249    // Here WD_AT_data_member_location points to the anonymous
1250    // field that includes this bit field.
1251    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1252
1253  } else
1254    // This is not a bitfield.
1255    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1256
1257  if (DT.getTag() == dwarf::DW_TAG_inheritance
1258      && DT.isVirtual()) {
1259
1260    // For C++, virtual base classes are not at fixed offset. Use following
1261    // expression to extract appropriate offset from vtable.
1262    // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1263
1264    DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1265    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1266    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1267    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1268    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1269    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1270    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1271    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1272
1273    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1274             VBaseLocationDie);
1275  } else
1276    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1277
1278  if (DT.isProtected())
1279    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1280            dwarf::DW_ACCESS_protected);
1281  else if (DT.isPrivate())
1282    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1283            dwarf::DW_ACCESS_private);
1284  // Otherwise C++ member and base classes are considered public.
1285  else if (DT.getCompileUnit().getLanguage() == dwarf::DW_LANG_C_plus_plus)
1286    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1287            dwarf::DW_ACCESS_public);
1288  if (DT.isVirtual())
1289    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1290            dwarf::DW_VIRTUALITY_virtual);
1291  return MemberDie;
1292}
1293
1294/// createSubprogramDIE - Create new DIE using SP.
1295DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
1296  CompileUnit *SPCU = getCompileUnit(SP);
1297  DIE *SPDie = SPCU->getDIE(SP);
1298  if (SPDie)
1299    return SPDie;
1300
1301  SPDie = new DIE(dwarf::DW_TAG_subprogram);
1302  // Constructors and operators for anonymous aggregates do not have names.
1303  if (!SP.getName().empty())
1304    addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1305
1306  StringRef LinkageName = SP.getLinkageName();
1307  if (!LinkageName.empty())
1308    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1309              getRealLinkageName(LinkageName));
1310
1311  addSourceLine(SPDie, SP);
1312
1313  if (SP.isPrototyped())
1314    addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1315
1316  // Add Return Type.
1317  DICompositeType SPTy = SP.getType();
1318  DIArray Args = SPTy.getTypeArray();
1319  unsigned SPTag = SPTy.getTag();
1320
1321  if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1322    addType(SPDie, SPTy);
1323  else
1324    addType(SPDie, DIType(Args.getElement(0)));
1325
1326  unsigned VK = SP.getVirtuality();
1327  if (VK) {
1328    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1329    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1330    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1331    addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1332    addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1333    ContainingTypeMap.insert(std::make_pair(SPDie,
1334                                            SP.getContainingType()));
1335  }
1336
1337  if (!SP.isDefinition()) {
1338    addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1339
1340    // Add arguments. Do not add arguments for subprogram definition. They will
1341    // be handled while processing variables.
1342    DICompositeType SPTy = SP.getType();
1343    DIArray Args = SPTy.getTypeArray();
1344    unsigned SPTag = SPTy.getTag();
1345
1346    if (SPTag == dwarf::DW_TAG_subroutine_type)
1347      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1348        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1349        DIType ATy = DIType(DIType(Args.getElement(i)));
1350        addType(Arg, ATy);
1351        if (ATy.isArtificial())
1352          addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1353        SPDie->addChild(Arg);
1354      }
1355  }
1356
1357  if (SP.isArtificial())
1358    addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1359
1360  if (!SP.isLocalToUnit())
1361    addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1362
1363  if (SP.isOptimized())
1364    addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1365
1366  if (unsigned isa = Asm->getISAEncoding()) {
1367    addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1368  }
1369
1370  // Add function template parameters.
1371  addTemplateParams(*SPDie, SP.getTemplateParams());
1372
1373  // DW_TAG_inlined_subroutine may refer to this DIE.
1374  SPCU->insertDIE(SP, SPDie);
1375
1376  // Add to context owner.
1377  addToContextOwner(SPDie, SP.getContext());
1378
1379  return SPDie;
1380}
1381
1382DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1383  assert(N && "Invalid Scope encoding!");
1384
1385  DbgScope *AScope = AbstractScopes.lookup(N);
1386  if (AScope)
1387    return AScope;
1388
1389  DbgScope *Parent = NULL;
1390
1391  DIDescriptor Scope(N);
1392  if (Scope.isLexicalBlock()) {
1393    DILexicalBlock DB(N);
1394    DIDescriptor ParentDesc = DB.getContext();
1395    Parent = getOrCreateAbstractScope(ParentDesc);
1396  }
1397
1398  AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1399
1400  if (Parent)
1401    Parent->addScope(AScope);
1402  AScope->setAbstractScope();
1403  AbstractScopes[N] = AScope;
1404  if (DIDescriptor(N).isSubprogram())
1405    AbstractScopesList.push_back(AScope);
1406  return AScope;
1407}
1408
1409/// isSubprogramContext - Return true if Context is either a subprogram
1410/// or another context nested inside a subprogram.
1411static bool isSubprogramContext(const MDNode *Context) {
1412  if (!Context)
1413    return false;
1414  DIDescriptor D(Context);
1415  if (D.isSubprogram())
1416    return true;
1417  if (D.isType())
1418    return isSubprogramContext(DIType(Context).getContext());
1419  return false;
1420}
1421
1422/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1423/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1424/// If there are global variables in this scope then create and insert
1425/// DIEs for these variables.
1426DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1427  CompileUnit *SPCU = getCompileUnit(SPNode);
1428  DIE *SPDie = SPCU->getDIE(SPNode);
1429
1430  assert(SPDie && "Unable to find subprogram DIE!");
1431  DISubprogram SP(SPNode);
1432
1433  // There is not any need to generate specification DIE for a function
1434  // defined at compile unit level. If a function is defined inside another
1435  // function then gdb prefers the definition at top level and but does not
1436  // expect specification DIE in parent function. So avoid creating
1437  // specification DIE for a function defined inside a function.
1438  if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1439      !SP.getContext().isFile() &&
1440      !isSubprogramContext(SP.getContext())) {
1441    addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1442
1443    // Add arguments.
1444    DICompositeType SPTy = SP.getType();
1445    DIArray Args = SPTy.getTypeArray();
1446    unsigned SPTag = SPTy.getTag();
1447    if (SPTag == dwarf::DW_TAG_subroutine_type)
1448      for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1449        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1450        DIType ATy = DIType(DIType(Args.getElement(i)));
1451        addType(Arg, ATy);
1452        if (ATy.isArtificial())
1453          addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1454        SPDie->addChild(Arg);
1455      }
1456    DIE *SPDeclDie = SPDie;
1457    SPDie = new DIE(dwarf::DW_TAG_subprogram);
1458    addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1459                SPDeclDie);
1460    SPCU->addDie(SPDie);
1461  }
1462
1463  // Pick up abstract subprogram DIE.
1464  if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
1465    SPDie = new DIE(dwarf::DW_TAG_subprogram);
1466    addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
1467                dwarf::DW_FORM_ref4, AbsSPDIE);
1468    SPCU->addDie(SPDie);
1469  }
1470
1471  addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1472           Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1473  addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1474           Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1475  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1476  MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1477  addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1478
1479  return SPDie;
1480}
1481
1482/// constructLexicalScope - Construct new DW_TAG_lexical_block
1483/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1484DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1485
1486  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1487  if (Scope->isAbstractScope())
1488    return ScopeDIE;
1489
1490  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1491  if (Ranges.empty())
1492    return 0;
1493
1494  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1495  if (Ranges.size() > 1) {
1496    // .debug_range section has not been laid out yet. Emit offset in
1497    // .debug_range as a uint, size 4, for now. emitDIE will handle
1498    // DW_AT_ranges appropriately.
1499    addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1500            DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1501    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1502         RE = Ranges.end(); RI != RE; ++RI) {
1503      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
1504      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
1505    }
1506    DebugRangeSymbols.push_back(NULL);
1507    DebugRangeSymbols.push_back(NULL);
1508    return ScopeDIE;
1509  }
1510
1511  const MCSymbol *Start = getLabelBeforeInsn(RI->first);
1512  const MCSymbol *End = getLabelAfterInsn(RI->second);
1513
1514  if (End == 0) return 0;
1515
1516  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1517  assert(End->isDefined() && "Invalid end label for an inlined scope!");
1518
1519  addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1520  addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1521
1522  return ScopeDIE;
1523}
1524
1525/// constructInlinedScopeDIE - This scope represents inlined body of
1526/// a function. Construct DIE to represent this concrete inlined copy
1527/// of the function.
1528DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1529
1530  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1531  assert (Ranges.empty() == false
1532          && "DbgScope does not have instruction markers!");
1533
1534  // FIXME : .debug_inlined section specification does not clearly state how
1535  // to emit inlined scope that is split into multiple instruction ranges.
1536  // For now, use first instruction range and emit low_pc/high_pc pair and
1537  // corresponding .debug_inlined section entry for this pair.
1538  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1539  const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
1540  const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
1541
1542  if (StartLabel == 0 || EndLabel == 0) {
1543    assert (0 && "Unexpected Start and End  labels for a inlined scope!");
1544    return 0;
1545  }
1546  assert(StartLabel->isDefined() &&
1547         "Invalid starting label for an inlined scope!");
1548  assert(EndLabel->isDefined() &&
1549         "Invalid end label for an inlined scope!");
1550
1551  if (!Scope->getScopeNode())
1552    return NULL;
1553  DIScope DS(Scope->getScopeNode());
1554  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1555
1556  DISubprogram InlinedSP = getDISubprogram(DS);
1557  CompileUnit *TheCU = getCompileUnit(InlinedSP);
1558  DIE *OriginDIE = TheCU->getDIE(InlinedSP);
1559  assert(OriginDIE && "Unable to find Origin DIE!");
1560  addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1561              dwarf::DW_FORM_ref4, OriginDIE);
1562
1563  addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1564  addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1565
1566  InlinedSubprogramDIEs.insert(OriginDIE);
1567
1568  // Track the start label for this inlined function.
1569  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1570    I = InlineInfo.find(InlinedSP);
1571
1572  if (I == InlineInfo.end()) {
1573    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1574                                                             ScopeDIE));
1575    InlinedSPNodes.push_back(InlinedSP);
1576  } else
1577    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1578
1579  DILocation DL(Scope->getInlinedAt());
1580  addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
1581  addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1582
1583  return ScopeDIE;
1584}
1585
1586
1587/// constructVariableDIE - Construct a DIE for the given DbgVariable.
1588DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1589  StringRef Name = DV->getName();
1590  if (Name.empty())
1591    return NULL;
1592
1593  // Translate tag to proper Dwarf tag.  The result variable is dropped for
1594  // now.
1595  unsigned Tag;
1596  switch (DV->getTag()) {
1597  case dwarf::DW_TAG_return_variable:
1598    return NULL;
1599  case dwarf::DW_TAG_arg_variable:
1600    Tag = dwarf::DW_TAG_formal_parameter;
1601    break;
1602  case dwarf::DW_TAG_auto_variable:    // fall thru
1603  default:
1604    Tag = dwarf::DW_TAG_variable;
1605    break;
1606  }
1607
1608  // Define variable debug information entry.
1609  DIE *VariableDie = new DIE(Tag);
1610
1611  DIE *AbsDIE = NULL;
1612  DenseMap<const DbgVariable *, const DbgVariable *>::iterator
1613    V2AVI = VarToAbstractVarMap.find(DV);
1614  if (V2AVI != VarToAbstractVarMap.end())
1615    AbsDIE = V2AVI->second->getDIE();
1616
1617  if (AbsDIE)
1618    addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1619                dwarf::DW_FORM_ref4, AbsDIE);
1620  else {
1621    addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1622    addSourceLine(VariableDie, DV->getVariable());
1623
1624    // Add variable type.
1625    addType(VariableDie, DV->getType());
1626  }
1627
1628  if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
1629    addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1630  else if (DIVariable(DV->getVariable()).isArtificial())
1631    addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1632
1633  if (Scope->isAbstractScope()) {
1634    DV->setDIE(VariableDie);
1635    return VariableDie;
1636  }
1637
1638  // Add variable address.
1639
1640  unsigned Offset = DV->getDotDebugLocOffset();
1641  if (Offset != ~0U) {
1642    addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1643             Asm->GetTempSymbol("debug_loc", Offset));
1644    DV->setDIE(VariableDie);
1645    UseDotDebugLocEntry.insert(VariableDie);
1646    return VariableDie;
1647  }
1648
1649  // Check if variable is described by a  DBG_VALUE instruction.
1650  DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
1651    DbgVariableToDbgInstMap.find(DV);
1652  if (DVI != DbgVariableToDbgInstMap.end()) {
1653    const MachineInstr *DVInsn = DVI->second;
1654    bool updated = false;
1655    // FIXME : Handle getNumOperands != 3
1656    if (DVInsn->getNumOperands() == 3) {
1657      if (DVInsn->getOperand(0).isReg()) {
1658        const MachineOperand RegOp = DVInsn->getOperand(0);
1659        const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1660        if (DVInsn->getOperand(1).isImm() &&
1661            TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1662          addVariableAddress(DV, VariableDie, DVInsn->getOperand(1).getImm());
1663          updated = true;
1664        } else
1665          updated = addRegisterAddress(VariableDie, RegOp);
1666      }
1667      else if (DVInsn->getOperand(0).isImm())
1668        updated = addConstantValue(VariableDie, DVInsn->getOperand(0));
1669      else if (DVInsn->getOperand(0).isFPImm())
1670        updated =
1671          addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1672    } else {
1673      MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1674      if (Location.getReg()) {
1675        addAddress(VariableDie, dwarf::DW_AT_location, Location);
1676        updated = true;
1677      }
1678    }
1679    if (!updated) {
1680      // If variableDie is not updated then DBG_VALUE instruction does not
1681      // have valid variable info.
1682      delete VariableDie;
1683      return NULL;
1684    }
1685    DV->setDIE(VariableDie);
1686    return VariableDie;
1687  }
1688
1689  // .. else use frame index, if available.
1690  int FI = 0;
1691  if (findVariableFrameIndex(DV, &FI))
1692    addVariableAddress(DV, VariableDie, FI);
1693
1694  DV->setDIE(VariableDie);
1695  return VariableDie;
1696
1697}
1698
1699void DwarfDebug::addPubTypes(DISubprogram SP) {
1700  DICompositeType SPTy = SP.getType();
1701  unsigned SPTag = SPTy.getTag();
1702  if (SPTag != dwarf::DW_TAG_subroutine_type)
1703    return;
1704
1705  DIArray Args = SPTy.getTypeArray();
1706  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1707    DIType ATy(Args.getElement(i));
1708    if (!ATy.Verify())
1709      continue;
1710    DICompositeType CATy = getDICompositeType(ATy);
1711    if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1712        && !CATy.isForwardDecl()) {
1713      CompileUnit *TheCU = getCompileUnit(CATy);
1714      if (DIEEntry *Entry = TheCU->getDIEEntry(CATy))
1715        TheCU->addGlobalType(CATy.getName(), Entry->getEntry());
1716    }
1717  }
1718}
1719
1720/// constructScopeDIE - Construct a DIE for this scope.
1721DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1722  if (!Scope || !Scope->getScopeNode())
1723    return NULL;
1724
1725  SmallVector <DIE *, 8> Children;
1726
1727  // Collect arguments for current function.
1728  if (Scope == CurrentFnDbgScope)
1729    for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
1730      if (DbgVariable *ArgDV = CurrentFnArguments[i])
1731        if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
1732          Children.push_back(Arg);
1733
1734  // Collect lexical scope childrens first.
1735  const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1736  for (unsigned i = 0, N = Variables.size(); i < N; ++i)
1737    if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
1738      Children.push_back(Variable);
1739  const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1740  for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
1741    if (DIE *Nested = constructScopeDIE(Scopes[j]))
1742      Children.push_back(Nested);
1743  DIScope DS(Scope->getScopeNode());
1744  DIE *ScopeDIE = NULL;
1745  if (Scope->getInlinedAt())
1746    ScopeDIE = constructInlinedScopeDIE(Scope);
1747  else if (DS.isSubprogram()) {
1748    ProcessedSPNodes.insert(DS);
1749    if (Scope->isAbstractScope()) {
1750      ScopeDIE = getCompileUnit(DS)->getDIE(DS);
1751      // Note down abstract DIE.
1752      if (ScopeDIE)
1753        AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
1754    }
1755    else
1756      ScopeDIE = updateSubprogramScopeDIE(DS);
1757  }
1758  else {
1759    // There is no need to emit empty lexical block DIE.
1760    if (Children.empty())
1761      return NULL;
1762    ScopeDIE = constructLexicalScopeDIE(Scope);
1763  }
1764
1765  if (!ScopeDIE) return NULL;
1766
1767  // Add children
1768  for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
1769         E = Children.end(); I != E; ++I)
1770    ScopeDIE->addChild(*I);
1771
1772  if (DS.isSubprogram())
1773    addPubTypes(DISubprogram(DS));
1774
1775 return ScopeDIE;
1776}
1777
1778/// GetOrCreateSourceID - Look up the source id with the given directory and
1779/// source file names. If none currently exists, create a new id and insert it
1780/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1781/// maps as well.
1782
1783unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
1784                                         StringRef DirName) {
1785  // If FE did not provide a file name, then assume stdin.
1786  if (FileName.empty())
1787    return GetOrCreateSourceID("<stdin>", StringRef());
1788
1789  // MCStream expects full path name as filename.
1790  if (!DirName.empty() && !FileName.startswith("/")) {
1791    std::string FullPathName(DirName.data());
1792    if (!DirName.endswith("/"))
1793      FullPathName += "/";
1794    FullPathName += FileName.data();
1795    // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
1796    return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
1797  }
1798
1799  StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
1800  if (Entry.getValue())
1801    return Entry.getValue();
1802
1803  unsigned SrcId = SourceIdMap.size();
1804  Entry.setValue(SrcId);
1805
1806  // Print out a .file directive to specify files for .loc directives.
1807  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
1808
1809  return SrcId;
1810}
1811
1812/// getOrCreateNameSpace - Create a DIE for DINameSpace.
1813DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1814  CompileUnit *TheCU = getCompileUnit(NS);
1815  DIE *NDie = TheCU->getDIE(NS);
1816  if (NDie)
1817    return NDie;
1818  NDie = new DIE(dwarf::DW_TAG_namespace);
1819  TheCU->insertDIE(NS, NDie);
1820  if (!NS.getName().empty())
1821    addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1822  addSourceLine(NDie, NS);
1823  addToContextOwner(NDie, NS.getContext());
1824  return NDie;
1825}
1826
1827/// constructCompileUnit - Create new CompileUnit for the given
1828/// metadata node with tag DW_TAG_compile_unit.
1829void DwarfDebug::constructCompileUnit(const MDNode *N) {
1830  DICompileUnit DIUnit(N);
1831  StringRef FN = DIUnit.getFilename();
1832  StringRef Dir = DIUnit.getDirectory();
1833  unsigned ID = GetOrCreateSourceID(FN, Dir);
1834
1835  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1836  addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1837            DIUnit.getProducer());
1838  addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1839          DIUnit.getLanguage());
1840  addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1841  // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1842  // simplifies debug range entries.
1843  addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
1844  // DW_AT_stmt_list is a offset of line number information for this
1845  // compile unit in debug_line section.
1846  if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
1847    addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
1848             Asm->GetTempSymbol("section_line"));
1849  else
1850    addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1851
1852  if (!Dir.empty())
1853    addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1854  if (DIUnit.isOptimized())
1855    addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1856
1857  StringRef Flags = DIUnit.getFlags();
1858  if (!Flags.empty())
1859    addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1860
1861  unsigned RVer = DIUnit.getRunTimeVersion();
1862  if (RVer)
1863    addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1864            dwarf::DW_FORM_data1, RVer);
1865
1866  CompileUnit *NewCU = new CompileUnit(ID, Die);
1867  if (!FirstCU)
1868    FirstCU = NewCU;
1869  CUMap.insert(std::make_pair(N, NewCU));
1870}
1871
1872/// getCompielUnit - Get CompileUnit DIE.
1873CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
1874  assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
1875  DIDescriptor D(N);
1876  const MDNode *CUNode = NULL;
1877  if (D.isCompileUnit())
1878    CUNode = N;
1879  else if (D.isSubprogram())
1880    CUNode = DISubprogram(N).getCompileUnit();
1881  else if (D.isType())
1882    CUNode = DIType(N).getCompileUnit();
1883  else if (D.isGlobalVariable())
1884    CUNode = DIGlobalVariable(N).getCompileUnit();
1885  else if (D.isVariable())
1886    CUNode = DIVariable(N).getCompileUnit();
1887  else if (D.isNameSpace())
1888    CUNode = DINameSpace(N).getCompileUnit();
1889  else if (D.isFile())
1890    CUNode = DIFile(N).getCompileUnit();
1891  else
1892    return FirstCU;
1893
1894  DenseMap<const MDNode *, CompileUnit *>::const_iterator I
1895    = CUMap.find(CUNode);
1896  if (I == CUMap.end())
1897    return FirstCU;
1898  return I->second;
1899}
1900
1901/// isUnsignedDIType - Return true if type encoding is unsigned.
1902static bool isUnsignedDIType(DIType Ty) {
1903  DIDerivedType DTy(Ty);
1904  if (DTy.Verify())
1905    return isUnsignedDIType(DTy.getTypeDerivedFrom());
1906
1907  DIBasicType BTy(Ty);
1908  if (BTy.Verify()) {
1909    unsigned Encoding = BTy.getEncoding();
1910    if (Encoding == dwarf::DW_ATE_unsigned ||
1911        Encoding == dwarf::DW_ATE_unsigned_char)
1912      return true;
1913  }
1914  return false;
1915}
1916
1917// Return const exprssion if value is a GEP to access merged global
1918// constant. e.g.
1919// i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1920static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1921  const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1922  if (!CE || CE->getNumOperands() != 3 ||
1923      CE->getOpcode() != Instruction::GetElementPtr)
1924    return NULL;
1925
1926  // First operand points to a global value.
1927  if (!isa<GlobalValue>(CE->getOperand(0)))
1928    return NULL;
1929
1930  // Second operand is zero.
1931  const ConstantInt *CI =
1932    dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1933  if (!CI || !CI->isZero())
1934    return NULL;
1935
1936  // Third operand is offset.
1937  if (!isa<ConstantInt>(CE->getOperand(2)))
1938    return NULL;
1939
1940  return CE;
1941}
1942
1943/// constructGlobalVariableDIE - Construct global variable DIE.
1944void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1945  DIGlobalVariable GV(N);
1946
1947  // If debug information is malformed then ignore it.
1948  if (GV.Verify() == false)
1949    return;
1950
1951  // Check for pre-existence.
1952  CompileUnit *TheCU = getCompileUnit(N);
1953  if (TheCU->getDIE(GV))
1954    return;
1955
1956  DIType GTy = GV.getType();
1957  DIE *VariableDIE = new DIE(GV.getTag());
1958
1959  bool isGlobalVariable = GV.getGlobal() != NULL;
1960
1961  // Add name.
1962  addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1963            GV.getDisplayName());
1964  StringRef LinkageName = GV.getLinkageName();
1965  if (!LinkageName.empty() && isGlobalVariable)
1966    addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1967              getRealLinkageName(LinkageName));
1968  // Add type.
1969  addType(VariableDIE, GTy);
1970  if (GTy.isCompositeType() && !GTy.getName().empty()
1971      && !GTy.isForwardDecl()) {
1972    DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1973    assert(Entry && "Missing global type!");
1974    TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1975  }
1976  // Add scoping info.
1977  if (!GV.isLocalToUnit()) {
1978    addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1979    // Expose as global.
1980    TheCU->addGlobal(GV.getName(), VariableDIE);
1981  }
1982  // Add line number info.
1983  addSourceLine(VariableDIE, GV);
1984  // Add to map.
1985  TheCU->insertDIE(N, VariableDIE);
1986  // Add to context owner.
1987  DIDescriptor GVContext = GV.getContext();
1988  addToContextOwner(VariableDIE, GVContext);
1989  // Add location.
1990  if (isGlobalVariable) {
1991    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1992    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1993    addLabel(Block, 0, dwarf::DW_FORM_udata,
1994             Asm->Mang->getSymbol(GV.getGlobal()));
1995    // Do not create specification DIE if context is either compile unit
1996    // or a subprogram.
1997    if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1998        !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1999      // Create specification DIE.
2000      DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
2001      addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
2002                  dwarf::DW_FORM_ref4, VariableDIE);
2003      addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
2004      addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
2005      TheCU->addDie(VariableSpecDIE);
2006    } else {
2007      addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
2008    }
2009  } else if (ConstantInt *CI =
2010             dyn_cast_or_null<ConstantInt>(GV.getConstant()))
2011    addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy));
2012  else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
2013    // GV is a merged global.
2014    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
2015    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
2016    addLabel(Block, 0, dwarf::DW_FORM_udata,
2017             Asm->Mang->getSymbol(cast<GlobalValue>(CE->getOperand(0))));
2018    ConstantInt *CII = cast<ConstantInt>(CE->getOperand(2));
2019    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
2020    addUInt(Block, 0, dwarf::DW_FORM_udata, CII->getZExtValue());
2021    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
2022    addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
2023  }
2024
2025  return;
2026}
2027
2028/// construct SubprogramDIE - Construct subprogram DIE.
2029void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
2030  DISubprogram SP(N);
2031
2032  // Check for pre-existence.
2033  CompileUnit *TheCU = getCompileUnit(N);
2034  if (TheCU->getDIE(N))
2035    return;
2036
2037  if (!SP.isDefinition())
2038    // This is a method declaration which will be handled while constructing
2039    // class type.
2040    return;
2041
2042  DIE *SubprogramDie = createSubprogramDIE(SP);
2043
2044  // Add to map.
2045  TheCU->insertDIE(N, SubprogramDie);
2046
2047  // Add to context owner.
2048  addToContextOwner(SubprogramDie, SP.getContext());
2049
2050  // Expose as global.
2051  TheCU->addGlobal(SP.getName(), SubprogramDie);
2052
2053  return;
2054}
2055
2056/// beginModule - Emit all Dwarf sections that should come prior to the
2057/// content. Create global DIEs and emit initial debug info sections.
2058/// This is inovked by the target AsmPrinter.
2059void DwarfDebug::beginModule(Module *M) {
2060  if (DisableDebugInfoPrinting)
2061    return;
2062
2063  DebugInfoFinder DbgFinder;
2064  DbgFinder.processModule(*M);
2065
2066  bool HasDebugInfo = false;
2067
2068  // Scan all the compile-units to see if there are any marked as the main unit.
2069  // if not, we do not generate debug info.
2070  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2071       E = DbgFinder.compile_unit_end(); I != E; ++I) {
2072    if (DICompileUnit(*I).isMain()) {
2073      HasDebugInfo = true;
2074      break;
2075    }
2076  }
2077
2078  if (!HasDebugInfo) return;
2079
2080  // Tell MMI that we have debug info.
2081  MMI->setDebugInfoAvailability(true);
2082
2083  // Emit initial sections.
2084  EmitSectionLabels();
2085
2086  // Create all the compile unit DIEs.
2087  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2088         E = DbgFinder.compile_unit_end(); I != E; ++I)
2089    constructCompileUnit(*I);
2090
2091  // Create DIEs for each subprogram.
2092  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
2093         E = DbgFinder.subprogram_end(); I != E; ++I)
2094    constructSubprogramDIE(*I);
2095
2096  // Create DIEs for each global variable.
2097  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
2098         E = DbgFinder.global_variable_end(); I != E; ++I)
2099    constructGlobalVariableDIE(*I);
2100
2101  //getOrCreateTypeDIE
2102  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
2103    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2104      getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2105
2106  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
2107    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2108      getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2109
2110  // Prime section data.
2111  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
2112}
2113
2114/// endModule - Emit all Dwarf sections that should come after the content.
2115///
2116void DwarfDebug::endModule() {
2117  if (!FirstCU) return;
2118  const Module *M = MMI->getModule();
2119  DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
2120  if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
2121    for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
2122      if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
2123      DISubprogram SP(AllSPs->getOperand(SI));
2124      if (!SP.Verify()) continue;
2125
2126      // Collect info for variables that were optimized out.
2127      if (!SP.isDefinition()) continue;
2128      StringRef FName = SP.getLinkageName();
2129      if (FName.empty())
2130        FName = SP.getName();
2131      NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
2132      if (!NMD) continue;
2133      unsigned E = NMD->getNumOperands();
2134      if (!E) continue;
2135      DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
2136      DeadFnScopeMap[SP] = Scope;
2137      for (unsigned I = 0; I != E; ++I) {
2138        DIVariable DV(NMD->getOperand(I));
2139        if (!DV.Verify()) continue;
2140        Scope->addVariable(new DbgVariable(DV));
2141      }
2142
2143      // Construct subprogram DIE and add variables DIEs.
2144      constructSubprogramDIE(SP);
2145      DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
2146      const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
2147      for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2148        DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
2149        if (VariableDIE)
2150          ScopeDIE->addChild(VariableDIE);
2151      }
2152    }
2153  }
2154
2155  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
2156  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
2157         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
2158    DIE *ISP = *AI;
2159    addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
2160  }
2161
2162  for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
2163         CE = ContainingTypeMap.end(); CI != CE; ++CI) {
2164    DIE *SPDie = CI->first;
2165    const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
2166    if (!N) continue;
2167    DIE *NDie = getCompileUnit(N)->getDIE(N);
2168    if (!NDie) continue;
2169    addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
2170  }
2171
2172  // Standard sections final addresses.
2173  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
2174  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
2175  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
2176  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
2177
2178  // End text sections.
2179  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2180    Asm->OutStreamer.SwitchSection(SectionMap[i]);
2181    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
2182  }
2183
2184  // Emit common frame information.
2185  emitCommonDebugFrame();
2186
2187  // Emit function debug frame information
2188  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2189         E = DebugFrames.end(); I != E; ++I)
2190    emitFunctionDebugFrame(*I);
2191
2192  // Compute DIE offsets and sizes.
2193  computeSizeAndOffsets();
2194
2195  // Emit all the DIEs into a debug info section
2196  emitDebugInfo();
2197
2198  // Corresponding abbreviations into a abbrev section.
2199  emitAbbreviations();
2200
2201  // Emit info into a debug pubnames section.
2202  emitDebugPubNames();
2203
2204  // Emit info into a debug pubtypes section.
2205  emitDebugPubTypes();
2206
2207  // Emit info into a debug loc section.
2208  emitDebugLoc();
2209
2210  // Emit info into a debug aranges section.
2211  EmitDebugARanges();
2212
2213  // Emit info into a debug ranges section.
2214  emitDebugRanges();
2215
2216  // Emit info into a debug macinfo section.
2217  emitDebugMacInfo();
2218
2219  // Emit inline info.
2220  emitDebugInlineInfo();
2221
2222  // Emit info into a debug str section.
2223  emitDebugStr();
2224
2225  // clean up.
2226  DeleteContainerSeconds(DeadFnScopeMap);
2227  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2228         E = CUMap.end(); I != E; ++I)
2229    delete I->second;
2230  FirstCU = NULL;  // Reset for the next Module, if any.
2231}
2232
2233/// findAbstractVariable - Find abstract variable, if any, associated with Var.
2234DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2235                                              DebugLoc ScopeLoc) {
2236
2237  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2238  if (AbsDbgVariable)
2239    return AbsDbgVariable;
2240
2241  LLVMContext &Ctx = Var->getContext();
2242  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2243  if (!Scope)
2244    return NULL;
2245
2246  AbsDbgVariable = new DbgVariable(Var);
2247  Scope->addVariable(AbsDbgVariable);
2248  AbstractVariables[Var] = AbsDbgVariable;
2249  return AbsDbgVariable;
2250}
2251
2252/// addCurrentFnArgument - If Var is an current function argument that add
2253/// it in CurrentFnArguments list.
2254bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
2255                                      DbgVariable *Var, DbgScope *Scope) {
2256  if (Scope != CurrentFnDbgScope)
2257    return false;
2258  DIVariable DV = Var->getVariable();
2259  if (DV.getTag() != dwarf::DW_TAG_arg_variable)
2260    return false;
2261  unsigned ArgNo = DV.getArgNumber();
2262  if (ArgNo == 0)
2263    return false;
2264
2265  size_t Size = CurrentFnArguments.size();
2266  if (Size == 0)
2267    CurrentFnArguments.resize(MF->getFunction()->arg_size());
2268  // llvm::Function argument size is not good indicator of how many
2269  // arguments does the function have at source level.
2270  if (ArgNo > Size)
2271    CurrentFnArguments.resize(ArgNo * 2);
2272  CurrentFnArguments[ArgNo - 1] = Var;
2273  return true;
2274}
2275
2276/// collectVariableInfoFromMMITable - Collect variable information from
2277/// side table maintained by MMI.
2278void
2279DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
2280                                   SmallPtrSet<const MDNode *, 16> &Processed) {
2281  const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2282  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2283  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2284         VE = VMap.end(); VI != VE; ++VI) {
2285    const MDNode *Var = VI->first;
2286    if (!Var) continue;
2287    Processed.insert(Var);
2288    DIVariable DV(Var);
2289    const std::pair<unsigned, DebugLoc> &VP = VI->second;
2290
2291    DbgScope *Scope = 0;
2292    if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2293      Scope = ConcreteScopes.lookup(IA);
2294    if (Scope == 0)
2295      Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2296
2297    // If variable scope is not found then skip this variable.
2298    if (Scope == 0)
2299      continue;
2300
2301    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
2302    DbgVariable *RegVar = new DbgVariable(DV);
2303    recordVariableFrameIndex(RegVar, VP.first);
2304    if (!addCurrentFnArgument(MF, RegVar, Scope))
2305      Scope->addVariable(RegVar);
2306    if (AbsDbgVariable) {
2307      recordVariableFrameIndex(AbsDbgVariable, VP.first);
2308      VarToAbstractVarMap[RegVar] = AbsDbgVariable;
2309    }
2310  }
2311}
2312
2313/// isDbgValueInDefinedReg - Return true if debug value, encoded by
2314/// DBG_VALUE instruction, is in a defined reg.
2315static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
2316  assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2317  return MI->getNumOperands() == 3 &&
2318         MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
2319         MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
2320}
2321
2322/// collectVariableInfo - Populate DbgScope entries with variables' info.
2323void
2324DwarfDebug::collectVariableInfo(const MachineFunction *MF,
2325                                SmallPtrSet<const MDNode *, 16> &Processed) {
2326
2327  /// collection info from MMI table.
2328  collectVariableInfoFromMMITable(MF, Processed);
2329
2330  for (SmallVectorImpl<const MDNode*>::const_iterator
2331         UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
2332         ++UVI) {
2333    const MDNode *Var = *UVI;
2334    if (Processed.count(Var))
2335      continue;
2336
2337    // History contains relevant DBG_VALUE instructions for Var and instructions
2338    // clobbering it.
2339    SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
2340    if (History.empty())
2341      continue;
2342    const MachineInstr *MInsn = History.front();
2343
2344    DIVariable DV(Var);
2345    DbgScope *Scope = NULL;
2346    if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
2347        DISubprogram(DV.getContext()).describes(MF->getFunction()))
2348      Scope = CurrentFnDbgScope;
2349    else
2350      Scope = findDbgScope(MInsn);
2351    // If variable scope is not found then skip this variable.
2352    if (!Scope)
2353      continue;
2354
2355    Processed.insert(DV);
2356    assert(MInsn->isDebugValue() && "History must begin with debug value");
2357    DbgVariable *RegVar = new DbgVariable(DV);
2358    if (!addCurrentFnArgument(MF, RegVar, Scope))
2359      Scope->addVariable(RegVar);
2360    if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
2361      DbgVariableToDbgInstMap[AbsVar] = MInsn;
2362      VarToAbstractVarMap[RegVar] = AbsVar;
2363    }
2364
2365    // Simple ranges that are fully coalesced.
2366    if (History.size() <= 1 || (History.size() == 2 &&
2367                                MInsn->isIdenticalTo(History.back()))) {
2368      DbgVariableToDbgInstMap[RegVar] = MInsn;
2369      continue;
2370    }
2371
2372    // handle multiple DBG_VALUE instructions describing one variable.
2373    RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
2374
2375    for (SmallVectorImpl<const MachineInstr*>::const_iterator
2376           HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
2377      const MachineInstr *Begin = *HI;
2378      assert(Begin->isDebugValue() && "Invalid History entry");
2379      MachineLocation MLoc;
2380      if (Begin->getNumOperands() == 3) {
2381        if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2382          MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2383      } else
2384        MLoc = Asm->getDebugValueLocation(Begin);
2385
2386      // FIXME: emitDebugLoc only understands registers.
2387      if (!MLoc.getReg())
2388        continue;
2389
2390      // Compute the range for a register location.
2391      const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
2392      const MCSymbol *SLabel = 0;
2393
2394      if (HI + 1 == HE)
2395        // If Begin is the last instruction in History then its value is valid
2396        // until the end of the funtion.
2397        SLabel = FunctionEndSym;
2398      else {
2399        const MachineInstr *End = HI[1];
2400        if (End->isDebugValue())
2401          SLabel = getLabelBeforeInsn(End);
2402        else {
2403          // End is a normal instruction clobbering the range.
2404          SLabel = getLabelAfterInsn(End);
2405          assert(SLabel && "Forgot label after clobber instruction");
2406          ++HI;
2407        }
2408      }
2409
2410      // The value is valid until the next DBG_VALUE or clobber.
2411      DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
2412    }
2413    DotDebugLocEntries.push_back(DotDebugLocEntry());
2414  }
2415
2416  // Collect info for variables that were optimized out.
2417  const Function *F = MF->getFunction();
2418  if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
2419    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2420      DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2421      if (!DV || !Processed.insert(DV))
2422        continue;
2423      DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
2424      if (Scope)
2425        Scope->addVariable(new DbgVariable(DV));
2426    }
2427  }
2428}
2429
2430/// getLabelBeforeInsn - Return Label preceding the instruction.
2431const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
2432  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
2433  assert(Label && "Didn't insert label before instruction");
2434  return Label;
2435}
2436
2437/// getLabelAfterInsn - Return Label immediately following the instruction.
2438const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
2439  return LabelsAfterInsn.lookup(MI);
2440}
2441
2442/// beginInstruction - Process beginning of an instruction.
2443void DwarfDebug::beginInstruction(const MachineInstr *MI) {
2444  // Check if source location changes, but ignore DBG_VALUE locations.
2445  if (!MI->isDebugValue()) {
2446    DebugLoc DL = MI->getDebugLoc();
2447    if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
2448      PrevInstLoc = DL;
2449      if (!DL.isUnknown()) {
2450        const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2451        recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2452      } else
2453        recordSourceLine(0, 0, 0);
2454    }
2455  }
2456
2457  // Insert labels where requested.
2458  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
2459    LabelsBeforeInsn.find(MI);
2460
2461  // No label needed.
2462  if (I == LabelsBeforeInsn.end())
2463    return;
2464
2465  // Label already assigned.
2466  if (I->second)
2467    return;
2468
2469  if (!PrevLabel) {
2470    PrevLabel = MMI->getContext().CreateTempSymbol();
2471    Asm->OutStreamer.EmitLabel(PrevLabel);
2472  }
2473  I->second = PrevLabel;
2474}
2475
2476/// endInstruction - Process end of an instruction.
2477void DwarfDebug::endInstruction(const MachineInstr *MI) {
2478  // Don't create a new label after DBG_VALUE instructions.
2479  // They don't generate code.
2480  if (!MI->isDebugValue())
2481    PrevLabel = 0;
2482
2483  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
2484    LabelsAfterInsn.find(MI);
2485
2486  // No label needed.
2487  if (I == LabelsAfterInsn.end())
2488    return;
2489
2490  // Label already assigned.
2491  if (I->second)
2492    return;
2493
2494  // We need a label after this instruction.
2495  if (!PrevLabel) {
2496    PrevLabel = MMI->getContext().CreateTempSymbol();
2497    Asm->OutStreamer.EmitLabel(PrevLabel);
2498  }
2499  I->second = PrevLabel;
2500}
2501
2502/// getOrCreateDbgScope - Create DbgScope for the scope.
2503DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
2504                                          const MDNode *InlinedAt) {
2505  if (!InlinedAt) {
2506    DbgScope *WScope = DbgScopeMap.lookup(Scope);
2507    if (WScope)
2508      return WScope;
2509    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2510    DbgScopeMap.insert(std::make_pair(Scope, WScope));
2511    if (DIDescriptor(Scope).isLexicalBlock()) {
2512      DbgScope *Parent =
2513        getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2514      WScope->setParent(Parent);
2515      Parent->addScope(WScope);
2516    }
2517
2518    if (!WScope->getParent()) {
2519      StringRef SPName = DISubprogram(Scope).getLinkageName();
2520      // We used to check only for a linkage name, but that fails
2521      // since we began omitting the linkage name for private
2522      // functions.  The new way is to check for the name in metadata,
2523      // but that's not supported in old .ll test cases.  Ergo, we
2524      // check both.
2525      if (SPName == Asm->MF->getFunction()->getName() ||
2526          DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
2527        CurrentFnDbgScope = WScope;
2528    }
2529
2530    return WScope;
2531  }
2532
2533  getOrCreateAbstractScope(Scope);
2534  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2535  if (WScope)
2536    return WScope;
2537
2538  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2539  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2540  DILocation DL(InlinedAt);
2541  DbgScope *Parent =
2542    getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2543  WScope->setParent(Parent);
2544  Parent->addScope(WScope);
2545
2546  ConcreteScopes[InlinedAt] = WScope;
2547
2548  return WScope;
2549}
2550
2551/// hasValidLocation - Return true if debug location entry attached with
2552/// machine instruction encodes valid location info.
2553static bool hasValidLocation(LLVMContext &Ctx,
2554                             const MachineInstr *MInsn,
2555                             const MDNode *&Scope, const MDNode *&InlinedAt) {
2556  DebugLoc DL = MInsn->getDebugLoc();
2557  if (DL.isUnknown()) return false;
2558
2559  const MDNode *S = DL.getScope(Ctx);
2560
2561  // There is no need to create another DIE for compile unit. For all
2562  // other scopes, create one DbgScope now. This will be translated
2563  // into a scope DIE at the end.
2564  if (DIScope(S).isCompileUnit()) return false;
2565
2566  Scope = S;
2567  InlinedAt = DL.getInlinedAt(Ctx);
2568  return true;
2569}
2570
2571/// calculateDominanceGraph - Calculate dominance graph for DbgScope
2572/// hierarchy.
2573static void calculateDominanceGraph(DbgScope *Scope) {
2574  assert (Scope && "Unable to calculate scop edominance graph!");
2575  SmallVector<DbgScope *, 4> WorkStack;
2576  WorkStack.push_back(Scope);
2577  unsigned Counter = 0;
2578  while (!WorkStack.empty()) {
2579    DbgScope *WS = WorkStack.back();
2580    const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2581    bool visitedChildren = false;
2582    for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2583           SE = Children.end(); SI != SE; ++SI) {
2584      DbgScope *ChildScope = *SI;
2585      if (!ChildScope->getDFSOut()) {
2586        WorkStack.push_back(ChildScope);
2587        visitedChildren = true;
2588        ChildScope->setDFSIn(++Counter);
2589        break;
2590      }
2591    }
2592    if (!visitedChildren) {
2593      WorkStack.pop_back();
2594      WS->setDFSOut(++Counter);
2595    }
2596  }
2597}
2598
2599/// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2600static
2601void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2602                       DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2603{
2604#ifndef NDEBUG
2605  unsigned PrevDFSIn = 0;
2606  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2607       I != E; ++I) {
2608    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2609         II != IE; ++II) {
2610      const MachineInstr *MInsn = II;
2611      const MDNode *Scope = NULL;
2612      const MDNode *InlinedAt = NULL;
2613
2614      // Check if instruction has valid location information.
2615      if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2616        dbgs() << " [ ";
2617        if (InlinedAt)
2618          dbgs() << "*";
2619        DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2620          MI2ScopeMap.find(MInsn);
2621        if (DI != MI2ScopeMap.end()) {
2622          DbgScope *S = DI->second;
2623          dbgs() << S->getDFSIn();
2624          PrevDFSIn = S->getDFSIn();
2625        } else
2626          dbgs() << PrevDFSIn;
2627      } else
2628        dbgs() << " [ x" << PrevDFSIn;
2629      dbgs() << " ]";
2630      MInsn->dump();
2631    }
2632    dbgs() << "\n";
2633  }
2634#endif
2635}
2636/// extractScopeInformation - Scan machine instructions in this function
2637/// and collect DbgScopes. Return true, if at least one scope was found.
2638bool DwarfDebug::extractScopeInformation() {
2639  // If scope information was extracted using .dbg intrinsics then there is not
2640  // any need to extract these information by scanning each instruction.
2641  if (!DbgScopeMap.empty())
2642    return false;
2643
2644  // Scan each instruction and create scopes. First build working set of scopes.
2645  LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2646  SmallVector<DbgRange, 4> MIRanges;
2647  DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2648  const MDNode *PrevScope = NULL;
2649  const MDNode *PrevInlinedAt = NULL;
2650  const MachineInstr *RangeBeginMI = NULL;
2651  const MachineInstr *PrevMI = NULL;
2652  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2653       I != E; ++I) {
2654    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2655         II != IE; ++II) {
2656      const MachineInstr *MInsn = II;
2657      const MDNode *Scope = NULL;
2658      const MDNode *InlinedAt = NULL;
2659
2660      // Check if instruction has valid location information.
2661      if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2662        PrevMI = MInsn;
2663        continue;
2664      }
2665
2666      // If scope has not changed then skip this instruction.
2667      if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2668        PrevMI = MInsn;
2669        continue;
2670      }
2671
2672      // Ignore DBG_VALUE. It does not contribute any instruction in output.
2673      if (MInsn->isDebugValue())
2674        continue;
2675
2676      if (RangeBeginMI) {
2677        // If we have alread seen a beginning of a instruction range and
2678        // current instruction scope does not match scope of first instruction
2679        // in this range then create a new instruction range.
2680        DbgRange R(RangeBeginMI, PrevMI);
2681        MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
2682                                                        PrevInlinedAt);
2683        MIRanges.push_back(R);
2684      }
2685
2686      // This is a beginning of a new instruction range.
2687      RangeBeginMI = MInsn;
2688
2689      // Reset previous markers.
2690      PrevMI = MInsn;
2691      PrevScope = Scope;
2692      PrevInlinedAt = InlinedAt;
2693    }
2694  }
2695
2696  // Create last instruction range.
2697  if (RangeBeginMI && PrevMI && PrevScope) {
2698    DbgRange R(RangeBeginMI, PrevMI);
2699    MIRanges.push_back(R);
2700    MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2701  }
2702
2703  if (!CurrentFnDbgScope)
2704    return false;
2705
2706  calculateDominanceGraph(CurrentFnDbgScope);
2707  if (PrintDbgScope)
2708    printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2709
2710  // Find ranges of instructions covered by each DbgScope;
2711  DbgScope *PrevDbgScope = NULL;
2712  for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2713         RE = MIRanges.end(); RI != RE; ++RI) {
2714    const DbgRange &R = *RI;
2715    DbgScope *S = MI2ScopeMap.lookup(R.first);
2716    assert (S && "Lost DbgScope for a machine instruction!");
2717    if (PrevDbgScope && !PrevDbgScope->dominates(S))
2718      PrevDbgScope->closeInsnRange(S);
2719    S->openInsnRange(R.first);
2720    S->extendInsnRange(R.second);
2721    PrevDbgScope = S;
2722  }
2723
2724  if (PrevDbgScope)
2725    PrevDbgScope->closeInsnRange();
2726
2727  identifyScopeMarkers();
2728
2729  return !DbgScopeMap.empty();
2730}
2731
2732/// identifyScopeMarkers() -
2733/// Each DbgScope has first instruction and last instruction to mark beginning
2734/// and end of a scope respectively. Create an inverse map that list scopes
2735/// starts (and ends) with an instruction. One instruction may start (or end)
2736/// multiple scopes. Ignore scopes that are not reachable.
2737void DwarfDebug::identifyScopeMarkers() {
2738  SmallVector<DbgScope *, 4> WorkList;
2739  WorkList.push_back(CurrentFnDbgScope);
2740  while (!WorkList.empty()) {
2741    DbgScope *S = WorkList.pop_back_val();
2742
2743    const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2744    if (!Children.empty())
2745      for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2746             SE = Children.end(); SI != SE; ++SI)
2747        WorkList.push_back(*SI);
2748
2749    if (S->isAbstractScope())
2750      continue;
2751
2752    const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2753    if (Ranges.empty())
2754      continue;
2755    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2756           RE = Ranges.end(); RI != RE; ++RI) {
2757      assert(RI->first && "DbgRange does not have first instruction!");
2758      assert(RI->second && "DbgRange does not have second instruction!");
2759      requestLabelBeforeInsn(RI->first);
2760      requestLabelAfterInsn(RI->second);
2761    }
2762  }
2763}
2764
2765/// FindFirstDebugLoc - Find the first debug location in the function. This
2766/// is intended to be an approximation for the source position of the
2767/// beginning of the function.
2768static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2769  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2770       I != E; ++I)
2771    for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2772         MBBI != MBBE; ++MBBI) {
2773      DebugLoc DL = MBBI->getDebugLoc();
2774      if (!DL.isUnknown())
2775        return DL;
2776    }
2777  return DebugLoc();
2778}
2779
2780#ifndef NDEBUG
2781/// CheckLineNumbers - Count basicblocks whose instructions do not have any
2782/// line number information.
2783static void CheckLineNumbers(const MachineFunction *MF) {
2784  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2785       I != E; ++I) {
2786    bool FoundLineNo = false;
2787    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2788         II != IE; ++II) {
2789      const MachineInstr *MI = II;
2790      if (!MI->getDebugLoc().isUnknown()) {
2791        FoundLineNo = true;
2792        break;
2793      }
2794    }
2795    if (!FoundLineNo && I->size())
2796      ++BlocksWithoutLineNo;
2797  }
2798}
2799#endif
2800
2801/// beginFunction - Gather pre-function debug information.  Assumes being
2802/// emitted immediately after the function entry point.
2803void DwarfDebug::beginFunction(const MachineFunction *MF) {
2804  if (!MMI->hasDebugInfo()) return;
2805  if (!extractScopeInformation()) return;
2806
2807#ifndef NDEBUG
2808  CheckLineNumbers(MF);
2809#endif
2810
2811  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2812                                        Asm->getFunctionNumber());
2813  // Assumes in correct section after the entry point.
2814  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2815
2816  // Emit label for the implicitly defined dbg.stoppoint at the start of the
2817  // function.
2818  DebugLoc FDL = FindFirstDebugLoc(MF);
2819  if (FDL.isUnknown()) return;
2820
2821  const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2822  const MDNode *TheScope = 0;
2823
2824  DISubprogram SP = getDISubprogram(Scope);
2825  unsigned Line, Col;
2826  if (SP.Verify()) {
2827    Line = SP.getLineNumber();
2828    Col = 0;
2829    TheScope = SP;
2830  } else {
2831    Line = FDL.getLine();
2832    Col = FDL.getCol();
2833    TheScope = Scope;
2834  }
2835
2836  recordSourceLine(Line, Col, TheScope);
2837
2838  assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
2839
2840  /// ProcessedArgs - Collection of arguments already processed.
2841  SmallPtrSet<const MDNode *, 8> ProcessedArgs;
2842
2843  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
2844
2845  /// LiveUserVar - Map physreg numbers to the MDNode they contain.
2846  std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
2847
2848  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2849       I != E; ++I) {
2850    bool AtBlockEntry = true;
2851    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2852         II != IE; ++II) {
2853      const MachineInstr *MI = II;
2854
2855      if (MI->isDebugValue()) {
2856        assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
2857
2858        // Keep track of user variables.
2859        const MDNode *Var =
2860          MI->getOperand(MI->getNumOperands() - 1).getMetadata();
2861
2862        // Variable is in a register, we need to check for clobbers.
2863        if (isDbgValueInDefinedReg(MI))
2864          LiveUserVar[MI->getOperand(0).getReg()] = Var;
2865
2866        // Check the history of this variable.
2867        SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
2868        if (History.empty()) {
2869          UserVariables.push_back(Var);
2870          // The first mention of a function argument gets the FunctionBeginSym
2871          // label, so arguments are visible when breaking at function entry.
2872          DIVariable DV(Var);
2873          if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
2874              DISubprogram(getDISubprogram(DV.getContext()))
2875                .describes(MF->getFunction()))
2876            LabelsBeforeInsn[MI] = FunctionBeginSym;
2877        } else {
2878          // We have seen this variable before. Try to coalesce DBG_VALUEs.
2879          const MachineInstr *Prev = History.back();
2880          if (Prev->isDebugValue()) {
2881            // Coalesce identical entries at the end of History.
2882            if (History.size() >= 2 &&
2883                Prev->isIdenticalTo(History[History.size() - 2]))
2884              History.pop_back();
2885
2886            // Terminate old register assignments that don't reach MI;
2887            MachineFunction::const_iterator PrevMBB = Prev->getParent();
2888            if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
2889                isDbgValueInDefinedReg(Prev)) {
2890              // Previous register assignment needs to terminate at the end of
2891              // its basic block.
2892              MachineBasicBlock::const_iterator LastMI =
2893                PrevMBB->getLastNonDebugInstr();
2894              if (LastMI == PrevMBB->end())
2895                // Drop DBG_VALUE for empty range.
2896                History.pop_back();
2897              else {
2898                // Terminate after LastMI.
2899                History.push_back(LastMI);
2900              }
2901            }
2902          }
2903        }
2904        History.push_back(MI);
2905      } else {
2906        // Not a DBG_VALUE instruction.
2907        if (!MI->isLabel())
2908          AtBlockEntry = false;
2909
2910        // Check if the instruction clobbers any registers with debug vars.
2911        for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
2912               MOE = MI->operands_end(); MOI != MOE; ++MOI) {
2913          if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
2914            continue;
2915          for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
2916               unsigned Reg = *AI; ++AI) {
2917            const MDNode *Var = LiveUserVar[Reg];
2918            if (!Var)
2919              continue;
2920            // Reg is now clobbered.
2921            LiveUserVar[Reg] = 0;
2922
2923            // Was MD last defined by a DBG_VALUE referring to Reg?
2924            DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
2925            if (HistI == DbgValues.end())
2926              continue;
2927            SmallVectorImpl<const MachineInstr*> &History = HistI->second;
2928            if (History.empty())
2929              continue;
2930            const MachineInstr *Prev = History.back();
2931            // Sanity-check: Register assignments are terminated at the end of
2932            // their block.
2933            if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
2934              continue;
2935            // Is the variable still in Reg?
2936            if (!isDbgValueInDefinedReg(Prev) ||
2937                Prev->getOperand(0).getReg() != Reg)
2938              continue;
2939            // Var is clobbered. Make sure the next instruction gets a label.
2940            History.push_back(MI);
2941          }
2942        }
2943      }
2944    }
2945  }
2946
2947  for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
2948       I != E; ++I) {
2949    SmallVectorImpl<const MachineInstr*> &History = I->second;
2950    if (History.empty())
2951      continue;
2952
2953    // Make sure the final register assignments are terminated.
2954    const MachineInstr *Prev = History.back();
2955    if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
2956      const MachineBasicBlock *PrevMBB = Prev->getParent();
2957      MachineBasicBlock::const_iterator LastMI = PrevMBB->getLastNonDebugInstr();
2958      if (LastMI == PrevMBB->end())
2959        // Drop DBG_VALUE for empty range.
2960        History.pop_back();
2961      else {
2962        // Terminate after LastMI.
2963        History.push_back(LastMI);
2964      }
2965    }
2966    // Request labels for the full history.
2967    for (unsigned i = 0, e = History.size(); i != e; ++i) {
2968      const MachineInstr *MI = History[i];
2969      if (MI->isDebugValue())
2970        requestLabelBeforeInsn(MI);
2971      else
2972        requestLabelAfterInsn(MI);
2973    }
2974  }
2975
2976  PrevInstLoc = DebugLoc();
2977  PrevLabel = FunctionBeginSym;
2978}
2979
2980/// endFunction - Gather and emit post-function debug information.
2981///
2982void DwarfDebug::endFunction(const MachineFunction *MF) {
2983  if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2984
2985  if (CurrentFnDbgScope) {
2986
2987    // Define end label for subprogram.
2988    FunctionEndSym = Asm->GetTempSymbol("func_end",
2989                                        Asm->getFunctionNumber());
2990    // Assumes in correct section after the entry point.
2991    Asm->OutStreamer.EmitLabel(FunctionEndSym);
2992
2993    SmallPtrSet<const MDNode *, 16> ProcessedVars;
2994    collectVariableInfo(MF, ProcessedVars);
2995
2996    // Construct abstract scopes.
2997    for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2998           AE = AbstractScopesList.end(); AI != AE; ++AI) {
2999      DISubprogram SP((*AI)->getScopeNode());
3000      if (SP.Verify()) {
3001        // Collect info for variables that were optimized out.
3002        StringRef FName = SP.getLinkageName();
3003        if (FName.empty())
3004          FName = SP.getName();
3005        if (NamedMDNode *NMD =
3006            getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
3007          for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3008          DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
3009          if (!DV || !ProcessedVars.insert(DV))
3010            continue;
3011          DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
3012          if (Scope)
3013            Scope->addVariable(new DbgVariable(DV));
3014          }
3015        }
3016      }
3017      if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
3018        constructScopeDIE(*AI);
3019    }
3020
3021    DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
3022
3023    if (!DisableFramePointerElim(*MF))
3024      addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
3025              dwarf::DW_FORM_flag, 1);
3026
3027
3028    DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
3029                                                 MMI->getFrameMoves()));
3030  }
3031
3032  // Clear debug info
3033  CurrentFnDbgScope = NULL;
3034  CurrentFnArguments.clear();
3035  DbgVariableToFrameIndexMap.clear();
3036  VarToAbstractVarMap.clear();
3037  DbgVariableToDbgInstMap.clear();
3038  DeleteContainerSeconds(DbgScopeMap);
3039  UserVariables.clear();
3040  DbgValues.clear();
3041  ConcreteScopes.clear();
3042  DeleteContainerSeconds(AbstractScopes);
3043  AbstractScopesList.clear();
3044  AbstractVariables.clear();
3045  LabelsBeforeInsn.clear();
3046  LabelsAfterInsn.clear();
3047  PrevLabel = NULL;
3048}
3049
3050/// recordVariableFrameIndex - Record a variable's index.
3051void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
3052  assert (V && "Invalid DbgVariable!");
3053  DbgVariableToFrameIndexMap[V] = Index;
3054}
3055
3056/// findVariableFrameIndex - Return true if frame index for the variable
3057/// is found. Update FI to hold value of the index.
3058bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
3059  assert (V && "Invalid DbgVariable!");
3060  DenseMap<const DbgVariable *, int>::iterator I =
3061    DbgVariableToFrameIndexMap.find(V);
3062  if (I == DbgVariableToFrameIndexMap.end())
3063    return false;
3064  *FI = I->second;
3065  return true;
3066}
3067
3068/// findDbgScope - Find DbgScope for the debug loc attached with an
3069/// instruction.
3070DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
3071  DbgScope *Scope = NULL;
3072  LLVMContext &Ctx =
3073    MInsn->getParent()->getParent()->getFunction()->getContext();
3074  DebugLoc DL = MInsn->getDebugLoc();
3075
3076  if (DL.isUnknown())
3077    return Scope;
3078
3079  if (const MDNode *IA = DL.getInlinedAt(Ctx))
3080    Scope = ConcreteScopes.lookup(IA);
3081  if (Scope == 0)
3082    Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
3083
3084  return Scope;
3085}
3086
3087
3088/// recordSourceLine - Register a source line with debug info. Returns the
3089/// unique label that was emitted and which provides correspondence to
3090/// the source line list.
3091void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S){
3092  StringRef Fn;
3093  StringRef Dir;
3094  unsigned Src = 1;
3095  if (S) {
3096    DIDescriptor Scope(S);
3097
3098    if (Scope.isCompileUnit()) {
3099      DICompileUnit CU(S);
3100      Fn = CU.getFilename();
3101      Dir = CU.getDirectory();
3102    } else if (Scope.isFile()) {
3103      DIFile F(S);
3104      Fn = F.getFilename();
3105      Dir = F.getDirectory();
3106    } else if (Scope.isSubprogram()) {
3107      DISubprogram SP(S);
3108      Fn = SP.getFilename();
3109      Dir = SP.getDirectory();
3110    } else if (Scope.isLexicalBlock()) {
3111      DILexicalBlock DB(S);
3112      Fn = DB.getFilename();
3113      Dir = DB.getDirectory();
3114    } else
3115      assert(0 && "Unexpected scope info");
3116
3117    Src = GetOrCreateSourceID(Fn, Dir);
3118  }
3119
3120  Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, DWARF2_FLAG_IS_STMT,
3121                                         0, 0);
3122}
3123
3124//===----------------------------------------------------------------------===//
3125// Emit Methods
3126//===----------------------------------------------------------------------===//
3127
3128/// computeSizeAndOffset - Compute the size and offset of a DIE.
3129///
3130unsigned
3131DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
3132  // Get the children.
3133  const std::vector<DIE *> &Children = Die->getChildren();
3134
3135  // If not last sibling and has children then add sibling offset attribute.
3136  if (!Last && !Children.empty())
3137    Die->addSiblingOffset(DIEValueAllocator);
3138
3139  // Record the abbreviation.
3140  assignAbbrevNumber(Die->getAbbrev());
3141
3142  // Get the abbreviation for this DIE.
3143  unsigned AbbrevNumber = Die->getAbbrevNumber();
3144  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3145
3146  // Set DIE offset
3147  Die->setOffset(Offset);
3148
3149  // Start the size with the size of abbreviation code.
3150  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
3151
3152  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3153  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3154
3155  // Size the DIE attribute values.
3156  for (unsigned i = 0, N = Values.size(); i < N; ++i)
3157    // Size attribute value.
3158    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
3159
3160  // Size the DIE children if any.
3161  if (!Children.empty()) {
3162    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
3163           "Children flag not set");
3164
3165    for (unsigned j = 0, M = Children.size(); j < M; ++j)
3166      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
3167
3168    // End of children marker.
3169    Offset += sizeof(int8_t);
3170  }
3171
3172  Die->setSize(Offset - Die->getOffset());
3173  return Offset;
3174}
3175
3176/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
3177///
3178void DwarfDebug::computeSizeAndOffsets() {
3179  unsigned PrevOffset = 0;
3180  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3181         E = CUMap.end(); I != E; ++I) {
3182    // Compute size of compile unit header.
3183    static unsigned Offset = PrevOffset +
3184      sizeof(int32_t) + // Length of Compilation Unit Info
3185      sizeof(int16_t) + // DWARF version number
3186      sizeof(int32_t) + // Offset Into Abbrev. Section
3187      sizeof(int8_t);   // Pointer Size (in bytes)
3188    computeSizeAndOffset(I->second->getCUDie(), Offset, true);
3189    PrevOffset = Offset;
3190  }
3191}
3192
3193/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
3194/// temporary label to it if SymbolStem is specified.
3195static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
3196                                const char *SymbolStem = 0) {
3197  Asm->OutStreamer.SwitchSection(Section);
3198  if (!SymbolStem) return 0;
3199
3200  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
3201  Asm->OutStreamer.EmitLabel(TmpSym);
3202  return TmpSym;
3203}
3204
3205/// EmitSectionLabels - Emit initial Dwarf sections with a label at
3206/// the start of each one.
3207void DwarfDebug::EmitSectionLabels() {
3208  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
3209
3210  // Dwarf sections base addresses.
3211  if (Asm->MAI->doesDwarfRequireFrameSection()) {
3212    DwarfFrameSectionSym =
3213      EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
3214   }
3215
3216  DwarfInfoSectionSym =
3217    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
3218  DwarfAbbrevSectionSym =
3219    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
3220  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
3221
3222  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
3223    EmitSectionSym(Asm, MacroInfo);
3224
3225  EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
3226  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
3227  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
3228  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
3229  DwarfStrSectionSym =
3230    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
3231  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
3232                                             "debug_range");
3233
3234  DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
3235                                           "section_debug_loc");
3236
3237  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
3238  EmitSectionSym(Asm, TLOF.getDataSection());
3239}
3240
3241/// emitDIE - Recusively Emits a debug information entry.
3242///
3243void DwarfDebug::emitDIE(DIE *Die) {
3244  // Get the abbreviation for this DIE.
3245  unsigned AbbrevNumber = Die->getAbbrevNumber();
3246  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3247
3248  // Emit the code (index) for the abbreviation.
3249  if (Asm->isVerbose())
3250    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
3251                                Twine::utohexstr(Die->getOffset()) + ":0x" +
3252                                Twine::utohexstr(Die->getSize()) + " " +
3253                                dwarf::TagString(Abbrev->getTag()));
3254  Asm->EmitULEB128(AbbrevNumber);
3255
3256  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3257  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3258
3259  // Emit the DIE attribute values.
3260  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3261    unsigned Attr = AbbrevData[i].getAttribute();
3262    unsigned Form = AbbrevData[i].getForm();
3263    assert(Form && "Too many attributes for DIE (check abbreviation)");
3264
3265    if (Asm->isVerbose())
3266      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
3267
3268    switch (Attr) {
3269    case dwarf::DW_AT_sibling:
3270      Asm->EmitInt32(Die->getSiblingOffset());
3271      break;
3272    case dwarf::DW_AT_abstract_origin: {
3273      DIEEntry *E = cast<DIEEntry>(Values[i]);
3274      DIE *Origin = E->getEntry();
3275      unsigned Addr = Origin->getOffset();
3276      Asm->EmitInt32(Addr);
3277      break;
3278    }
3279    case dwarf::DW_AT_ranges: {
3280      // DW_AT_range Value encodes offset in debug_range section.
3281      DIEInteger *V = cast<DIEInteger>(Values[i]);
3282
3283      if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
3284        Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
3285                                 V->getValue(),
3286                                 4);
3287      } else {
3288        Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
3289                                       V->getValue(),
3290                                       DwarfDebugRangeSectionSym,
3291                                       4);
3292      }
3293      break;
3294    }
3295    case dwarf::DW_AT_location: {
3296      if (UseDotDebugLocEntry.count(Die) != 0) {
3297        DIELabel *L = cast<DIELabel>(Values[i]);
3298        Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
3299      } else
3300        Values[i]->EmitValue(Asm, Form);
3301      break;
3302    }
3303    case dwarf::DW_AT_accessibility: {
3304      if (Asm->isVerbose()) {
3305        DIEInteger *V = cast<DIEInteger>(Values[i]);
3306        Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
3307      }
3308      Values[i]->EmitValue(Asm, Form);
3309      break;
3310    }
3311    default:
3312      // Emit an attribute using the defined form.
3313      Values[i]->EmitValue(Asm, Form);
3314      break;
3315    }
3316  }
3317
3318  // Emit the DIE children if any.
3319  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
3320    const std::vector<DIE *> &Children = Die->getChildren();
3321
3322    for (unsigned j = 0, M = Children.size(); j < M; ++j)
3323      emitDIE(Children[j]);
3324
3325    if (Asm->isVerbose())
3326      Asm->OutStreamer.AddComment("End Of Children Mark");
3327    Asm->EmitInt8(0);
3328  }
3329}
3330
3331/// emitDebugInfo - Emit the debug info section.
3332///
3333void DwarfDebug::emitDebugInfo() {
3334  // Start debug info section.
3335  Asm->OutStreamer.SwitchSection(
3336                            Asm->getObjFileLowering().getDwarfInfoSection());
3337  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3338         E = CUMap.end(); I != E; ++I) {
3339    CompileUnit *TheCU = I->second;
3340    DIE *Die = TheCU->getCUDie();
3341
3342    // Emit the compile units header.
3343    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
3344                                                  TheCU->getID()));
3345
3346    // Emit size of content not including length itself
3347    unsigned ContentSize = Die->getSize() +
3348      sizeof(int16_t) + // DWARF version number
3349      sizeof(int32_t) + // Offset Into Abbrev. Section
3350      sizeof(int8_t) +  // Pointer Size (in bytes)
3351      sizeof(int32_t);  // FIXME - extra pad for gdb bug.
3352
3353    Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
3354    Asm->EmitInt32(ContentSize);
3355    Asm->OutStreamer.AddComment("DWARF version number");
3356    Asm->EmitInt16(dwarf::DWARF_VERSION);
3357    Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
3358    Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
3359                           DwarfAbbrevSectionSym);
3360    Asm->OutStreamer.AddComment("Address Size (in bytes)");
3361    Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3362
3363    emitDIE(Die);
3364    // FIXME - extra padding for gdb bug.
3365    Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
3366    Asm->EmitInt8(0);
3367    Asm->EmitInt8(0);
3368    Asm->EmitInt8(0);
3369    Asm->EmitInt8(0);
3370    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
3371  }
3372}
3373
3374/// emitAbbreviations - Emit the abbreviation section.
3375///
3376void DwarfDebug::emitAbbreviations() const {
3377  // Check to see if it is worth the effort.
3378  if (!Abbreviations.empty()) {
3379    // Start the debug abbrev section.
3380    Asm->OutStreamer.SwitchSection(
3381                            Asm->getObjFileLowering().getDwarfAbbrevSection());
3382
3383    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
3384
3385    // For each abbrevation.
3386    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3387      // Get abbreviation data
3388      const DIEAbbrev *Abbrev = Abbreviations[i];
3389
3390      // Emit the abbrevations code (base 1 index.)
3391      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
3392
3393      // Emit the abbreviations data.
3394      Abbrev->Emit(Asm);
3395    }
3396
3397    // Mark end of abbreviations.
3398    Asm->EmitULEB128(0, "EOM(3)");
3399
3400    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
3401  }
3402}
3403
3404/// emitEndOfLineMatrix - Emit the last address of the section and the end of
3405/// the line matrix.
3406///
3407void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
3408  // Define last address of section.
3409  Asm->OutStreamer.AddComment("Extended Op");
3410  Asm->EmitInt8(0);
3411
3412  Asm->OutStreamer.AddComment("Op size");
3413  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3414  Asm->OutStreamer.AddComment("DW_LNE_set_address");
3415  Asm->EmitInt8(dwarf::DW_LNE_set_address);
3416
3417  Asm->OutStreamer.AddComment("Section end label");
3418
3419  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
3420                                   Asm->getTargetData().getPointerSize(),
3421                                   0/*AddrSpace*/);
3422
3423  // Mark end of matrix.
3424  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
3425  Asm->EmitInt8(0);
3426  Asm->EmitInt8(1);
3427  Asm->EmitInt8(1);
3428}
3429
3430/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3431///
3432void DwarfDebug::emitCommonDebugFrame() {
3433  if (!Asm->MAI->doesDwarfRequireFrameSection())
3434    return;
3435
3436  int stackGrowth = Asm->getTargetData().getPointerSize();
3437  if (Asm->TM.getFrameLowering()->getStackGrowthDirection() ==
3438      TargetFrameLowering::StackGrowsDown)
3439    stackGrowth *= -1;
3440
3441  // Start the dwarf frame section.
3442  Asm->OutStreamer.SwitchSection(
3443                              Asm->getObjFileLowering().getDwarfFrameSection());
3444
3445  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3446  Asm->OutStreamer.AddComment("Length of Common Information Entry");
3447  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3448                           Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3449
3450  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3451  Asm->OutStreamer.AddComment("CIE Identifier Tag");
3452  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3453  Asm->OutStreamer.AddComment("CIE Version");
3454  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3455  Asm->OutStreamer.AddComment("CIE Augmentation");
3456  Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3457  Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3458  Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3459  Asm->OutStreamer.AddComment("CIE RA Column");
3460  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3461  const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
3462  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3463
3464  std::vector<MachineMove> Moves;
3465  TFI->getInitialFrameState(Moves);
3466
3467  Asm->EmitFrameMoves(Moves, 0, false);
3468
3469  Asm->EmitAlignment(2);
3470  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3471}
3472
3473/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3474/// section.
3475void DwarfDebug::
3476emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3477  if (!Asm->MAI->doesDwarfRequireFrameSection())
3478    return;
3479
3480  // Start the dwarf frame section.
3481  Asm->OutStreamer.SwitchSection(
3482                              Asm->getObjFileLowering().getDwarfFrameSection());
3483
3484  Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3485  MCSymbol *DebugFrameBegin =
3486    Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3487  MCSymbol *DebugFrameEnd =
3488    Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3489  Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3490
3491  Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3492
3493  Asm->OutStreamer.AddComment("FDE CIE offset");
3494  Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3495                         DwarfFrameSectionSym);
3496
3497  Asm->OutStreamer.AddComment("FDE initial location");
3498  MCSymbol *FuncBeginSym =
3499    Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3500  Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3501                                   Asm->getTargetData().getPointerSize(),
3502                                   0/*AddrSpace*/);
3503
3504
3505  Asm->OutStreamer.AddComment("FDE address range");
3506  Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3507                           FuncBeginSym, Asm->getTargetData().getPointerSize());
3508
3509  Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3510
3511  Asm->EmitAlignment(2);
3512  Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3513}
3514
3515/// emitDebugPubNames - Emit visible names into a debug pubnames section.
3516///
3517void DwarfDebug::emitDebugPubNames() {
3518  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3519         E = CUMap.end(); I != E; ++I) {
3520    CompileUnit *TheCU = I->second;
3521    // Start the dwarf pubnames section.
3522    Asm->OutStreamer.SwitchSection(
3523      Asm->getObjFileLowering().getDwarfPubNamesSection());
3524
3525    Asm->OutStreamer.AddComment("Length of Public Names Info");
3526    Asm->EmitLabelDifference(
3527      Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
3528      Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
3529
3530    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3531                                                  TheCU->getID()));
3532
3533    Asm->OutStreamer.AddComment("DWARF Version");
3534    Asm->EmitInt16(dwarf::DWARF_VERSION);
3535
3536    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3537    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3538                           DwarfInfoSectionSym);
3539
3540    Asm->OutStreamer.AddComment("Compilation Unit Length");
3541    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3542                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
3543                             4);
3544
3545    const StringMap<DIE*> &Globals = TheCU->getGlobals();
3546    for (StringMap<DIE*>::const_iterator
3547           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3548      const char *Name = GI->getKeyData();
3549      DIE *Entity = GI->second;
3550
3551      Asm->OutStreamer.AddComment("DIE offset");
3552      Asm->EmitInt32(Entity->getOffset());
3553
3554      if (Asm->isVerbose())
3555        Asm->OutStreamer.AddComment("External Name");
3556      Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3557    }
3558
3559    Asm->OutStreamer.AddComment("End Mark");
3560    Asm->EmitInt32(0);
3561    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3562                                                TheCU->getID()));
3563  }
3564}
3565
3566void DwarfDebug::emitDebugPubTypes() {
3567  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3568         E = CUMap.end(); I != E; ++I) {
3569    CompileUnit *TheCU = I->second;
3570    // Start the dwarf pubnames section.
3571    Asm->OutStreamer.SwitchSection(
3572      Asm->getObjFileLowering().getDwarfPubTypesSection());
3573    Asm->OutStreamer.AddComment("Length of Public Types Info");
3574    Asm->EmitLabelDifference(
3575      Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
3576      Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
3577
3578    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3579                                                  TheCU->getID()));
3580
3581    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3582    Asm->EmitInt16(dwarf::DWARF_VERSION);
3583
3584    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3585    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3586                           DwarfInfoSectionSym);
3587
3588    Asm->OutStreamer.AddComment("Compilation Unit Length");
3589    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3590                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
3591                             4);
3592
3593    const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
3594    for (StringMap<DIE*>::const_iterator
3595           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3596      const char *Name = GI->getKeyData();
3597      DIE * Entity = GI->second;
3598
3599      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3600      Asm->EmitInt32(Entity->getOffset());
3601
3602      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3603      Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3604    }
3605
3606    Asm->OutStreamer.AddComment("End Mark");
3607    Asm->EmitInt32(0);
3608    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3609                                                  TheCU->getID()));
3610  }
3611}
3612
3613/// emitDebugStr - Emit visible names into a debug str section.
3614///
3615void DwarfDebug::emitDebugStr() {
3616  // Check to see if it is worth the effort.
3617  if (StringPool.empty()) return;
3618
3619  // Start the dwarf str section.
3620  Asm->OutStreamer.SwitchSection(
3621                                Asm->getObjFileLowering().getDwarfStrSection());
3622
3623  // Get all of the string pool entries and put them in an array by their ID so
3624  // we can sort them.
3625  SmallVector<std::pair<unsigned,
3626      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3627
3628  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3629       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3630    Entries.push_back(std::make_pair(I->second.second, &*I));
3631
3632  array_pod_sort(Entries.begin(), Entries.end());
3633
3634  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3635    // Emit a label for reference from debug information entries.
3636    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3637
3638    // Emit the string itself.
3639    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3640  }
3641}
3642
3643/// emitDebugLoc - Emit visible names into a debug loc section.
3644///
3645void DwarfDebug::emitDebugLoc() {
3646  if (DotDebugLocEntries.empty())
3647    return;
3648
3649  for (SmallVector<DotDebugLocEntry, 4>::iterator
3650         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
3651       I != E; ++I) {
3652    DotDebugLocEntry &Entry = *I;
3653    if (I + 1 != DotDebugLocEntries.end())
3654      Entry.Merge(I+1);
3655  }
3656
3657  // Start the dwarf loc section.
3658  Asm->OutStreamer.SwitchSection(
3659    Asm->getObjFileLowering().getDwarfLocSection());
3660  unsigned char Size = Asm->getTargetData().getPointerSize();
3661  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
3662  unsigned index = 1;
3663  for (SmallVector<DotDebugLocEntry, 4>::iterator
3664         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
3665       I != E; ++I, ++index) {
3666    DotDebugLocEntry &Entry = *I;
3667    if (Entry.isMerged()) continue;
3668    if (Entry.isEmpty()) {
3669      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3670      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3671      Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
3672    } else {
3673      Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
3674      Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
3675      const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3676      unsigned Reg = RI->getDwarfRegNum(Entry.Loc.getReg(), false);
3677      if (int Offset =  Entry.Loc.getOffset()) {
3678        // If the value is at a certain offset from frame register then
3679        // use DW_OP_fbreg.
3680        unsigned OffsetSize = Offset ? MCAsmInfo::getSLEB128Size(Offset) : 1;
3681        Asm->OutStreamer.AddComment("Loc expr size");
3682        Asm->EmitInt16(1 + OffsetSize);
3683        Asm->OutStreamer.AddComment(
3684          dwarf::OperationEncodingString(dwarf::DW_OP_fbreg));
3685        Asm->EmitInt8(dwarf::DW_OP_fbreg);
3686        Asm->OutStreamer.AddComment("Offset");
3687        Asm->EmitSLEB128(Offset);
3688      } else {
3689        if (Reg < 32) {
3690          Asm->OutStreamer.AddComment("Loc expr size");
3691          Asm->EmitInt16(1);
3692          Asm->OutStreamer.AddComment(
3693            dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
3694          Asm->EmitInt8(dwarf::DW_OP_reg0 + Reg);
3695        } else {
3696          Asm->OutStreamer.AddComment("Loc expr size");
3697          Asm->EmitInt16(1 + MCAsmInfo::getULEB128Size(Reg));
3698          Asm->EmitInt8(dwarf::DW_OP_regx);
3699          Asm->EmitULEB128(Reg);
3700        }
3701      }
3702    }
3703  }
3704}
3705
3706/// EmitDebugARanges - Emit visible names into a debug aranges section.
3707///
3708void DwarfDebug::EmitDebugARanges() {
3709  // Start the dwarf aranges section.
3710  Asm->OutStreamer.SwitchSection(
3711                          Asm->getObjFileLowering().getDwarfARangesSection());
3712}
3713
3714/// emitDebugRanges - Emit visible names into a debug ranges section.
3715///
3716void DwarfDebug::emitDebugRanges() {
3717  // Start the dwarf ranges section.
3718  Asm->OutStreamer.SwitchSection(
3719    Asm->getObjFileLowering().getDwarfRangesSection());
3720  unsigned char Size = Asm->getTargetData().getPointerSize();
3721  for (SmallVector<const MCSymbol *, 8>::iterator
3722         I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3723       I != E; ++I) {
3724    if (*I)
3725      Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3726    else
3727      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3728  }
3729}
3730
3731/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3732///
3733void DwarfDebug::emitDebugMacInfo() {
3734  if (const MCSection *LineInfo =
3735      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3736    // Start the dwarf macinfo section.
3737    Asm->OutStreamer.SwitchSection(LineInfo);
3738  }
3739}
3740
3741/// emitDebugInlineInfo - Emit inline info using following format.
3742/// Section Header:
3743/// 1. length of section
3744/// 2. Dwarf version number
3745/// 3. address size.
3746///
3747/// Entries (one "entry" for each function that was inlined):
3748///
3749/// 1. offset into __debug_str section for MIPS linkage name, if exists;
3750///   otherwise offset into __debug_str for regular function name.
3751/// 2. offset into __debug_str section for regular function name.
3752/// 3. an unsigned LEB128 number indicating the number of distinct inlining
3753/// instances for the function.
3754///
3755/// The rest of the entry consists of a {die_offset, low_pc} pair for each
3756/// inlined instance; the die_offset points to the inlined_subroutine die in the
3757/// __debug_info section, and the low_pc is the starting address for the
3758/// inlining instance.
3759void DwarfDebug::emitDebugInlineInfo() {
3760  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3761    return;
3762
3763  if (!FirstCU)
3764    return;
3765
3766  Asm->OutStreamer.SwitchSection(
3767                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
3768
3769  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3770  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3771                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3772
3773  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3774
3775  Asm->OutStreamer.AddComment("Dwarf Version");
3776  Asm->EmitInt16(dwarf::DWARF_VERSION);
3777  Asm->OutStreamer.AddComment("Address Size (in bytes)");
3778  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3779
3780  for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3781         E = InlinedSPNodes.end(); I != E; ++I) {
3782
3783    const MDNode *Node = *I;
3784    DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3785      = InlineInfo.find(Node);
3786    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3787    DISubprogram SP(Node);
3788    StringRef LName = SP.getLinkageName();
3789    StringRef Name = SP.getName();
3790
3791    Asm->OutStreamer.AddComment("MIPS linkage name");
3792    if (LName.empty()) {
3793      Asm->OutStreamer.EmitBytes(Name, 0);
3794      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3795    } else
3796      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3797                             DwarfStrSectionSym);
3798
3799    Asm->OutStreamer.AddComment("Function name");
3800    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3801    Asm->EmitULEB128(Labels.size(), "Inline count");
3802
3803    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3804           LE = Labels.end(); LI != LE; ++LI) {
3805      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3806      Asm->EmitInt32(LI->second->getOffset());
3807
3808      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3809      Asm->OutStreamer.EmitSymbolValue(LI->first,
3810                                       Asm->getTargetData().getPointerSize(),0);
3811    }
3812  }
3813
3814  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
3815}
3816