DwarfDebug.cpp revision 6f01d9c2f0a97b0dccde93a232c88f088877819f
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#define DEBUG_TYPE "dwarfdebug"
14#include "DwarfDebug.h"
15#include "llvm/Module.h"
16#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/CodeGen/MachineModuleInfo.h"
18#include "llvm/MC/MCSection.h"
19#include "llvm/MC/MCStreamer.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/Target/TargetData.h"
22#include "llvm/Target/TargetFrameInfo.h"
23#include "llvm/Target/TargetLoweringObjectFile.h"
24#include "llvm/Target/TargetRegisterInfo.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/Mangler.h"
29#include "llvm/Support/Timer.h"
30#include "llvm/System/Path.h"
31using namespace llvm;
32
33static TimerGroup &getDwarfTimerGroup() {
34  static TimerGroup DwarfTimerGroup("Dwarf Debugging");
35  return DwarfTimerGroup;
36}
37
38//===----------------------------------------------------------------------===//
39
40/// Configuration values for initial hash set sizes (log2).
41///
42static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
43
44namespace llvm {
45
46//===----------------------------------------------------------------------===//
47/// CompileUnit - This dwarf writer support class manages information associate
48/// with a source file.
49class CompileUnit {
50  /// ID - File identifier for source.
51  ///
52  unsigned ID;
53
54  /// Die - Compile unit debug information entry.
55  ///
56  DIE *Die;
57
58  /// IndexTyDie - An anonymous type for index type.
59  DIE *IndexTyDie;
60
61  /// GVToDieMap - Tracks the mapping of unit level debug informaton
62  /// variables to debug information entries.
63  /// FIXME : Rename GVToDieMap -> NodeToDieMap
64  ValueMap<MDNode *, DIE *> GVToDieMap;
65
66  /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
67  /// descriptors to debug information entries using a DIEEntry proxy.
68  /// FIXME : Rename
69  ValueMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
70
71  /// Globals - A map of globally visible named entities for this unit.
72  ///
73  StringMap<DIE*> Globals;
74
75public:
76  CompileUnit(unsigned I, DIE *D)
77    : ID(I), Die(D), IndexTyDie(0) {}
78  ~CompileUnit() { delete Die; delete IndexTyDie; }
79
80  // Accessors.
81  unsigned getID() const { return ID; }
82  DIE* getCUDie() const { return Die; }
83  StringMap<DIE*> &getGlobals() { return Globals; }
84
85  /// hasContent - Return true if this compile unit has something to write out.
86  ///
87  bool hasContent() const { return !Die->getChildren().empty(); }
88
89  /// AddGlobal - Add a new global entity to the compile unit.
90  ///
91  void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
92
93  /// getDIE - Returns the debug information entry map slot for the
94  /// specified debug variable.
95  DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
96
97  /// insertDIE - Insert DIE into the map.
98  void insertDIE(MDNode *N, DIE *D) {
99    GVToDieMap.insert(std::make_pair(N, D));
100  }
101
102  /// getDIEEntry - Returns the debug information entry for the speciefied
103  /// debug variable.
104  DIEEntry *getDIEEntry(MDNode *N) { return GVToDIEEntryMap.lookup(N); }
105
106  /// insertDIEEntry - Insert debug information entry into the map.
107  void insertDIEEntry(MDNode *N, DIEEntry *E) {
108    GVToDIEEntryMap.insert(std::make_pair(N, E));
109  }
110
111  /// AddDie - Adds or interns the DIE to the compile unit.
112  ///
113  void AddDie(DIE *Buffer) {
114    this->Die->AddChild(Buffer);
115  }
116
117  // getIndexTyDie - Get an anonymous type for index type.
118  DIE *getIndexTyDie() {
119    return IndexTyDie;
120  }
121
122  // setIndexTyDie - Set D as anonymous type for index which can be reused later.
123  void setIndexTyDie(DIE *D) {
124    IndexTyDie = D;
125  }
126
127};
128
129//===----------------------------------------------------------------------===//
130/// DbgVariable - This class is used to track local variable information.
131///
132class DbgVariable {
133  DIVariable Var;                    // Variable Descriptor.
134  unsigned FrameIndex;               // Variable frame index.
135  DbgVariable *AbstractVar;          // Abstract variable for this variable.
136  DIE *TheDIE;
137public:
138  DbgVariable(DIVariable V, unsigned I)
139    : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0)  {}
140
141  // Accessors.
142  DIVariable getVariable()           const { return Var; }
143  unsigned getFrameIndex()           const { return FrameIndex; }
144  void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
145  DbgVariable *getAbstractVariable() const { return AbstractVar; }
146  void setDIE(DIE *D)                      { TheDIE = D; }
147  DIE *getDIE()                      const { return TheDIE; }
148};
149
150//===----------------------------------------------------------------------===//
151/// DbgScope - This class is used to track scope information.
152///
153class DbgScope {
154  DbgScope *Parent;                   // Parent to this scope.
155  DIDescriptor Desc;                  // Debug info descriptor for scope.
156  WeakVH InlinedAtLocation;           // Location at which scope is inlined.
157  bool AbstractScope;                 // Abstract Scope
158  unsigned StartLabelID;              // Label ID of the beginning of scope.
159  unsigned EndLabelID;                // Label ID of the end of scope.
160  const MachineInstr *LastInsn;       // Last instruction of this scope.
161  const MachineInstr *FirstInsn;      // First instruction of this scope.
162  SmallVector<DbgScope *, 4> Scopes;  // Scopes defined in scope.
163  SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
164
165  // Private state for dump()
166  mutable unsigned IndentLevel;
167public:
168  DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
169    : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
170      StartLabelID(0), EndLabelID(0),
171      LastInsn(0), FirstInsn(0), IndentLevel(0) {}
172  virtual ~DbgScope();
173
174  // Accessors.
175  DbgScope *getParent()          const { return Parent; }
176  void setParent(DbgScope *P)          { Parent = P; }
177  DIDescriptor getDesc()         const { return Desc; }
178  MDNode *getInlinedAt()         const {
179    return dyn_cast_or_null<MDNode>(InlinedAtLocation);
180  }
181  MDNode *getScopeNode()         const { return Desc.getNode(); }
182  unsigned getStartLabelID()     const { return StartLabelID; }
183  unsigned getEndLabelID()       const { return EndLabelID; }
184  SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
185  SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
186  void setStartLabelID(unsigned S) { StartLabelID = S; }
187  void setEndLabelID(unsigned E)   { EndLabelID = E; }
188  void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
189  const MachineInstr *getLastInsn()      { return LastInsn; }
190  void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
191  void setAbstractScope() { AbstractScope = true; }
192  bool isAbstractScope() const { return AbstractScope; }
193  const MachineInstr *getFirstInsn()      { return FirstInsn; }
194
195  /// AddScope - Add a scope to the scope.
196  ///
197  void AddScope(DbgScope *S) { Scopes.push_back(S); }
198
199  /// AddVariable - Add a variable to the scope.
200  ///
201  void AddVariable(DbgVariable *V) { Variables.push_back(V); }
202
203  void FixInstructionMarkers() {
204    assert (getFirstInsn() && "First instruction is missing!");
205    if (getLastInsn())
206      return;
207
208    // If a scope does not have an instruction to mark an end then use
209    // the end of last child scope.
210    SmallVector<DbgScope *, 4> &Scopes = getScopes();
211    assert (!Scopes.empty() && "Inner most scope does not have last insn!");
212    DbgScope *L = Scopes.back();
213    if (!L->getLastInsn())
214      L->FixInstructionMarkers();
215    setLastInsn(L->getLastInsn());
216  }
217
218#ifndef NDEBUG
219  void dump() const;
220#endif
221};
222
223#ifndef NDEBUG
224void DbgScope::dump() const {
225  raw_ostream &err = errs();
226  err.indent(IndentLevel);
227  MDNode *N = Desc.getNode();
228  N->dump();
229  err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
230  if (AbstractScope)
231    err << "Abstract Scope\n";
232
233  IndentLevel += 2;
234  if (!Scopes.empty())
235    err << "Children ...\n";
236  for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
237    if (Scopes[i] != this)
238      Scopes[i]->dump();
239
240  IndentLevel -= 2;
241}
242#endif
243
244//===----------------------------------------------------------------------===//
245/// DbgConcreteScope - This class is used to track a scope that holds concrete
246/// instance information.
247///
248class DbgConcreteScope : public DbgScope {
249  CompileUnit *Unit;
250  DIE *Die;                           // Debug info for this concrete scope.
251public:
252  DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
253
254  // Accessors.
255  DIE *getDie() const { return Die; }
256  void setDie(DIE *D) { Die = D; }
257};
258
259DbgScope::~DbgScope() {
260  for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
261    delete Scopes[i];
262  for (unsigned j = 0, M = Variables.size(); j < M; ++j)
263    delete Variables[j];
264}
265
266} // end llvm namespace
267
268DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
269  : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
270    AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
271    Values(), StringPool(),
272    SectionSourceLines(), didInitial(false), shouldEmit(false),
273    CurrentFnDbgScope(0), DebugTimer(0) {
274  if (TimePassesIsEnabled)
275    DebugTimer = new Timer("Dwarf Debug Writer",
276                           getDwarfTimerGroup());
277}
278DwarfDebug::~DwarfDebug() {
279  for (unsigned j = 0, M = Values.size(); j < M; ++j)
280    delete Values[j];
281
282  delete DebugTimer;
283}
284
285/// AssignAbbrevNumber - Define a unique number for the abbreviation.
286///
287void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
288  // Profile the node so that we can make it unique.
289  FoldingSetNodeID ID;
290  Abbrev.Profile(ID);
291
292  // Check the set for priors.
293  DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
294
295  // If it's newly added.
296  if (InSet == &Abbrev) {
297    // Add to abbreviation list.
298    Abbreviations.push_back(&Abbrev);
299
300    // Assign the vector position + 1 as its number.
301    Abbrev.setNumber(Abbreviations.size());
302  } else {
303    // Assign existing abbreviation number.
304    Abbrev.setNumber(InSet->getNumber());
305  }
306}
307
308/// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
309/// information entry.
310DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
311  DIEEntry *Value = new DIEEntry(Entry);
312  Values.push_back(Value);
313  return Value;
314}
315
316/// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
317///
318void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
319  Value->setEntry(Entry);
320}
321
322/// AddUInt - Add an unsigned integer attribute data and value.
323///
324void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
325                         unsigned Form, uint64_t Integer) {
326  if (!Form) Form = DIEInteger::BestForm(false, Integer);
327  DIEValue *Value = new DIEInteger(Integer);
328  Values.push_back(Value);
329  Die->AddValue(Attribute, Form, Value);
330}
331
332/// AddSInt - Add an signed integer attribute data and value.
333///
334void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
335                         unsigned Form, int64_t Integer) {
336  if (!Form) Form = DIEInteger::BestForm(true, Integer);
337  DIEValue *Value = new DIEInteger(Integer);
338  Values.push_back(Value);
339  Die->AddValue(Attribute, Form, Value);
340}
341
342/// AddString - Add a string attribute data and value.
343///
344void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
345                           const std::string &String) {
346  DIEValue *Value = new DIEString(String);
347  Values.push_back(Value);
348  Die->AddValue(Attribute, Form, Value);
349}
350
351/// AddLabel - Add a Dwarf label attribute data and value.
352///
353void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
354                          const DWLabel &Label) {
355  DIEValue *Value = new DIEDwarfLabel(Label);
356  Values.push_back(Value);
357  Die->AddValue(Attribute, Form, Value);
358}
359
360/// AddObjectLabel - Add an non-Dwarf label attribute data and value.
361///
362void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
363                                const std::string &Label) {
364  DIEValue *Value = new DIEObjectLabel(Label);
365  Values.push_back(Value);
366  Die->AddValue(Attribute, Form, Value);
367}
368
369/// AddSectionOffset - Add a section offset label attribute data and value.
370///
371void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
372                                  const DWLabel &Label, const DWLabel &Section,
373                                  bool isEH, bool useSet) {
374  DIEValue *Value = new DIESectionOffset(Label, Section, isEH, useSet);
375  Values.push_back(Value);
376  Die->AddValue(Attribute, Form, Value);
377}
378
379/// AddDelta - Add a label delta attribute data and value.
380///
381void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
382                          const DWLabel &Hi, const DWLabel &Lo) {
383  DIEValue *Value = new DIEDelta(Hi, Lo);
384  Values.push_back(Value);
385  Die->AddValue(Attribute, Form, Value);
386}
387
388/// AddBlock - Add block data.
389///
390void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
391                          DIEBlock *Block) {
392  Block->ComputeSize(TD);
393  Values.push_back(Block);
394  Die->AddValue(Attribute, Block->BestForm(), Block);
395}
396
397/// AddSourceLine - Add location information to specified debug information
398/// entry.
399void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
400  // If there is no compile unit specified, don't add a line #.
401  if (V->getCompileUnit().isNull())
402    return;
403
404  unsigned Line = V->getLineNumber();
405  unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
406  assert(FileID && "Invalid file id");
407  AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
408  AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
409}
410
411/// AddSourceLine - Add location information to specified debug information
412/// entry.
413void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
414  // If there is no compile unit specified, don't add a line #.
415  if (G->getCompileUnit().isNull())
416    return;
417
418  unsigned Line = G->getLineNumber();
419  unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
420  assert(FileID && "Invalid file id");
421  AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
422  AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
423}
424
425/// AddSourceLine - Add location information to specified debug information
426/// entry.
427void DwarfDebug::AddSourceLine(DIE *Die, const DISubprogram *SP) {
428  // If there is no compile unit specified, don't add a line #.
429  if (SP->getCompileUnit().isNull())
430    return;
431  // If the line number is 0, don't add it.
432  if (SP->getLineNumber() == 0)
433    return;
434
435
436  unsigned Line = SP->getLineNumber();
437  unsigned FileID = FindCompileUnit(SP->getCompileUnit()).getID();
438  assert(FileID && "Invalid file id");
439  AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
440  AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
441}
442
443/// AddSourceLine - Add location information to specified debug information
444/// entry.
445void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
446  // If there is no compile unit specified, don't add a line #.
447  DICompileUnit CU = Ty->getCompileUnit();
448  if (CU.isNull())
449    return;
450
451  unsigned Line = Ty->getLineNumber();
452  unsigned FileID = FindCompileUnit(CU).getID();
453  assert(FileID && "Invalid file id");
454  AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
455  AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
456}
457
458/* Byref variables, in Blocks, are declared by the programmer as
459   "SomeType VarName;", but the compiler creates a
460   __Block_byref_x_VarName struct, and gives the variable VarName
461   either the struct, or a pointer to the struct, as its type.  This
462   is necessary for various behind-the-scenes things the compiler
463   needs to do with by-reference variables in blocks.
464
465   However, as far as the original *programmer* is concerned, the
466   variable should still have type 'SomeType', as originally declared.
467
468   The following function dives into the __Block_byref_x_VarName
469   struct to find the original type of the variable.  This will be
470   passed back to the code generating the type for the Debug
471   Information Entry for the variable 'VarName'.  'VarName' will then
472   have the original type 'SomeType' in its debug information.
473
474   The original type 'SomeType' will be the type of the field named
475   'VarName' inside the __Block_byref_x_VarName struct.
476
477   NOTE: In order for this to not completely fail on the debugger
478   side, the Debug Information Entry for the variable VarName needs to
479   have a DW_AT_location that tells the debugger how to unwind through
480   the pointers and __Block_byref_x_VarName struct to find the actual
481   value of the variable.  The function AddBlockByrefType does this.  */
482
483/// Find the type the programmer originally declared the variable to be
484/// and return that type.
485///
486DIType DwarfDebug::GetBlockByrefType(DIType Ty, std::string Name) {
487
488  DIType subType = Ty;
489  unsigned tag = Ty.getTag();
490
491  if (tag == dwarf::DW_TAG_pointer_type) {
492    DIDerivedType DTy = DIDerivedType(Ty.getNode());
493    subType = DTy.getTypeDerivedFrom();
494  }
495
496  DICompositeType blockStruct = DICompositeType(subType.getNode());
497
498  DIArray Elements = blockStruct.getTypeArray();
499
500  if (Elements.isNull())
501    return Ty;
502
503  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
504    DIDescriptor Element = Elements.getElement(i);
505    DIDerivedType DT = DIDerivedType(Element.getNode());
506    if (strcmp(Name.c_str(), DT.getName()) == 0)
507      return (DT.getTypeDerivedFrom());
508  }
509
510  return Ty;
511}
512
513/// AddComplexAddress - Start with the address based on the location provided,
514/// and generate the DWARF information necessary to find the actual variable
515/// given the extra address information encoded in the DIVariable, starting from
516/// the starting location.  Add the DWARF information to the die.
517///
518void DwarfDebug::AddComplexAddress(DbgVariable *&DV, DIE *Die,
519                                   unsigned Attribute,
520                                   const MachineLocation &Location) {
521  const DIVariable &VD = DV->getVariable();
522  DIType Ty = VD.getType();
523
524  // Decode the original location, and use that as the start of the byref
525  // variable's location.
526  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
527  DIEBlock *Block = new DIEBlock();
528
529  if (Location.isReg()) {
530    if (Reg < 32) {
531      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
532    } else {
533      Reg = Reg - dwarf::DW_OP_reg0;
534      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
535      AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
536    }
537  } else {
538    if (Reg < 32)
539      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
540    else {
541      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
542      AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
543    }
544
545    AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
546  }
547
548  for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
549    uint64_t Element = VD.getAddrElement(i);
550
551    if (Element == DIFactory::OpPlus) {
552      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
553      AddUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
554    } else if (Element == DIFactory::OpDeref) {
555      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
556    } else llvm_unreachable("unknown DIFactory Opcode");
557  }
558
559  // Now attach the location information to the DIE.
560  AddBlock(Die, Attribute, 0, Block);
561}
562
563/* Byref variables, in Blocks, are declared by the programmer as "SomeType
564   VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
565   gives the variable VarName either the struct, or a pointer to the struct, as
566   its type.  This is necessary for various behind-the-scenes things the
567   compiler needs to do with by-reference variables in Blocks.
568
569   However, as far as the original *programmer* is concerned, the variable
570   should still have type 'SomeType', as originally declared.
571
572   The function GetBlockByrefType dives into the __Block_byref_x_VarName
573   struct to find the original type of the variable, which is then assigned to
574   the variable's Debug Information Entry as its real type.  So far, so good.
575   However now the debugger will expect the variable VarName to have the type
576   SomeType.  So we need the location attribute for the variable to be an
577   expression that explains to the debugger how to navigate through the
578   pointers and struct to find the actual variable of type SomeType.
579
580   The following function does just that.  We start by getting
581   the "normal" location for the variable. This will be the location
582   of either the struct __Block_byref_x_VarName or the pointer to the
583   struct __Block_byref_x_VarName.
584
585   The struct will look something like:
586
587   struct __Block_byref_x_VarName {
588     ... <various fields>
589     struct __Block_byref_x_VarName *forwarding;
590     ... <various other fields>
591     SomeType VarName;
592     ... <maybe more fields>
593   };
594
595   If we are given the struct directly (as our starting point) we
596   need to tell the debugger to:
597
598   1).  Add the offset of the forwarding field.
599
600   2).  Follow that pointer to get the the real __Block_byref_x_VarName
601   struct to use (the real one may have been copied onto the heap).
602
603   3).  Add the offset for the field VarName, to find the actual variable.
604
605   If we started with a pointer to the struct, then we need to
606   dereference that pointer first, before the other steps.
607   Translating this into DWARF ops, we will need to append the following
608   to the current location description for the variable:
609
610   DW_OP_deref                    -- optional, if we start with a pointer
611   DW_OP_plus_uconst <forward_fld_offset>
612   DW_OP_deref
613   DW_OP_plus_uconst <varName_fld_offset>
614
615   That is what this function does.  */
616
617/// AddBlockByrefAddress - Start with the address based on the location
618/// provided, and generate the DWARF information necessary to find the
619/// actual Block variable (navigating the Block struct) based on the
620/// starting location.  Add the DWARF information to the die.  For
621/// more information, read large comment just above here.
622///
623void DwarfDebug::AddBlockByrefAddress(DbgVariable *&DV, DIE *Die,
624                                      unsigned Attribute,
625                                      const MachineLocation &Location) {
626  const DIVariable &VD = DV->getVariable();
627  DIType Ty = VD.getType();
628  DIType TmpTy = Ty;
629  unsigned Tag = Ty.getTag();
630  bool isPointer = false;
631
632  const char *varName = VD.getName();
633
634  if (Tag == dwarf::DW_TAG_pointer_type) {
635    DIDerivedType DTy = DIDerivedType(Ty.getNode());
636    TmpTy = DTy.getTypeDerivedFrom();
637    isPointer = true;
638  }
639
640  DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
641
642  // Find the __forwarding field and the variable field in the __Block_byref
643  // struct.
644  DIArray Fields = blockStruct.getTypeArray();
645  DIDescriptor varField = DIDescriptor();
646  DIDescriptor forwardingField = DIDescriptor();
647
648
649  for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
650    DIDescriptor Element = Fields.getElement(i);
651    DIDerivedType DT = DIDerivedType(Element.getNode());
652    const char *fieldName = DT.getName();
653    if (strcmp(fieldName, "__forwarding") == 0)
654      forwardingField = Element;
655    else if (strcmp(fieldName, varName) == 0)
656      varField = Element;
657  }
658
659  assert(!varField.isNull() && "Can't find byref variable in Block struct");
660  assert(!forwardingField.isNull()
661         && "Can't find forwarding field in Block struct");
662
663  // Get the offsets for the forwarding field and the variable field.
664  unsigned int forwardingFieldOffset =
665    DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
666  unsigned int varFieldOffset =
667    DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
668
669  // Decode the original location, and use that as the start of the byref
670  // variable's location.
671  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
672  DIEBlock *Block = new DIEBlock();
673
674  if (Location.isReg()) {
675    if (Reg < 32)
676      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
677    else {
678      Reg = Reg - dwarf::DW_OP_reg0;
679      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
680      AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
681    }
682  } else {
683    if (Reg < 32)
684      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
685    else {
686      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
687      AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
688    }
689
690    AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
691  }
692
693  // If we started with a pointer to the __Block_byref... struct, then
694  // the first thing we need to do is dereference the pointer (DW_OP_deref).
695  if (isPointer)
696    AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
697
698  // Next add the offset for the '__forwarding' field:
699  // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
700  // adding the offset if it's 0.
701  if (forwardingFieldOffset > 0) {
702    AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
703    AddUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
704  }
705
706  // Now dereference the __forwarding field to get to the real __Block_byref
707  // struct:  DW_OP_deref.
708  AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
709
710  // Now that we've got the real __Block_byref... struct, add the offset
711  // for the variable's field to get to the location of the actual variable:
712  // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
713  if (varFieldOffset > 0) {
714    AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
715    AddUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
716  }
717
718  // Now attach the location information to the DIE.
719  AddBlock(Die, Attribute, 0, Block);
720}
721
722/// AddAddress - Add an address attribute to a die based on the location
723/// provided.
724void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
725                            const MachineLocation &Location) {
726  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
727  DIEBlock *Block = new DIEBlock();
728
729  if (Location.isReg()) {
730    if (Reg < 32) {
731      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
732    } else {
733      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
734      AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
735    }
736  } else {
737    if (Reg < 32) {
738      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
739    } else {
740      AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
741      AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
742    }
743
744    AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
745  }
746
747  AddBlock(Die, Attribute, 0, Block);
748}
749
750/// AddType - Add a new type attribute to the specified entity.
751void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
752  if (Ty.isNull())
753    return;
754
755  // Check for pre-existence.
756  DIEEntry *Slot = DW_Unit->getDIEEntry(Ty.getNode());
757
758  // If it exists then use the existing value.
759  if (Slot) {
760    Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
761    return;
762  }
763
764  // Set up proxy.
765  Slot = CreateDIEEntry();
766  DW_Unit->insertDIEEntry(Ty.getNode(), Slot);
767
768  // Construct type.
769  DIE *Buffer = new DIE(dwarf::DW_TAG_base_type);
770  if (Ty.isBasicType())
771    ConstructTypeDIE(DW_Unit, *Buffer, DIBasicType(Ty.getNode()));
772  else if (Ty.isCompositeType())
773    ConstructTypeDIE(DW_Unit, *Buffer, DICompositeType(Ty.getNode()));
774  else {
775    assert(Ty.isDerivedType() && "Unknown kind of DIType");
776    ConstructTypeDIE(DW_Unit, *Buffer, DIDerivedType(Ty.getNode()));
777  }
778
779  // Add debug information entry to entity and appropriate context.
780  DIE *Die = NULL;
781  DIDescriptor Context = Ty.getContext();
782  if (!Context.isNull())
783    Die = DW_Unit->getDIE(Context.getNode());
784
785  if (Die)
786    Die->AddChild(Buffer);
787  else
788    DW_Unit->AddDie(Buffer);
789  SetDIEEntry(Slot, Buffer);
790  Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
791}
792
793/// ConstructTypeDIE - Construct basic type die from DIBasicType.
794void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
795                                  DIBasicType BTy) {
796  // Get core information.
797  const char *Name = BTy.getName();
798  Buffer.setTag(dwarf::DW_TAG_base_type);
799  AddUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
800          BTy.getEncoding());
801
802  // Add name if not anonymous or intermediate type.
803  if (Name)
804    AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
805  uint64_t Size = BTy.getSizeInBits() >> 3;
806  AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
807}
808
809/// ConstructTypeDIE - Construct derived type die from DIDerivedType.
810void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
811                                  DIDerivedType DTy) {
812  // Get core information.
813  const char *Name = DTy.getName();
814  uint64_t Size = DTy.getSizeInBits() >> 3;
815  unsigned Tag = DTy.getTag();
816
817  // FIXME - Workaround for templates.
818  if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
819
820  Buffer.setTag(Tag);
821
822  // Map to main type, void will not have a type.
823  DIType FromTy = DTy.getTypeDerivedFrom();
824  AddType(DW_Unit, &Buffer, FromTy);
825
826  // Add name if not anonymous or intermediate type.
827  if (Name && Tag != dwarf::DW_TAG_pointer_type)
828    AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
829
830  // Add size if non-zero (derived types might be zero-sized.)
831  if (Size)
832    AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
833
834  // Add source line info if available and TyDesc is not a forward declaration.
835  if (!DTy.isForwardDecl() && Tag != dwarf::DW_TAG_pointer_type)
836    AddSourceLine(&Buffer, &DTy);
837}
838
839/// ConstructTypeDIE - Construct type DIE from DICompositeType.
840void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
841                                  DICompositeType CTy) {
842  // Get core information.
843  const char *Name = CTy.getName();
844
845  uint64_t Size = CTy.getSizeInBits() >> 3;
846  unsigned Tag = CTy.getTag();
847  Buffer.setTag(Tag);
848
849  switch (Tag) {
850  case dwarf::DW_TAG_vector_type:
851  case dwarf::DW_TAG_array_type:
852    ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
853    break;
854  case dwarf::DW_TAG_enumeration_type: {
855    DIArray Elements = CTy.getTypeArray();
856
857    // Add enumerators to enumeration type.
858    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
859      DIE *ElemDie = NULL;
860      DIEnumerator Enum(Elements.getElement(i).getNode());
861      if (!Enum.isNull()) {
862        ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
863        Buffer.AddChild(ElemDie);
864      }
865    }
866  }
867    break;
868  case dwarf::DW_TAG_subroutine_type: {
869    // Add return type.
870    DIArray Elements = CTy.getTypeArray();
871    DIDescriptor RTy = Elements.getElement(0);
872    AddType(DW_Unit, &Buffer, DIType(RTy.getNode()));
873
874    // Add prototype flag.
875    AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
876
877    // Add arguments.
878    for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
879      DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
880      DIDescriptor Ty = Elements.getElement(i);
881      AddType(DW_Unit, Arg, DIType(Ty.getNode()));
882      Buffer.AddChild(Arg);
883    }
884  }
885    break;
886  case dwarf::DW_TAG_structure_type:
887  case dwarf::DW_TAG_union_type:
888  case dwarf::DW_TAG_class_type: {
889    // Add elements to structure type.
890    DIArray Elements = CTy.getTypeArray();
891
892    // A forward struct declared type may not have elements available.
893    if (Elements.isNull())
894      break;
895
896    // Add elements to structure type.
897    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
898      DIDescriptor Element = Elements.getElement(i);
899      if (Element.isNull())
900        continue;
901      DIE *ElemDie = NULL;
902      if (Element.getTag() == dwarf::DW_TAG_subprogram)
903        ElemDie = CreateSubprogramDIE(DW_Unit,
904                                      DISubprogram(Element.getNode()));
905      else
906        ElemDie = CreateMemberDIE(DW_Unit,
907                                  DIDerivedType(Element.getNode()));
908      Buffer.AddChild(ElemDie);
909    }
910
911    if (CTy.isAppleBlockExtension())
912      AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
913
914    unsigned RLang = CTy.getRunTimeLang();
915    if (RLang)
916      AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
917              dwarf::DW_FORM_data1, RLang);
918    break;
919  }
920  default:
921    break;
922  }
923
924  // Add name if not anonymous or intermediate type.
925  if (Name)
926    AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
927
928  if (Tag == dwarf::DW_TAG_enumeration_type ||
929      Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
930    // Add size if non-zero (derived types might be zero-sized.)
931    if (Size)
932      AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
933    else {
934      // Add zero size if it is not a forward declaration.
935      if (CTy.isForwardDecl())
936        AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
937      else
938        AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
939    }
940
941    // Add source line info if available.
942    if (!CTy.isForwardDecl())
943      AddSourceLine(&Buffer, &CTy);
944  }
945}
946
947/// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
948void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
949  int64_t L = SR.getLo();
950  int64_t H = SR.getHi();
951  DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
952
953  AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
954  if (L)
955    AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
956  if (H)
957    AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
958
959  Buffer.AddChild(DW_Subrange);
960}
961
962/// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
963void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
964                                       DICompositeType *CTy) {
965  Buffer.setTag(dwarf::DW_TAG_array_type);
966  if (CTy->getTag() == dwarf::DW_TAG_vector_type)
967    AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
968
969  // Emit derived type.
970  AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
971  DIArray Elements = CTy->getTypeArray();
972
973  // Get an anonymous type for index type.
974  DIE *IdxTy = DW_Unit->getIndexTyDie();
975  if (!IdxTy) {
976    // Construct an anonymous type for index type.
977    IdxTy = new DIE(dwarf::DW_TAG_base_type);
978    AddUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
979    AddUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
980            dwarf::DW_ATE_signed);
981    DW_Unit->AddDie(IdxTy);
982    DW_Unit->setIndexTyDie(IdxTy);
983  }
984
985  // Add subranges to array type.
986  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
987    DIDescriptor Element = Elements.getElement(i);
988    if (Element.getTag() == dwarf::DW_TAG_subrange_type)
989      ConstructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
990  }
991}
992
993/// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
994DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
995  DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
996  const char *Name = ETy->getName();
997  AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
998  int64_t Value = ETy->getEnumValue();
999  AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1000  return Enumerator;
1001}
1002
1003/// CreateGlobalVariableDIE - Create new DIE using GV.
1004DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
1005                                         const DIGlobalVariable &GV) {
1006  // If the global variable was optmized out then no need to create debug info entry.
1007  if (!GV.getGlobal()) return NULL;
1008  if (!GV.getDisplayName()) return NULL;
1009
1010  DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1011  AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1012            GV.getDisplayName());
1013
1014  const char *LinkageName = GV.getLinkageName();
1015  if (LinkageName) {
1016    // Skip special LLVM prefix that is used to inform the asm printer to not
1017    // emit usual symbol prefix before the symbol name. This happens for
1018    // Objective-C symbol names and symbol whose name is replaced using GCC's
1019    // __asm__ attribute.
1020    if (LinkageName[0] == 1)
1021      LinkageName = &LinkageName[1];
1022    AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1023              LinkageName);
1024  }
1025  AddType(DW_Unit, GVDie, GV.getType());
1026  if (!GV.isLocalToUnit())
1027    AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1028  AddSourceLine(GVDie, &GV);
1029
1030  // Add address.
1031  DIEBlock *Block = new DIEBlock();
1032  AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1033  AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1034                 Asm->Mang->getMangledName(GV.getGlobal()));
1035  AddBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1036
1037  return GVDie;
1038}
1039
1040/// CreateMemberDIE - Create new member DIE.
1041DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1042  DIE *MemberDie = new DIE(DT.getTag());
1043  if (const char *Name = DT.getName())
1044    AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1045
1046  AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1047
1048  AddSourceLine(MemberDie, &DT);
1049
1050  DIEBlock *MemLocationDie = new DIEBlock();
1051  AddUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1052
1053  uint64_t Size = DT.getSizeInBits();
1054  uint64_t FieldSize = DT.getOriginalTypeSize();
1055
1056  if (Size != FieldSize) {
1057    // Handle bitfield.
1058    AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1059    AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1060
1061    uint64_t Offset = DT.getOffsetInBits();
1062    uint64_t FieldOffset = Offset;
1063    uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1064    uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1065    FieldOffset = (HiMark - FieldSize);
1066    Offset -= FieldOffset;
1067
1068    // Maybe we need to work from the other end.
1069    if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1070    AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1071
1072    // Here WD_AT_data_member_location points to the anonymous
1073    // field that includes this bit field.
1074    AddUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1075
1076  } else
1077    // This is not a bitfield.
1078    AddUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1079
1080  AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1081
1082  if (DT.isProtected())
1083    AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1084            dwarf::DW_ACCESS_protected);
1085  else if (DT.isPrivate())
1086    AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1087            dwarf::DW_ACCESS_private);
1088
1089  return MemberDie;
1090}
1091
1092/// CreateSubprogramDIE - Create new DIE using SP.
1093DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
1094                                     const DISubprogram &SP,
1095                                     bool IsConstructor,
1096                                     bool IsInlined) {
1097  DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1098
1099  const char * Name = SP.getName();
1100  AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1101
1102  const char *LinkageName = SP.getLinkageName();
1103  if (LinkageName) {
1104    // Skip special LLVM prefix that is used to inform the asm printer to not emit
1105    // usual symbol prefix before the symbol name. This happens for Objective-C
1106    // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
1107    if (LinkageName[0] == 1)
1108      LinkageName = &LinkageName[1];
1109    AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1110              LinkageName);
1111  }
1112  AddSourceLine(SPDie, &SP);
1113
1114  DICompositeType SPTy = SP.getType();
1115  DIArray Args = SPTy.getTypeArray();
1116
1117  // Add prototyped tag, if C or ObjC.
1118  unsigned Lang = SP.getCompileUnit().getLanguage();
1119  if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1120      Lang == dwarf::DW_LANG_ObjC)
1121    AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1122
1123  // Add Return Type.
1124  unsigned SPTag = SPTy.getTag();
1125  if (!IsConstructor) {
1126    if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1127      AddType(DW_Unit, SPDie, SPTy);
1128    else
1129      AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1130  }
1131
1132  if (!SP.isDefinition()) {
1133    AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1134
1135    // Add arguments. Do not add arguments for subprogram definition. They will
1136    // be handled through RecordVariable.
1137    if (SPTag == dwarf::DW_TAG_subroutine_type)
1138      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1139        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1140        AddType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1141        AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1142        SPDie->AddChild(Arg);
1143      }
1144  }
1145
1146  // DW_TAG_inlined_subroutine may refer to this DIE.
1147  DW_Unit->insertDIE(SP.getNode(), SPDie);
1148  return SPDie;
1149}
1150
1151/// FindCompileUnit - Get the compile unit for the given descriptor.
1152///
1153CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
1154  DenseMap<Value *, CompileUnit *>::const_iterator I =
1155    CompileUnitMap.find(Unit.getNode());
1156  assert(I != CompileUnitMap.end() && "Missing compile unit.");
1157  return *I->second;
1158}
1159
1160/// CreateDbgScopeVariable - Create a new scope variable.
1161///
1162DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1163  // Get the descriptor.
1164  const DIVariable &VD = DV->getVariable();
1165  const char *Name = VD.getName();
1166  if (!Name)
1167    return NULL;
1168
1169  // Translate tag to proper Dwarf tag.  The result variable is dropped for
1170  // now.
1171  unsigned Tag;
1172  switch (VD.getTag()) {
1173  case dwarf::DW_TAG_return_variable:
1174    return NULL;
1175  case dwarf::DW_TAG_arg_variable:
1176    Tag = dwarf::DW_TAG_formal_parameter;
1177    break;
1178  case dwarf::DW_TAG_auto_variable:    // fall thru
1179  default:
1180    Tag = dwarf::DW_TAG_variable;
1181    break;
1182  }
1183
1184  // Define variable debug information entry.
1185  DIE *VariableDie = new DIE(Tag);
1186  AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1187
1188  // Add source line info if available.
1189  AddSourceLine(VariableDie, &VD);
1190
1191  // Add variable type.
1192  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1193  // addresses instead.
1194  if (VD.isBlockByrefVariable())
1195    AddType(Unit, VariableDie, GetBlockByrefType(VD.getType(), Name));
1196  else
1197    AddType(Unit, VariableDie, VD.getType());
1198
1199  // Add variable address.
1200  // Variables for abstract instances of inlined functions don't get a
1201  // location.
1202  MachineLocation Location;
1203  Location.set(RI->getFrameRegister(*MF),
1204               RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1205
1206
1207  if (VD.hasComplexAddress())
1208    AddComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1209  else if (VD.isBlockByrefVariable())
1210    AddBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1211  else
1212    AddAddress(VariableDie, dwarf::DW_AT_location, Location);
1213
1214  return VariableDie;
1215}
1216
1217/// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1218/// Initialize scope and update scope hierarchy.
1219DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1220  MDNode *InlinedAt) {
1221  assert (N && "Invalid Scope encoding!");
1222  assert (MI && "Missing machine instruction!");
1223  bool GetConcreteScope = (MI && InlinedAt);
1224
1225  DbgScope *NScope = NULL;
1226
1227  if (InlinedAt)
1228    NScope = DbgScopeMap.lookup(InlinedAt);
1229  else
1230    NScope = DbgScopeMap.lookup(N);
1231  assert (NScope && "Unable to find working scope!");
1232
1233  if (NScope->getFirstInsn())
1234    return NScope;
1235
1236  DbgScope *Parent = NULL;
1237  if (GetConcreteScope) {
1238    DILocation IL(InlinedAt);
1239    Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1240                         IL.getOrigLocation().getNode());
1241    assert (Parent && "Unable to find Parent scope!");
1242    NScope->setParent(Parent);
1243    Parent->AddScope(NScope);
1244  } else if (DIDescriptor(N).isLexicalBlock()) {
1245    DILexicalBlock DB(N);
1246    if (!DB.getContext().isNull()) {
1247      Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1248      NScope->setParent(Parent);
1249      Parent->AddScope(NScope);
1250    }
1251  }
1252
1253  NScope->setFirstInsn(MI);
1254
1255  if (!Parent && !InlinedAt) {
1256    StringRef SPName = DISubprogram(N).getLinkageName();
1257    if (SPName == MF->getFunction()->getName())
1258      CurrentFnDbgScope = NScope;
1259  }
1260
1261  if (GetConcreteScope) {
1262    ConcreteScopes[InlinedAt] = NScope;
1263    getOrCreateAbstractScope(N);
1264  }
1265
1266  return NScope;
1267}
1268
1269DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1270  assert (N && "Invalid Scope encoding!");
1271
1272  DbgScope *AScope = AbstractScopes.lookup(N);
1273  if (AScope)
1274    return AScope;
1275
1276  DbgScope *Parent = NULL;
1277
1278  DIDescriptor Scope(N);
1279  if (Scope.isLexicalBlock()) {
1280    DILexicalBlock DB(N);
1281    DIDescriptor ParentDesc = DB.getContext();
1282    if (!ParentDesc.isNull())
1283      Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1284  }
1285
1286  AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1287
1288  if (Parent)
1289    Parent->AddScope(AScope);
1290  AScope->setAbstractScope();
1291  AbstractScopes[N] = AScope;
1292  if (DIDescriptor(N).isSubprogram())
1293    AbstractScopesList.push_back(AScope);
1294  return AScope;
1295}
1296
1297static DISubprogram getDISubprogram(MDNode *N) {
1298
1299  DIDescriptor D(N);
1300  if (D.isNull())
1301    return DISubprogram();
1302
1303  if (D.isCompileUnit())
1304    return DISubprogram();
1305
1306  if (D.isSubprogram())
1307    return DISubprogram(N);
1308
1309  if (D.isLexicalBlock())
1310    return getDISubprogram(DILexicalBlock(N).getContext().getNode());
1311
1312  llvm_unreachable("Unexpected Descriptor!");
1313}
1314
1315DIE *DwarfDebug::UpdateSubprogramScopeDIE(MDNode *SPNode) {
1316
1317 DIE *SPDie = ModuleCU->getDIE(SPNode);
1318 assert (SPDie && "Unable to find subprogram DIE!");
1319 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1320          DWLabel("func_begin", SubprogramCount));
1321 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1322          DWLabel("func_end", SubprogramCount));
1323 MachineLocation Location(RI->getFrameRegister(*MF));
1324 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1325
1326 if (!DISubprogram(SPNode).isLocalToUnit())
1327   AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1328
1329 // If there are global variables at this scope then add their dies.
1330 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(),
1331        SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
1332   MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
1333   if (!N) continue;
1334   DIGlobalVariable GV(N);
1335   if (GV.getContext().getNode() == SPNode) {
1336     DIE *ScopedGVDie = CreateGlobalVariableDIE(ModuleCU, GV);
1337     if (ScopedGVDie)
1338       SPDie->AddChild(ScopedGVDie);
1339   }
1340 }
1341 return SPDie;
1342}
1343
1344DIE *DwarfDebug::ConstructLexicalScopeDIE(DbgScope *Scope) {
1345  unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1346  unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1347
1348  // Ignore empty scopes.
1349  if (StartID == EndID && StartID != 0)
1350    return NULL;
1351
1352  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1353  if (Scope->isAbstractScope())
1354    return ScopeDIE;
1355
1356  AddLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1357           StartID ?
1358             DWLabel("label", StartID)
1359           : DWLabel("func_begin", SubprogramCount));
1360  AddLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1361           EndID ?
1362             DWLabel("label", EndID)
1363           : DWLabel("func_end", SubprogramCount));
1364
1365
1366
1367  return ScopeDIE;
1368}
1369
1370DIE *DwarfDebug::ConstructInlinedScopeDIE(DbgScope *Scope) {
1371  unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1372  unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1373  assert (StartID && "Invalid starting label for an inlined scope!");
1374  assert (EndID && "Invalid end label for an inlined scope!");
1375  // Ignore empty scopes.
1376  if (StartID == EndID && StartID != 0)
1377    return NULL;
1378
1379  DIScope DS(Scope->getScopeNode());
1380  if (DS.isNull())
1381    return NULL;
1382  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1383
1384  DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1385  DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1386  assert (OriginDIE && "Unable to find Origin DIE!");
1387  AddDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1388              dwarf::DW_FORM_ref4, OriginDIE);
1389
1390  AddLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1391           DWLabel("label", StartID));
1392  AddLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1393           DWLabel("label", EndID));
1394
1395  InlinedSubprogramDIEs.insert(OriginDIE);
1396
1397  // Track the start label for this inlined function.
1398  ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1399    I = InlineInfo.find(InlinedSP.getNode());
1400
1401  if (I == InlineInfo.end()) {
1402    InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID, ScopeDIE));
1403    InlinedSPNodes.push_back(InlinedSP.getNode());
1404  } else
1405    I->second.push_back(std::make_pair(StartID, ScopeDIE));
1406
1407  StringPool.insert(InlinedSP.getName());
1408  StringPool.insert(InlinedSP.getLinkageName());
1409  DILocation DL(Scope->getInlinedAt());
1410  AddUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1411  AddUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1412
1413  return ScopeDIE;
1414}
1415
1416DIE *DwarfDebug::ConstructVariableDIE(DbgVariable *DV,
1417                                      DbgScope *Scope, CompileUnit *Unit) {
1418  // Get the descriptor.
1419  const DIVariable &VD = DV->getVariable();
1420  const char *Name = VD.getName();
1421  if (!Name)
1422    return NULL;
1423
1424  // Translate tag to proper Dwarf tag.  The result variable is dropped for
1425  // now.
1426  unsigned Tag;
1427  switch (VD.getTag()) {
1428  case dwarf::DW_TAG_return_variable:
1429    return NULL;
1430  case dwarf::DW_TAG_arg_variable:
1431    Tag = dwarf::DW_TAG_formal_parameter;
1432    break;
1433  case dwarf::DW_TAG_auto_variable:    // fall thru
1434  default:
1435    Tag = dwarf::DW_TAG_variable;
1436    break;
1437  }
1438
1439  // Define variable debug information entry.
1440  DIE *VariableDie = new DIE(Tag);
1441
1442
1443  DIE *AbsDIE = NULL;
1444  if (DbgVariable *AV = DV->getAbstractVariable())
1445    AbsDIE = AV->getDIE();
1446
1447  if (AbsDIE) {
1448    DIScope DS(Scope->getScopeNode());
1449    DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1450    DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1451    (void) OriginSPDIE;
1452    assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1453    DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1454    assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1455    AddDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1456                dwarf::DW_FORM_ref4, AbsDIE);
1457  }
1458  else {
1459    AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1460    AddSourceLine(VariableDie, &VD);
1461
1462    // Add variable type.
1463    // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1464    // addresses instead.
1465    if (VD.isBlockByrefVariable())
1466      AddType(Unit, VariableDie, GetBlockByrefType(VD.getType(), Name));
1467    else
1468      AddType(Unit, VariableDie, VD.getType());
1469  }
1470
1471  // Add variable address.
1472  if (!Scope->isAbstractScope()) {
1473    MachineLocation Location;
1474    Location.set(RI->getFrameRegister(*MF),
1475                 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1476
1477
1478    if (VD.hasComplexAddress())
1479      AddComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1480    else if (VD.isBlockByrefVariable())
1481      AddBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1482    else
1483      AddAddress(VariableDie, dwarf::DW_AT_location, Location);
1484  }
1485  DV->setDIE(VariableDie);
1486  return VariableDie;
1487
1488}
1489DIE *DwarfDebug::ConstructScopeDIE(DbgScope *Scope) {
1490 if (!Scope)
1491  return NULL;
1492 DIScope DS(Scope->getScopeNode());
1493 if (DS.isNull())
1494   return NULL;
1495
1496 DIE *ScopeDIE = NULL;
1497 if (Scope->getInlinedAt())
1498   ScopeDIE = ConstructInlinedScopeDIE(Scope);
1499 else if (DS.isSubprogram()) {
1500   if (Scope->isAbstractScope())
1501     ScopeDIE = ModuleCU->getDIE(DS.getNode());
1502   else
1503     ScopeDIE = UpdateSubprogramScopeDIE(DS.getNode());
1504 }
1505 else {
1506   ScopeDIE = ConstructLexicalScopeDIE(Scope);
1507   if (!ScopeDIE) return NULL;
1508 }
1509
1510  // Add variables to scope.
1511  SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1512  for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1513    DIE *VariableDIE = ConstructVariableDIE(Variables[i], Scope, ModuleCU);
1514    if (VariableDIE)
1515      ScopeDIE->AddChild(VariableDIE);
1516  }
1517
1518  // Add nested scopes.
1519  SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1520  for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1521    // Define the Scope debug information entry.
1522    DIE *NestedDIE = ConstructScopeDIE(Scopes[j]);
1523    if (NestedDIE)
1524      ScopeDIE->AddChild(NestedDIE);
1525  }
1526  return ScopeDIE;
1527}
1528
1529/// GetOrCreateSourceID - Look up the source id with the given directory and
1530/// source file names. If none currently exists, create a new id and insert it
1531/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1532/// maps as well.
1533unsigned DwarfDebug::GetOrCreateSourceID(const char *DirName,
1534                                         const char *FileName) {
1535  unsigned DId;
1536  StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1537  if (DI != DirectoryIdMap.end()) {
1538    DId = DI->getValue();
1539  } else {
1540    DId = DirectoryNames.size() + 1;
1541    DirectoryIdMap[DirName] = DId;
1542    DirectoryNames.push_back(DirName);
1543  }
1544
1545  unsigned FId;
1546  StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1547  if (FI != SourceFileIdMap.end()) {
1548    FId = FI->getValue();
1549  } else {
1550    FId = SourceFileNames.size() + 1;
1551    SourceFileIdMap[FileName] = FId;
1552    SourceFileNames.push_back(FileName);
1553  }
1554
1555  DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1556    SourceIdMap.find(std::make_pair(DId, FId));
1557  if (SI != SourceIdMap.end())
1558    return SI->second;
1559
1560  unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
1561  SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1562  SourceIds.push_back(std::make_pair(DId, FId));
1563
1564  return SrcId;
1565}
1566
1567void DwarfDebug::ConstructCompileUnit(MDNode *N) {
1568  DICompileUnit DIUnit(N);
1569  const char *FN = DIUnit.getFilename();
1570  const char *Dir = DIUnit.getDirectory();
1571  unsigned ID = GetOrCreateSourceID(Dir, FN);
1572
1573  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1574  AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1575                   DWLabel("section_line", 0), DWLabel("section_line", 0),
1576                   false);
1577  AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1578            DIUnit.getProducer());
1579  AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1580          DIUnit.getLanguage());
1581  AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1582
1583  if (Dir)
1584    AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1585  if (DIUnit.isOptimized())
1586    AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1587
1588  if (const char *Flags = DIUnit.getFlags())
1589    AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1590
1591  unsigned RVer = DIUnit.getRunTimeVersion();
1592  if (RVer)
1593    AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1594            dwarf::DW_FORM_data1, RVer);
1595
1596  CompileUnit *Unit = new CompileUnit(ID, Die);
1597  if (!ModuleCU && DIUnit.isMain()) {
1598    // Use first compile unit marked as isMain as the compile unit
1599    // for this module.
1600    ModuleCU = Unit;
1601  }
1602
1603  CompileUnitMap[DIUnit.getNode()] = Unit;
1604  CompileUnits.push_back(Unit);
1605}
1606
1607void DwarfDebug::ConstructGlobalVariableDIE(MDNode *N) {
1608  DIGlobalVariable DI_GV(N);
1609
1610  // If debug information is malformed then ignore it.
1611  if (DI_GV.Verify() == false)
1612    return;
1613
1614  // Check for pre-existence.
1615  if (ModuleCU->getDIE(DI_GV.getNode()))
1616    return;
1617
1618  DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
1619
1620  // Add to map.
1621  ModuleCU->insertDIE(N, VariableDie);
1622
1623  // Add to context owner.
1624  ModuleCU->getCUDie()->AddChild(VariableDie);
1625
1626  // Expose as global. FIXME - need to check external flag.
1627  ModuleCU->AddGlobal(DI_GV.getName(), VariableDie);
1628  return;
1629}
1630
1631void DwarfDebug::ConstructSubprogram(MDNode *N) {
1632  DISubprogram SP(N);
1633
1634  // Check for pre-existence.
1635  if (ModuleCU->getDIE(N))
1636    return;
1637
1638  if (!SP.isDefinition())
1639    // This is a method declaration which will be handled while constructing
1640    // class type.
1641    return;
1642
1643  DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
1644
1645  // Add to map.
1646  ModuleCU->insertDIE(N, SubprogramDie);
1647
1648  // Add to context owner.
1649  ModuleCU->getCUDie()->AddChild(SubprogramDie);
1650
1651  // Expose as global.
1652  ModuleCU->AddGlobal(SP.getName(), SubprogramDie);
1653  return;
1654}
1655
1656/// BeginModule - Emit all Dwarf sections that should come prior to the
1657/// content. Create global DIEs and emit initial debug info sections.
1658/// This is inovked by the target AsmPrinter.
1659void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
1660  this->M = M;
1661
1662  if (TimePassesIsEnabled)
1663    DebugTimer->startTimer();
1664
1665  if (!MAI->doesSupportDebugInformation())
1666    return;
1667
1668  DebugInfoFinder DbgFinder;
1669  DbgFinder.processModule(*M);
1670
1671  // Create all the compile unit DIEs.
1672  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1673         E = DbgFinder.compile_unit_end(); I != E; ++I)
1674    ConstructCompileUnit(*I);
1675
1676  if (CompileUnits.empty()) {
1677    if (TimePassesIsEnabled)
1678      DebugTimer->stopTimer();
1679
1680    return;
1681  }
1682
1683  // If main compile unit for this module is not seen than randomly
1684  // select first compile unit.
1685  if (!ModuleCU)
1686    ModuleCU = CompileUnits[0];
1687
1688  // Create DIEs for each of the externally visible global variables.
1689  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1690         E = DbgFinder.global_variable_end(); I != E; ++I) {
1691    DIGlobalVariable GV(*I);
1692    if (GV.getContext().getNode() != GV.getCompileUnit().getNode())
1693      ScopedGVs.push_back(*I);
1694    else
1695      ConstructGlobalVariableDIE(*I);
1696  }
1697
1698  // Create DIEs for each subprogram.
1699  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1700         E = DbgFinder.subprogram_end(); I != E; ++I)
1701    ConstructSubprogram(*I);
1702
1703  MMI = mmi;
1704  shouldEmit = true;
1705  MMI->setDebugInfoAvailability(true);
1706
1707  // Prime section data.
1708  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1709
1710  // Print out .file directives to specify files for .loc directives. These are
1711  // printed out early so that they precede any .loc directives.
1712  if (MAI->hasDotLocAndDotFile()) {
1713    for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1714      // Remember source id starts at 1.
1715      std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1716      sys::Path FullPath(getSourceDirectoryName(Id.first));
1717      bool AppendOk =
1718        FullPath.appendComponent(getSourceFileName(Id.second));
1719      assert(AppendOk && "Could not append filename to directory!");
1720      AppendOk = false;
1721      Asm->EmitFile(i, FullPath.str());
1722      Asm->EOL();
1723    }
1724  }
1725
1726  // Emit initial sections
1727  EmitInitial();
1728
1729  if (TimePassesIsEnabled)
1730    DebugTimer->stopTimer();
1731}
1732
1733/// EndModule - Emit all Dwarf sections that should come after the content.
1734///
1735void DwarfDebug::EndModule() {
1736  if (!ModuleCU)
1737    return;
1738
1739  if (TimePassesIsEnabled)
1740    DebugTimer->startTimer();
1741
1742  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1743  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1744         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1745    DIE *ISP = *AI;
1746    AddUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1747  }
1748
1749  // Standard sections final addresses.
1750  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1751  EmitLabel("text_end", 0);
1752  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1753  EmitLabel("data_end", 0);
1754
1755  // End text sections.
1756  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1757    Asm->OutStreamer.SwitchSection(SectionMap[i]);
1758    EmitLabel("section_end", i);
1759  }
1760
1761  // Emit common frame information.
1762  EmitCommonDebugFrame();
1763
1764  // Emit function debug frame information
1765  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1766         E = DebugFrames.end(); I != E; ++I)
1767    EmitFunctionDebugFrame(*I);
1768
1769  // Compute DIE offsets and sizes.
1770  SizeAndOffsets();
1771
1772  // Emit all the DIEs into a debug info section
1773  EmitDebugInfo();
1774
1775  // Corresponding abbreviations into a abbrev section.
1776  EmitAbbreviations();
1777
1778  // Emit source line correspondence into a debug line section.
1779  EmitDebugLines();
1780
1781  // Emit info into a debug pubnames section.
1782  EmitDebugPubNames();
1783
1784  // Emit info into a debug str section.
1785  EmitDebugStr();
1786
1787  // Emit info into a debug loc section.
1788  EmitDebugLoc();
1789
1790  // Emit info into a debug aranges section.
1791  EmitDebugARanges();
1792
1793  // Emit info into a debug ranges section.
1794  EmitDebugRanges();
1795
1796  // Emit info into a debug macinfo section.
1797  EmitDebugMacInfo();
1798
1799  // Emit inline info.
1800  EmitDebugInlineInfo();
1801
1802  if (TimePassesIsEnabled)
1803    DebugTimer->stopTimer();
1804}
1805
1806/// findAbstractVariable - Find abstract variable, if any, associated with Var.
1807DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var, unsigned FrameIdx,
1808                                              DILocation &ScopeLoc) {
1809
1810  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1811  if (AbsDbgVariable)
1812    return AbsDbgVariable;
1813
1814  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1815  if (!Scope)
1816    return NULL;
1817
1818  AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1819  Scope->AddVariable(AbsDbgVariable);
1820  AbstractVariables[Var.getNode()] = AbsDbgVariable;
1821  return AbsDbgVariable;
1822}
1823
1824/// CollectVariableInfo - Populate DbgScope entries with variables' info.
1825void DwarfDebug::CollectVariableInfo() {
1826  if (!MMI) return;
1827
1828  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1829  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1830         VE = VMap.end(); VI != VE; ++VI) {
1831    MetadataBase *MB = VI->first;
1832    MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1833    if (!Var) continue;
1834    DIVariable DV (Var);
1835    std::pair< unsigned, MDNode *> VP = VI->second;
1836    DILocation ScopeLoc(VP.second);
1837
1838    DbgScope *Scope =
1839      ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1840    if (!Scope)
1841      Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1842    // If variable scope is not found then skip this variable.
1843    if (!Scope)
1844      continue;
1845
1846    DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1847    Scope->AddVariable(RegVar);
1848    if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, ScopeLoc))
1849      RegVar->setAbstractVariable(AbsDbgVariable);
1850  }
1851}
1852
1853/// BeginScope - Process beginning of a scope starting at Label.
1854void DwarfDebug::BeginScope(const MachineInstr *MI, unsigned Label) {
1855  InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1856  if (I == DbgScopeBeginMap.end())
1857    return;
1858  ScopeVector &SD = DbgScopeBeginMap[MI];
1859  for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1860       SDI != SDE; ++SDI)
1861    (*SDI)->setStartLabelID(Label);
1862}
1863
1864/// EndScope - Process end of a scope.
1865void DwarfDebug::EndScope(const MachineInstr *MI) {
1866  InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1867  if (I == DbgScopeEndMap.end())
1868    return;
1869
1870  unsigned Label = MMI->NextLabelID();
1871  Asm->printLabel(Label);
1872
1873  SmallVector<DbgScope *, 2> &SD = I->second;
1874  for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1875       SDI != SDE; ++SDI)
1876    (*SDI)->setEndLabelID(Label);
1877  return;
1878}
1879
1880/// createDbgScope - Create DbgScope for the scope.
1881void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1882
1883  if (!InlinedAt) {
1884    DbgScope *WScope = DbgScopeMap.lookup(Scope);
1885    if (WScope)
1886      return;
1887    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1888    DbgScopeMap.insert(std::make_pair(Scope, WScope));
1889    if (DIDescriptor(Scope).isLexicalBlock())
1890      createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
1891    return;
1892  }
1893
1894  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1895  if (WScope)
1896    return;
1897
1898  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1899  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1900  DILocation DL(InlinedAt);
1901  createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
1902}
1903
1904/// ExtractScopeInformation - Scan machine instructions in this function
1905/// and collect DbgScopes. Return true, if atleast one scope was found.
1906bool DwarfDebug::ExtractScopeInformation(MachineFunction *MF) {
1907  // If scope information was extracted using .dbg intrinsics then there is not
1908  // any need to extract these information by scanning each instruction.
1909  if (!DbgScopeMap.empty())
1910    return false;
1911
1912  // Scan each instruction and create scopes. First build working set of scopes.
1913  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1914       I != E; ++I) {
1915    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1916         II != IE; ++II) {
1917      const MachineInstr *MInsn = II;
1918      DebugLoc DL = MInsn->getDebugLoc();
1919      if (DL.isUnknown()) continue;
1920      DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1921      if (!DLT.Scope) continue;
1922      // There is no need to create another DIE for compile unit. For all
1923      // other scopes, create one DbgScope now. This will be translated
1924      // into a scope DIE at the end.
1925      if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1926      createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
1927    }
1928  }
1929
1930
1931  // Build scope hierarchy using working set of scopes.
1932  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1933       I != E; ++I) {
1934    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1935         II != IE; ++II) {
1936      const MachineInstr *MInsn = II;
1937      DebugLoc DL = MInsn->getDebugLoc();
1938      if (DL.isUnknown())  continue;
1939      DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1940      if (!DLT.Scope)  continue;
1941      // There is no need to create another DIE for compile unit. For all
1942      // other scopes, create one DbgScope now. This will be translated
1943      // into a scope DIE at the end.
1944      if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1945      DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
1946      Scope->setLastInsn(MInsn);
1947    }
1948  }
1949
1950  // If a scope's last instruction is not set then use its child scope's
1951  // last instruction as this scope's last instrunction.
1952  for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1953	 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1954    if (DI->second->isAbstractScope())
1955      continue;
1956    assert (DI->second->getFirstInsn() && "Invalid first instruction!");
1957    DI->second->FixInstructionMarkers();
1958    assert (DI->second->getLastInsn() && "Invalid last instruction!");
1959  }
1960
1961  // Each scope has first instruction and last instruction to mark beginning
1962  // and end of a scope respectively. Create an inverse map that list scopes
1963  // starts (and ends) with an instruction. One instruction may start (or end)
1964  // multiple scopes.
1965  for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1966	 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1967    DbgScope *S = DI->second;
1968    if (S->isAbstractScope())
1969      continue;
1970    const MachineInstr *MI = S->getFirstInsn();
1971    assert (MI && "DbgScope does not have first instruction!");
1972
1973    InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
1974    if (IDI != DbgScopeBeginMap.end())
1975      IDI->second.push_back(S);
1976    else
1977      DbgScopeBeginMap[MI].push_back(S);
1978
1979    MI = S->getLastInsn();
1980    assert (MI && "DbgScope does not have last instruction!");
1981    IDI = DbgScopeEndMap.find(MI);
1982    if (IDI != DbgScopeEndMap.end())
1983      IDI->second.push_back(S);
1984    else
1985      DbgScopeEndMap[MI].push_back(S);
1986  }
1987
1988  return !DbgScopeMap.empty();
1989}
1990
1991/// BeginFunction - Gather pre-function debug information.  Assumes being
1992/// emitted immediately after the function entry point.
1993void DwarfDebug::BeginFunction(MachineFunction *MF) {
1994  this->MF = MF;
1995
1996  if (!ShouldEmitDwarfDebug()) return;
1997
1998  if (TimePassesIsEnabled)
1999    DebugTimer->startTimer();
2000
2001  if (!ExtractScopeInformation(MF))
2002    return;
2003  CollectVariableInfo();
2004
2005  // Begin accumulating function debug information.
2006  MMI->BeginFunction(MF);
2007
2008  // Assumes in correct section after the entry point.
2009  EmitLabel("func_begin", ++SubprogramCount);
2010
2011  // Emit label for the implicitly defined dbg.stoppoint at the start of the
2012  // function.
2013  DebugLoc FDL = MF->getDefaultDebugLoc();
2014  if (!FDL.isUnknown()) {
2015    DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2016    unsigned LabelID = 0;
2017    DISubprogram SP = getDISubprogram(DLT.Scope);
2018    if (!SP.isNull())
2019      LabelID = RecordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2020    else
2021      LabelID = RecordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2022    Asm->printLabel(LabelID);
2023    O << '\n';
2024  }
2025  if (TimePassesIsEnabled)
2026    DebugTimer->stopTimer();
2027}
2028
2029/// EndFunction - Gather and emit post-function debug information.
2030///
2031void DwarfDebug::EndFunction(MachineFunction *MF) {
2032  if (!ShouldEmitDwarfDebug()) return;
2033
2034  if (TimePassesIsEnabled)
2035    DebugTimer->startTimer();
2036
2037  if (DbgScopeMap.empty())
2038    return;
2039
2040  // Define end label for subprogram.
2041  EmitLabel("func_end", SubprogramCount);
2042
2043  // Get function line info.
2044  if (!Lines.empty()) {
2045    // Get section line info.
2046    unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2047    if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2048    std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2049    // Append the function info to section info.
2050    SectionLineInfos.insert(SectionLineInfos.end(),
2051                            Lines.begin(), Lines.end());
2052  }
2053
2054  // Construct abstract scopes.
2055  for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2056         AE = AbstractScopesList.end(); AI != AE; ++AI)
2057    ConstructScopeDIE(*AI);
2058
2059  ConstructScopeDIE(CurrentFnDbgScope);
2060
2061  DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2062                                               MMI->getFrameMoves()));
2063
2064  // Clear debug info
2065  if (CurrentFnDbgScope) {
2066    CurrentFnDbgScope = NULL;
2067    DbgScopeMap.clear();
2068    DbgScopeBeginMap.clear();
2069    DbgScopeEndMap.clear();
2070    ConcreteScopes.clear();
2071    AbstractScopesList.clear();
2072  }
2073
2074  Lines.clear();
2075
2076  if (TimePassesIsEnabled)
2077    DebugTimer->stopTimer();
2078}
2079
2080/// RecordSourceLine - Records location information and associates it with a
2081/// label. Returns a unique label ID used to generate a label and provide
2082/// correspondence to the source line list.
2083unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
2084                                      MDNode *S) {
2085  if (!MMI)
2086    return 0;
2087
2088  if (TimePassesIsEnabled)
2089    DebugTimer->startTimer();
2090
2091  const char *Dir = NULL;
2092  const char *Fn = NULL;
2093
2094  DIDescriptor Scope(S);
2095  if (Scope.isCompileUnit()) {
2096    DICompileUnit CU(S);
2097    Dir = CU.getDirectory();
2098    Fn = CU.getFilename();
2099  } else if (Scope.isSubprogram()) {
2100    DISubprogram SP(S);
2101    Dir = SP.getDirectory();
2102    Fn = SP.getFilename();
2103  } else if (Scope.isLexicalBlock()) {
2104    DILexicalBlock DB(S);
2105    Dir = DB.getDirectory();
2106    Fn = DB.getFilename();
2107  } else
2108    assert (0 && "Unexpected scope info");
2109
2110  unsigned Src = GetOrCreateSourceID(Dir, Fn);
2111  unsigned ID = MMI->NextLabelID();
2112  Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2113
2114  if (TimePassesIsEnabled)
2115    DebugTimer->stopTimer();
2116
2117  return ID;
2118}
2119
2120/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2121/// timed. Look up the source id with the given directory and source file
2122/// names. If none currently exists, create a new id and insert it in the
2123/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2124/// well.
2125unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2126                                         const std::string &FileName) {
2127  if (TimePassesIsEnabled)
2128    DebugTimer->startTimer();
2129
2130  unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2131
2132  if (TimePassesIsEnabled)
2133    DebugTimer->stopTimer();
2134
2135  return SrcId;
2136}
2137
2138//===----------------------------------------------------------------------===//
2139// Emit Methods
2140//===----------------------------------------------------------------------===//
2141
2142/// SizeAndOffsetDie - Compute the size and offset of a DIE.
2143///
2144unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2145  // Get the children.
2146  const std::vector<DIE *> &Children = Die->getChildren();
2147
2148  // If not last sibling and has children then add sibling offset attribute.
2149  if (!Last && !Children.empty()) Die->AddSiblingOffset();
2150
2151  // Record the abbreviation.
2152  AssignAbbrevNumber(Die->getAbbrev());
2153
2154  // Get the abbreviation for this DIE.
2155  unsigned AbbrevNumber = Die->getAbbrevNumber();
2156  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2157
2158  // Set DIE offset
2159  Die->setOffset(Offset);
2160
2161  // Start the size with the size of abbreviation code.
2162  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2163
2164  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2165  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2166
2167  // Size the DIE attribute values.
2168  for (unsigned i = 0, N = Values.size(); i < N; ++i)
2169    // Size attribute value.
2170    Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2171
2172  // Size the DIE children if any.
2173  if (!Children.empty()) {
2174    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2175           "Children flag not set");
2176
2177    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2178      Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2179
2180    // End of children marker.
2181    Offset += sizeof(int8_t);
2182  }
2183
2184  Die->setSize(Offset - Die->getOffset());
2185  return Offset;
2186}
2187
2188/// SizeAndOffsets - Compute the size and offset of all the DIEs.
2189///
2190void DwarfDebug::SizeAndOffsets() {
2191  // Compute size of compile unit header.
2192  static unsigned Offset =
2193    sizeof(int32_t) + // Length of Compilation Unit Info
2194    sizeof(int16_t) + // DWARF version number
2195    sizeof(int32_t) + // Offset Into Abbrev. Section
2196    sizeof(int8_t);   // Pointer Size (in bytes)
2197
2198  SizeAndOffsetDie(ModuleCU->getCUDie(), Offset, true);
2199  CompileUnitOffsets[ModuleCU] = 0;
2200}
2201
2202/// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
2203/// tools to recognize the object file contains Dwarf information.
2204void DwarfDebug::EmitInitial() {
2205  // Check to see if we already emitted intial headers.
2206  if (didInitial) return;
2207  didInitial = true;
2208
2209  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2210
2211  // Dwarf sections base addresses.
2212  if (MAI->doesDwarfRequireFrameSection()) {
2213    Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2214    EmitLabel("section_debug_frame", 0);
2215  }
2216
2217  Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2218  EmitLabel("section_info", 0);
2219  Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2220  EmitLabel("section_abbrev", 0);
2221  Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2222  EmitLabel("section_aranges", 0);
2223
2224  if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2225    Asm->OutStreamer.SwitchSection(LineInfoDirective);
2226    EmitLabel("section_macinfo", 0);
2227  }
2228
2229  Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2230  EmitLabel("section_line", 0);
2231  Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2232  EmitLabel("section_loc", 0);
2233  Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2234  EmitLabel("section_pubnames", 0);
2235  Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2236  EmitLabel("section_str", 0);
2237  Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2238  EmitLabel("section_ranges", 0);
2239
2240  Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2241  EmitLabel("text_begin", 0);
2242  Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2243  EmitLabel("data_begin", 0);
2244}
2245
2246/// EmitDIE - Recusively Emits a debug information entry.
2247///
2248void DwarfDebug::EmitDIE(DIE *Die) {
2249  // Get the abbreviation for this DIE.
2250  unsigned AbbrevNumber = Die->getAbbrevNumber();
2251  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2252
2253  Asm->EOL();
2254
2255  // Emit the code (index) for the abbreviation.
2256  Asm->EmitULEB128Bytes(AbbrevNumber);
2257
2258  if (Asm->isVerbose())
2259    Asm->EOL(std::string("Abbrev [" +
2260                         utostr(AbbrevNumber) +
2261                         "] 0x" + utohexstr(Die->getOffset()) +
2262                         ":0x" + utohexstr(Die->getSize()) + " " +
2263                         dwarf::TagString(Abbrev->getTag())));
2264  else
2265    Asm->EOL();
2266
2267  SmallVector<DIEValue*, 32> &Values = Die->getValues();
2268  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2269
2270  // Emit the DIE attribute values.
2271  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2272    unsigned Attr = AbbrevData[i].getAttribute();
2273    unsigned Form = AbbrevData[i].getForm();
2274    assert(Form && "Too many attributes for DIE (check abbreviation)");
2275
2276    switch (Attr) {
2277    case dwarf::DW_AT_sibling:
2278      Asm->EmitInt32(Die->SiblingOffset());
2279      break;
2280    case dwarf::DW_AT_abstract_origin: {
2281      DIEEntry *E = cast<DIEEntry>(Values[i]);
2282      DIE *Origin = E->getEntry();
2283      unsigned Addr = Origin->getOffset();
2284      Asm->EmitInt32(Addr);
2285      break;
2286    }
2287    default:
2288      // Emit an attribute using the defined form.
2289      Values[i]->EmitValue(this, Form);
2290      break;
2291    }
2292
2293    Asm->EOL(dwarf::AttributeString(Attr));
2294  }
2295
2296  // Emit the DIE children if any.
2297  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2298    const std::vector<DIE *> &Children = Die->getChildren();
2299
2300    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2301      EmitDIE(Children[j]);
2302
2303    Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2304  }
2305}
2306
2307/// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2308///
2309void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
2310  DIE *Die = Unit->getCUDie();
2311
2312  // Emit the compile units header.
2313  EmitLabel("info_begin", Unit->getID());
2314
2315  // Emit size of content not including length itself
2316  unsigned ContentSize = Die->getSize() +
2317    sizeof(int16_t) + // DWARF version number
2318    sizeof(int32_t) + // Offset Into Abbrev. Section
2319    sizeof(int8_t) +  // Pointer Size (in bytes)
2320    sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2321
2322  Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
2323  Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2324  EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2325  Asm->EOL("Offset Into Abbrev. Section");
2326  Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2327
2328  EmitDIE(Die);
2329  // FIXME - extra padding for gdb bug.
2330  Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2331  Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2332  Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2333  Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2334  EmitLabel("info_end", Unit->getID());
2335
2336  Asm->EOL();
2337}
2338
2339void DwarfDebug::EmitDebugInfo() {
2340  // Start debug info section.
2341  Asm->OutStreamer.SwitchSection(
2342                            Asm->getObjFileLowering().getDwarfInfoSection());
2343
2344  EmitDebugInfoPerCU(ModuleCU);
2345}
2346
2347/// EmitAbbreviations - Emit the abbreviation section.
2348///
2349void DwarfDebug::EmitAbbreviations() const {
2350  // Check to see if it is worth the effort.
2351  if (!Abbreviations.empty()) {
2352    // Start the debug abbrev section.
2353    Asm->OutStreamer.SwitchSection(
2354                            Asm->getObjFileLowering().getDwarfAbbrevSection());
2355
2356    EmitLabel("abbrev_begin", 0);
2357
2358    // For each abbrevation.
2359    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2360      // Get abbreviation data
2361      const DIEAbbrev *Abbrev = Abbreviations[i];
2362
2363      // Emit the abbrevations code (base 1 index.)
2364      Asm->EmitULEB128Bytes(Abbrev->getNumber());
2365      Asm->EOL("Abbreviation Code");
2366
2367      // Emit the abbreviations data.
2368      Abbrev->Emit(Asm);
2369
2370      Asm->EOL();
2371    }
2372
2373    // Mark end of abbreviations.
2374    Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2375
2376    EmitLabel("abbrev_end", 0);
2377    Asm->EOL();
2378  }
2379}
2380
2381/// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2382/// the line matrix.
2383///
2384void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2385  // Define last address of section.
2386  Asm->EmitInt8(0); Asm->EOL("Extended Op");
2387  Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2388  Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2389  EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2390
2391  // Mark end of matrix.
2392  Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2393  Asm->EmitULEB128Bytes(1); Asm->EOL();
2394  Asm->EmitInt8(1); Asm->EOL();
2395}
2396
2397/// EmitDebugLines - Emit source line information.
2398///
2399void DwarfDebug::EmitDebugLines() {
2400  // If the target is using .loc/.file, the assembler will be emitting the
2401  // .debug_line table automatically.
2402  if (MAI->hasDotLocAndDotFile())
2403    return;
2404
2405  // Minimum line delta, thus ranging from -10..(255-10).
2406  const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2407  // Maximum line delta, thus ranging from -10..(255-10).
2408  const int MaxLineDelta = 255 + MinLineDelta;
2409
2410  // Start the dwarf line section.
2411  Asm->OutStreamer.SwitchSection(
2412                            Asm->getObjFileLowering().getDwarfLineSection());
2413
2414  // Construct the section header.
2415  EmitDifference("line_end", 0, "line_begin", 0, true);
2416  Asm->EOL("Length of Source Line Info");
2417  EmitLabel("line_begin", 0);
2418
2419  Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2420
2421  EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2422  Asm->EOL("Prolog Length");
2423  EmitLabel("line_prolog_begin", 0);
2424
2425  Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2426
2427  Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2428
2429  Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2430
2431  Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2432
2433  Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2434
2435  // Line number standard opcode encodings argument count
2436  Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2437  Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2438  Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2439  Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2440  Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2441  Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2442  Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2443  Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2444  Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2445
2446  // Emit directories.
2447  for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2448    Asm->EmitString(getSourceDirectoryName(DI));
2449    Asm->EOL("Directory");
2450  }
2451
2452  Asm->EmitInt8(0); Asm->EOL("End of directories");
2453
2454  // Emit files.
2455  for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2456    // Remember source id starts at 1.
2457    std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2458    Asm->EmitString(getSourceFileName(Id.second));
2459    Asm->EOL("Source");
2460    Asm->EmitULEB128Bytes(Id.first);
2461    Asm->EOL("Directory #");
2462    Asm->EmitULEB128Bytes(0);
2463    Asm->EOL("Mod date");
2464    Asm->EmitULEB128Bytes(0);
2465    Asm->EOL("File size");
2466  }
2467
2468  Asm->EmitInt8(0); Asm->EOL("End of files");
2469
2470  EmitLabel("line_prolog_end", 0);
2471
2472  // A sequence for each text section.
2473  unsigned SecSrcLinesSize = SectionSourceLines.size();
2474
2475  for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2476    // Isolate current sections line info.
2477    const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2478
2479    /*if (Asm->isVerbose()) {
2480      const MCSection *S = SectionMap[j + 1];
2481      O << '\t' << MAI->getCommentString() << " Section"
2482        << S->getName() << '\n';
2483    }*/
2484    Asm->EOL();
2485
2486    // Dwarf assumes we start with first line of first source file.
2487    unsigned Source = 1;
2488    unsigned Line = 1;
2489
2490    // Construct rows of the address, source, line, column matrix.
2491    for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2492      const SrcLineInfo &LineInfo = LineInfos[i];
2493      unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2494      if (!LabelID) continue;
2495
2496      if (LineInfo.getLine() == 0) continue;
2497
2498      if (!Asm->isVerbose())
2499        Asm->EOL();
2500      else {
2501        std::pair<unsigned, unsigned> SourceID =
2502          getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2503        O << '\t' << MAI->getCommentString() << ' '
2504          << getSourceDirectoryName(SourceID.first) << ' '
2505          << getSourceFileName(SourceID.second)
2506          <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2507      }
2508
2509      // Define the line address.
2510      Asm->EmitInt8(0); Asm->EOL("Extended Op");
2511      Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2512      Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2513      EmitReference("label",  LabelID); Asm->EOL("Location label");
2514
2515      // If change of source, then switch to the new source.
2516      if (Source != LineInfo.getSourceID()) {
2517        Source = LineInfo.getSourceID();
2518        Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2519        Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2520      }
2521
2522      // If change of line.
2523      if (Line != LineInfo.getLine()) {
2524        // Determine offset.
2525        int Offset = LineInfo.getLine() - Line;
2526        int Delta = Offset - MinLineDelta;
2527
2528        // Update line.
2529        Line = LineInfo.getLine();
2530
2531        // If delta is small enough and in range...
2532        if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2533          // ... then use fast opcode.
2534          Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2535        } else {
2536          // ... otherwise use long hand.
2537          Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2538          Asm->EOL("DW_LNS_advance_line");
2539          Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2540          Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2541        }
2542      } else {
2543        // Copy the previous row (different address or source)
2544        Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2545      }
2546    }
2547
2548    EmitEndOfLineMatrix(j + 1);
2549  }
2550
2551  if (SecSrcLinesSize == 0)
2552    // Because we're emitting a debug_line section, we still need a line
2553    // table. The linker and friends expect it to exist. If there's nothing to
2554    // put into it, emit an empty table.
2555    EmitEndOfLineMatrix(1);
2556
2557  EmitLabel("line_end", 0);
2558  Asm->EOL();
2559}
2560
2561/// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2562///
2563void DwarfDebug::EmitCommonDebugFrame() {
2564  if (!MAI->doesDwarfRequireFrameSection())
2565    return;
2566
2567  int stackGrowth =
2568    Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2569      TargetFrameInfo::StackGrowsUp ?
2570    TD->getPointerSize() : -TD->getPointerSize();
2571
2572  // Start the dwarf frame section.
2573  Asm->OutStreamer.SwitchSection(
2574                              Asm->getObjFileLowering().getDwarfFrameSection());
2575
2576  EmitLabel("debug_frame_common", 0);
2577  EmitDifference("debug_frame_common_end", 0,
2578                 "debug_frame_common_begin", 0, true);
2579  Asm->EOL("Length of Common Information Entry");
2580
2581  EmitLabel("debug_frame_common_begin", 0);
2582  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2583  Asm->EOL("CIE Identifier Tag");
2584  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2585  Asm->EOL("CIE Version");
2586  Asm->EmitString("");
2587  Asm->EOL("CIE Augmentation");
2588  Asm->EmitULEB128Bytes(1);
2589  Asm->EOL("CIE Code Alignment Factor");
2590  Asm->EmitSLEB128Bytes(stackGrowth);
2591  Asm->EOL("CIE Data Alignment Factor");
2592  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2593  Asm->EOL("CIE RA Column");
2594
2595  std::vector<MachineMove> Moves;
2596  RI->getInitialFrameState(Moves);
2597
2598  EmitFrameMoves(NULL, 0, Moves, false);
2599
2600  Asm->EmitAlignment(2, 0, 0, false);
2601  EmitLabel("debug_frame_common_end", 0);
2602
2603  Asm->EOL();
2604}
2605
2606/// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2607/// section.
2608void
2609DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2610  if (!MAI->doesDwarfRequireFrameSection())
2611    return;
2612
2613  // Start the dwarf frame section.
2614  Asm->OutStreamer.SwitchSection(
2615                              Asm->getObjFileLowering().getDwarfFrameSection());
2616
2617  EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2618                 "debug_frame_begin", DebugFrameInfo.Number, true);
2619  Asm->EOL("Length of Frame Information Entry");
2620
2621  EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2622
2623  EmitSectionOffset("debug_frame_common", "section_debug_frame",
2624                    0, 0, true, false);
2625  Asm->EOL("FDE CIE offset");
2626
2627  EmitReference("func_begin", DebugFrameInfo.Number);
2628  Asm->EOL("FDE initial location");
2629  EmitDifference("func_end", DebugFrameInfo.Number,
2630                 "func_begin", DebugFrameInfo.Number);
2631  Asm->EOL("FDE address range");
2632
2633  EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2634                 false);
2635
2636  Asm->EmitAlignment(2, 0, 0, false);
2637  EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2638
2639  Asm->EOL();
2640}
2641
2642void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2643  EmitDifference("pubnames_end", Unit->getID(),
2644                 "pubnames_begin", Unit->getID(), true);
2645  Asm->EOL("Length of Public Names Info");
2646
2647  EmitLabel("pubnames_begin", Unit->getID());
2648
2649  Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2650
2651  EmitSectionOffset("info_begin", "section_info",
2652                    Unit->getID(), 0, true, false);
2653  Asm->EOL("Offset of Compilation Unit Info");
2654
2655  EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2656                 true);
2657  Asm->EOL("Compilation Unit Length");
2658
2659  StringMap<DIE*> &Globals = Unit->getGlobals();
2660  for (StringMap<DIE*>::const_iterator
2661         GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2662    const char *Name = GI->getKeyData();
2663    DIE * Entity = GI->second;
2664
2665    Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2666    Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2667  }
2668
2669  Asm->EmitInt32(0); Asm->EOL("End Mark");
2670  EmitLabel("pubnames_end", Unit->getID());
2671
2672  Asm->EOL();
2673}
2674
2675/// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2676///
2677void DwarfDebug::EmitDebugPubNames() {
2678  // Start the dwarf pubnames section.
2679  Asm->OutStreamer.SwitchSection(
2680                          Asm->getObjFileLowering().getDwarfPubNamesSection());
2681
2682  EmitDebugPubNamesPerCU(ModuleCU);
2683}
2684
2685/// EmitDebugStr - Emit visible names into a debug str section.
2686///
2687void DwarfDebug::EmitDebugStr() {
2688  // Check to see if it is worth the effort.
2689  if (!StringPool.empty()) {
2690    // Start the dwarf str section.
2691    Asm->OutStreamer.SwitchSection(
2692                                Asm->getObjFileLowering().getDwarfStrSection());
2693
2694    // For each of strings in the string pool.
2695    for (unsigned StringID = 1, N = StringPool.size();
2696         StringID <= N; ++StringID) {
2697      // Emit a label for reference from debug information entries.
2698      EmitLabel("string", StringID);
2699
2700      // Emit the string itself.
2701      const std::string &String = StringPool[StringID];
2702      Asm->EmitString(String); Asm->EOL();
2703    }
2704
2705    Asm->EOL();
2706  }
2707}
2708
2709/// EmitDebugLoc - Emit visible names into a debug loc section.
2710///
2711void DwarfDebug::EmitDebugLoc() {
2712  // Start the dwarf loc section.
2713  Asm->OutStreamer.SwitchSection(
2714                              Asm->getObjFileLowering().getDwarfLocSection());
2715  Asm->EOL();
2716}
2717
2718/// EmitDebugARanges - Emit visible names into a debug aranges section.
2719///
2720void DwarfDebug::EmitDebugARanges() {
2721  // Start the dwarf aranges section.
2722  Asm->OutStreamer.SwitchSection(
2723                          Asm->getObjFileLowering().getDwarfARangesSection());
2724
2725  // FIXME - Mock up
2726#if 0
2727  CompileUnit *Unit = GetBaseCompileUnit();
2728
2729  // Don't include size of length
2730  Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2731
2732  Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2733
2734  EmitReference("info_begin", Unit->getID());
2735  Asm->EOL("Offset of Compilation Unit Info");
2736
2737  Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2738
2739  Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2740
2741  Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
2742  Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
2743
2744  // Range 1
2745  EmitReference("text_begin", 0); Asm->EOL("Address");
2746  EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2747
2748  Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2749  Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2750#endif
2751
2752  Asm->EOL();
2753}
2754
2755/// EmitDebugRanges - Emit visible names into a debug ranges section.
2756///
2757void DwarfDebug::EmitDebugRanges() {
2758  // Start the dwarf ranges section.
2759  Asm->OutStreamer.SwitchSection(
2760                            Asm->getObjFileLowering().getDwarfRangesSection());
2761  Asm->EOL();
2762}
2763
2764/// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2765///
2766void DwarfDebug::EmitDebugMacInfo() {
2767  if (const MCSection *LineInfo =
2768      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2769    // Start the dwarf macinfo section.
2770    Asm->OutStreamer.SwitchSection(LineInfo);
2771    Asm->EOL();
2772  }
2773}
2774
2775/// EmitDebugInlineInfo - Emit inline info using following format.
2776/// Section Header:
2777/// 1. length of section
2778/// 2. Dwarf version number
2779/// 3. address size.
2780///
2781/// Entries (one "entry" for each function that was inlined):
2782///
2783/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2784///   otherwise offset into __debug_str for regular function name.
2785/// 2. offset into __debug_str section for regular function name.
2786/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2787/// instances for the function.
2788///
2789/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2790/// inlined instance; the die_offset points to the inlined_subroutine die in the
2791/// __debug_info section, and the low_pc is the starting address for the
2792/// inlining instance.
2793void DwarfDebug::EmitDebugInlineInfo() {
2794  if (!MAI->doesDwarfUsesInlineInfoSection())
2795    return;
2796
2797  if (!ModuleCU)
2798    return;
2799
2800  Asm->OutStreamer.SwitchSection(
2801                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
2802  Asm->EOL();
2803  EmitDifference("debug_inlined_end", 1,
2804                 "debug_inlined_begin", 1, true);
2805  Asm->EOL("Length of Debug Inlined Information Entry");
2806
2807  EmitLabel("debug_inlined_begin", 1);
2808
2809  Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2810  Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2811
2812  for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2813         E = InlinedSPNodes.end(); I != E; ++I) {
2814
2815//  for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
2816    //        I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2817    MDNode *Node = *I;
2818    ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II = InlineInfo.find(Node);
2819    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2820    DISubprogram SP(Node);
2821    const char *LName = SP.getLinkageName();
2822    const char *Name = SP.getName();
2823
2824    if (!LName)
2825      Asm->EmitString(Name);
2826    else {
2827      // Skip special LLVM prefix that is used to inform the asm printer to not
2828      // emit usual symbol prefix before the symbol name. This happens for
2829      // Objective-C symbol names and symbol whose name is replaced using GCC's
2830      // __asm__ attribute.
2831      if (LName[0] == 1)
2832        LName = &LName[1];
2833//      Asm->EmitString(LName);
2834      EmitSectionOffset("string", "section_str",
2835                        StringPool.idFor(LName), false, true);
2836
2837    }
2838    Asm->EOL("MIPS linkage name");
2839//    Asm->EmitString(Name);
2840    EmitSectionOffset("string", "section_str",
2841                      StringPool.idFor(Name), false, true);
2842    Asm->EOL("Function name");
2843    Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2844
2845    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2846           LE = Labels.end(); LI != LE; ++LI) {
2847      DIE *SP = LI->second;
2848      Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2849
2850      if (TD->getPointerSize() == sizeof(int32_t))
2851        O << MAI->getData32bitsDirective();
2852      else
2853        O << MAI->getData64bitsDirective();
2854
2855      PrintLabelName("label", LI->first); Asm->EOL("low_pc");
2856    }
2857  }
2858
2859  EmitLabel("debug_inlined_end", 1);
2860  Asm->EOL();
2861}
2862