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