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