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