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