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