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