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