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