DwarfDebug.cpp revision ecca2e6a2e156bc1197e79138382f34457f67a44
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/STLExtras.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/ValueHandle.h"
33#include "llvm/Support/FormattedStream.h"
34#include "llvm/Support/Timer.h"
35#include "llvm/System/Path.h"
36using namespace llvm;
37
38//===----------------------------------------------------------------------===//
39
40/// Configuration values for initial hash set sizes (log2).
41///
42static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
43
44namespace llvm {
45
46//===----------------------------------------------------------------------===//
47/// CompileUnit - This dwarf writer support class manages information associate
48/// with a source file.
49class CompileUnit {
50  /// ID - File identifier for source.
51  ///
52  unsigned ID;
53
54  /// Die - Compile unit debug information entry.
55  ///
56  const OwningPtr<DIE> CUDie;
57
58  /// IndexTyDie - An anonymous type for index type.  Owned by CUDie.
59  DIE *IndexTyDie;
60
61  /// GVToDieMap - Tracks the mapping of unit level debug informaton
62  /// variables to debug information entries.
63  /// FIXME : Rename GVToDieMap -> NodeToDieMap
64  DenseMap<MDNode *, DIE *> GVToDieMap;
65
66  /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
67  /// descriptors to debug information entries using a DIEEntry proxy.
68  /// FIXME : Rename
69  DenseMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
70
71  /// Globals - A map of globally visible named entities for this unit.
72  ///
73  StringMap<DIE*> Globals;
74
75  /// GlobalTypes - A map of globally visible types for this unit.
76  ///
77  StringMap<DIE*> GlobalTypes;
78
79public:
80  CompileUnit(unsigned I, DIE *D)
81    : ID(I), CUDie(D), IndexTyDie(0) {}
82
83  // Accessors.
84  unsigned getID()                  const { return ID; }
85  DIE* getCUDie()                   const { return CUDie.get(); }
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 *const AbstractVar;    // Abstract variable for this variable.
152  DIE *TheDIE;
153public:
154  // AbsVar may be NULL.
155  DbgVariable(DIVariable V, unsigned I, DbgVariable *AbsVar)
156    : Var(V), FrameIndex(I), AbstractVar(AbsVar), TheDIE(0)  {}
157
158  // Accessors.
159  DIVariable getVariable()           const { return Var; }
160  unsigned getFrameIndex()           const { return FrameIndex; }
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  // Scopes defined in scope.  Contents not owned.
180  SmallVector<DbgScope *, 4> Scopes;
181  // Variables declared in scope.  Contents owned.
182  SmallVector<DbgVariable *, 8> Variables;
183
184  // Private state for dump()
185  mutable unsigned IndentLevel;
186public:
187  DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
188    : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
189      StartLabel(0), EndLabel(0),
190      LastInsn(0), FirstInsn(0), IndentLevel(0) {}
191  virtual ~DbgScope();
192
193  // Accessors.
194  DbgScope *getParent()          const { return Parent; }
195  void setParent(DbgScope *P)          { Parent = P; }
196  DIDescriptor getDesc()         const { return Desc; }
197  MDNode *getInlinedAt()         const {
198    return InlinedAtLocation;
199  }
200  MDNode *getScopeNode()         const { return Desc.getNode(); }
201  MCSymbol *getStartLabel()      const { return StartLabel; }
202  MCSymbol *getEndLabel()        const { return EndLabel; }
203  const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
204  const SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
205  void setStartLabel(MCSymbol *S) { StartLabel = S; }
206  void setEndLabel(MCSymbol *E)   { EndLabel = E; }
207  void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
208  const MachineInstr *getLastInsn()      { return LastInsn; }
209  void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
210  void setAbstractScope() { AbstractScope = true; }
211  bool isAbstractScope() const { return AbstractScope; }
212  const MachineInstr *getFirstInsn()      { return FirstInsn; }
213
214  /// addScope - Add a scope to the scope.
215  ///
216  void addScope(DbgScope *S) { Scopes.push_back(S); }
217
218  /// addVariable - Add a variable to the scope.
219  ///
220  void addVariable(DbgVariable *V) { Variables.push_back(V); }
221
222  void fixInstructionMarkers(DenseMap<const MachineInstr *,
223                             unsigned> &MIIndexMap) {
224    assert (getFirstInsn() && "First instruction is missing!");
225
226    // Use the end of last child scope as end of this scope.
227    const SmallVector<DbgScope *, 4> &Scopes = getScopes();
228    const MachineInstr *LastInsn = getFirstInsn();
229    unsigned LIndex = 0;
230    if (Scopes.empty()) {
231      assert (getLastInsn() && "Inner most scope does not have last insn!");
232      return;
233    }
234    for (SmallVector<DbgScope *, 4>::const_iterator SI = Scopes.begin(),
235           SE = Scopes.end(); SI != SE; ++SI) {
236      DbgScope *DS = *SI;
237      DS->fixInstructionMarkers(MIIndexMap);
238      const MachineInstr *DSLastInsn = DS->getLastInsn();
239      unsigned DSI = MIIndexMap[DSLastInsn];
240      if (DSI > LIndex) {
241        LastInsn = DSLastInsn;
242        LIndex = DSI;
243      }
244    }
245
246    unsigned CurrentLastInsnIndex = 0;
247    if (const MachineInstr *CL = getLastInsn())
248      CurrentLastInsnIndex = MIIndexMap[CL];
249    unsigned FIndex = MIIndexMap[getFirstInsn()];
250
251    // Set LastInsn as the last instruction for this scope only if
252    // it follows
253    //  1) this scope's first instruction and
254    //  2) current last instruction for this scope, if any.
255    if (LIndex >= CurrentLastInsnIndex && LIndex >= FIndex)
256      setLastInsn(LastInsn);
257  }
258
259#ifndef NDEBUG
260  void dump() const;
261#endif
262};
263
264#ifndef NDEBUG
265void DbgScope::dump() const {
266  raw_ostream &err = dbgs();
267  err.indent(IndentLevel);
268  MDNode *N = Desc.getNode();
269  N->dump();
270  err << " [" << StartLabel << ", " << EndLabel << "]\n";
271  if (AbstractScope)
272    err << "Abstract Scope\n";
273
274  IndentLevel += 2;
275  if (!Scopes.empty())
276    err << "Children ...\n";
277  for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
278    if (Scopes[i] != this)
279      Scopes[i]->dump();
280
281  IndentLevel -= 2;
282}
283#endif
284
285DbgScope::~DbgScope() {
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  // Construct type.
824  DIE *Buffer = getOrCreateTypeDIE(Ty);
825
826  // Set up proxy.
827  Entry = createDIEEntry(Buffer);
828  ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
829
830  Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
831}
832
833/// constructTypeDIE - Construct basic type die from DIBasicType.
834void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
835  // Get core information.
836  StringRef Name = BTy.getName();
837  Buffer.setTag(dwarf::DW_TAG_base_type);
838  addUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
839          BTy.getEncoding());
840
841  // Add name if not anonymous or intermediate type.
842  if (!Name.empty())
843    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
844  uint64_t Size = BTy.getSizeInBits() >> 3;
845  addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
846}
847
848/// constructTypeDIE - Construct derived type die from DIDerivedType.
849void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
850  // Get core information.
851  StringRef Name = DTy.getName();
852  uint64_t Size = DTy.getSizeInBits() >> 3;
853  unsigned Tag = DTy.getTag();
854
855  // FIXME - Workaround for templates.
856  if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
857
858  Buffer.setTag(Tag);
859
860  // Map to main type, void will not have a type.
861  DIType FromTy = DTy.getTypeDerivedFrom();
862  addType(&Buffer, FromTy);
863
864  // Add name if not anonymous or intermediate type.
865  if (!Name.empty())
866    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
867
868  // Add size if non-zero (derived types might be zero-sized.)
869  if (Size)
870    addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
871
872  // Add source line info if available and TyDesc is not a forward declaration.
873  if (!DTy.isForwardDecl())
874    addSourceLine(&Buffer, &DTy);
875}
876
877/// constructTypeDIE - Construct type DIE from DICompositeType.
878void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
879  // Get core information.
880  StringRef Name = CTy.getName();
881
882  uint64_t Size = CTy.getSizeInBits() >> 3;
883  unsigned Tag = CTy.getTag();
884  Buffer.setTag(Tag);
885
886  switch (Tag) {
887  case dwarf::DW_TAG_vector_type:
888  case dwarf::DW_TAG_array_type:
889    constructArrayTypeDIE(Buffer, &CTy);
890    break;
891  case dwarf::DW_TAG_enumeration_type: {
892    DIArray Elements = CTy.getTypeArray();
893
894    // Add enumerators to enumeration type.
895    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
896      DIE *ElemDie = NULL;
897      DIDescriptor Enum(Elements.getElement(i).getNode());
898      if (Enum.isEnumerator()) {
899        ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
900        Buffer.addChild(ElemDie);
901      }
902    }
903  }
904    break;
905  case dwarf::DW_TAG_subroutine_type: {
906    // Add return type.
907    DIArray Elements = CTy.getTypeArray();
908    DIDescriptor RTy = Elements.getElement(0);
909    addType(&Buffer, DIType(RTy.getNode()));
910
911    // Add prototype flag.
912    addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
913
914    // Add arguments.
915    for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
916      DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
917      DIDescriptor Ty = Elements.getElement(i);
918      addType(Arg, DIType(Ty.getNode()));
919      Buffer.addChild(Arg);
920    }
921  }
922    break;
923  case dwarf::DW_TAG_structure_type:
924  case dwarf::DW_TAG_union_type:
925  case dwarf::DW_TAG_class_type: {
926    // Add elements to structure type.
927    DIArray Elements = CTy.getTypeArray();
928
929    // A forward struct declared type may not have elements available.
930    unsigned N = Elements.getNumElements();
931    if (N == 0)
932      break;
933
934    // Add elements to structure type.
935    for (unsigned i = 0; i < N; ++i) {
936      DIDescriptor Element = Elements.getElement(i);
937      DIE *ElemDie = NULL;
938      if (Element.isSubprogram())
939        ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
940      else if (Element.isVariable()) {
941        DIVariable DV(Element.getNode());
942        ElemDie = new DIE(dwarf::DW_TAG_variable);
943        addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
944                  DV.getName());
945        addType(ElemDie, DV.getType());
946        addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
947        addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
948        addSourceLine(ElemDie, &DV);
949      } else if (Element.isDerivedType())
950        ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
951      else
952        continue;
953      Buffer.addChild(ElemDie);
954    }
955
956    if (CTy.isAppleBlockExtension())
957      addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
958
959    unsigned RLang = CTy.getRunTimeLang();
960    if (RLang)
961      addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
962              dwarf::DW_FORM_data1, RLang);
963
964    DICompositeType ContainingType = CTy.getContainingType();
965    if (DIDescriptor(ContainingType.getNode()).isCompositeType())
966      addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
967                  getOrCreateTypeDIE(DIType(ContainingType.getNode())));
968    break;
969  }
970  default:
971    break;
972  }
973
974  // Add name if not anonymous or intermediate type.
975  if (!Name.empty())
976    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
977
978  if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
979      Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
980    // Add size if non-zero (derived types might be zero-sized.)
981    if (Size)
982      addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
983    else {
984      // Add zero size if it is not a forward declaration.
985      if (CTy.isForwardDecl())
986        addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
987      else
988        addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
989    }
990
991    // Add source line info if available.
992    if (!CTy.isForwardDecl())
993      addSourceLine(&Buffer, &CTy);
994  }
995}
996
997/// constructSubrangeDIE - Construct subrange DIE from DISubrange.
998void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
999  int64_t L = SR.getLo();
1000  int64_t H = SR.getHi();
1001  DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1002
1003  addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1004  if (L)
1005    addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1006  addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1007
1008  Buffer.addChild(DW_Subrange);
1009}
1010
1011/// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1012void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1013                                       DICompositeType *CTy) {
1014  Buffer.setTag(dwarf::DW_TAG_array_type);
1015  if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1016    addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1017
1018  // Emit derived type.
1019  addType(&Buffer, CTy->getTypeDerivedFrom());
1020  DIArray Elements = CTy->getTypeArray();
1021
1022  // Get an anonymous type for index type.
1023  DIE *IdxTy = ModuleCU->getIndexTyDie();
1024  if (!IdxTy) {
1025    // Construct an anonymous type for index type.
1026    IdxTy = new DIE(dwarf::DW_TAG_base_type);
1027    addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1028    addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1029            dwarf::DW_ATE_signed);
1030    ModuleCU->addDie(IdxTy);
1031    ModuleCU->setIndexTyDie(IdxTy);
1032  }
1033
1034  // Add subranges to array type.
1035  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1036    DIDescriptor Element = Elements.getElement(i);
1037    if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1038      constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1039  }
1040}
1041
1042/// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1043DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1044  DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1045  StringRef Name = ETy.getName();
1046  addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1047  int64_t Value = ETy.getEnumValue();
1048  addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1049  return Enumerator;
1050}
1051
1052/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1053/// printer to not emit usual symbol prefix before the symbol name is used then
1054/// return linkage name after skipping this special LLVM prefix.
1055static StringRef getRealLinkageName(StringRef LinkageName) {
1056  char One = '\1';
1057  if (LinkageName.startswith(StringRef(&One, 1)))
1058    return LinkageName.substr(1);
1059  return LinkageName;
1060}
1061
1062/// createGlobalVariableDIE - Create new DIE using GV.
1063DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1064  // If the global variable was optmized out then no need to create debug info
1065  // entry.
1066  if (!GV.getGlobal()) return NULL;
1067  if (GV.getDisplayName().empty()) return NULL;
1068
1069  DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1070  addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1071            GV.getDisplayName());
1072
1073  StringRef LinkageName = GV.getLinkageName();
1074  if (!LinkageName.empty())
1075    addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1076              getRealLinkageName(LinkageName));
1077
1078  addType(GVDie, GV.getType());
1079  if (!GV.isLocalToUnit())
1080    addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1081  addSourceLine(GVDie, &GV);
1082
1083  return GVDie;
1084}
1085
1086/// createMemberDIE - Create new member DIE.
1087DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1088  DIE *MemberDie = new DIE(DT.getTag());
1089  StringRef Name = DT.getName();
1090  if (!Name.empty())
1091    addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1092
1093  addType(MemberDie, DT.getTypeDerivedFrom());
1094
1095  addSourceLine(MemberDie, &DT);
1096
1097  DIEBlock *MemLocationDie = new DIEBlock();
1098  addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1099
1100  uint64_t Size = DT.getSizeInBits();
1101  uint64_t FieldSize = DT.getOriginalTypeSize();
1102
1103  if (Size != FieldSize) {
1104    // Handle bitfield.
1105    addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1106    addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1107
1108    uint64_t Offset = DT.getOffsetInBits();
1109    uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1110    uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1111    uint64_t FieldOffset = (HiMark - FieldSize);
1112    Offset -= FieldOffset;
1113
1114    // Maybe we need to work from the other end.
1115    if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1116    addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1117
1118    // Here WD_AT_data_member_location points to the anonymous
1119    // field that includes this bit field.
1120    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1121
1122  } else
1123    // This is not a bitfield.
1124    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1125
1126  if (DT.getTag() == dwarf::DW_TAG_inheritance
1127      && DT.isVirtual()) {
1128
1129    // For C++, virtual base classes are not at fixed offset. Use following
1130    // expression to extract appropriate offset from vtable.
1131    // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1132
1133    DIEBlock *VBaseLocationDie = new DIEBlock();
1134    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1135    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1136    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1137    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1138    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1139    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1140    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1141
1142    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1143             VBaseLocationDie);
1144  } else
1145    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1146
1147  if (DT.isProtected())
1148    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1149            dwarf::DW_ACCESS_protected);
1150  else if (DT.isPrivate())
1151    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1152            dwarf::DW_ACCESS_private);
1153  else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1154    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1155            dwarf::DW_ACCESS_public);
1156  if (DT.isVirtual())
1157    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1158            dwarf::DW_VIRTUALITY_virtual);
1159  return MemberDie;
1160}
1161
1162/// createSubprogramDIE - Create new DIE using SP.
1163DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1164  DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1165  if (SPDie)
1166    return SPDie;
1167
1168  SPDie = new DIE(dwarf::DW_TAG_subprogram);
1169  // Constructors and operators for anonymous aggregates do not have names.
1170  if (!SP.getName().empty())
1171    addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1172
1173  StringRef LinkageName = SP.getLinkageName();
1174  if (!LinkageName.empty())
1175    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1176              getRealLinkageName(LinkageName));
1177
1178  addSourceLine(SPDie, &SP);
1179
1180  // Add prototyped tag, if C or ObjC.
1181  unsigned Lang = SP.getCompileUnit().getLanguage();
1182  if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1183      Lang == dwarf::DW_LANG_ObjC)
1184    addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1185
1186  // Add Return Type.
1187  DICompositeType SPTy = SP.getType();
1188  DIArray Args = SPTy.getTypeArray();
1189  unsigned SPTag = SPTy.getTag();
1190
1191  if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1192    addType(SPDie, SPTy);
1193  else
1194    addType(SPDie, DIType(Args.getElement(0).getNode()));
1195
1196  unsigned VK = SP.getVirtuality();
1197  if (VK) {
1198    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1199    DIEBlock *Block = new DIEBlock();
1200    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1201    addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1202    addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1203    ContainingTypeMap.insert(std::make_pair(SPDie,
1204                                            SP.getContainingType().getNode()));
1205  }
1206
1207  if (MakeDecl || !SP.isDefinition()) {
1208    addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1209
1210    // Add arguments. Do not add arguments for subprogram definition. They will
1211    // be handled while processing variables.
1212    DICompositeType SPTy = SP.getType();
1213    DIArray Args = SPTy.getTypeArray();
1214    unsigned SPTag = SPTy.getTag();
1215
1216    if (SPTag == dwarf::DW_TAG_subroutine_type)
1217      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1218        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1219        DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1220        addType(Arg, ATy);
1221        if (ATy.isArtificial())
1222          addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1223        SPDie->addChild(Arg);
1224      }
1225  }
1226
1227  if (SP.isArtificial())
1228    addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1229
1230  // DW_TAG_inlined_subroutine may refer to this DIE.
1231  ModuleCU->insertDIE(SP.getNode(), SPDie);
1232  return SPDie;
1233}
1234
1235/// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1236/// Initialize scope and update scope hierarchy.
1237DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1238  MDNode *InlinedAt) {
1239  assert (N && "Invalid Scope encoding!");
1240  assert (MI && "Missing machine instruction!");
1241  bool GetConcreteScope = (MI && InlinedAt);
1242
1243  DbgScope *NScope = NULL;
1244
1245  if (InlinedAt)
1246    NScope = DbgScopeMap.lookup(InlinedAt);
1247  else
1248    NScope = DbgScopeMap.lookup(N);
1249  assert (NScope && "Unable to find working scope!");
1250
1251  if (NScope->getFirstInsn())
1252    return NScope;
1253
1254  DbgScope *Parent = NULL;
1255  if (GetConcreteScope) {
1256    DILocation IL(InlinedAt);
1257    Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1258                         IL.getOrigLocation().getNode());
1259    assert (Parent && "Unable to find Parent scope!");
1260    NScope->setParent(Parent);
1261    Parent->addScope(NScope);
1262  } else if (DIDescriptor(N).isLexicalBlock()) {
1263    DILexicalBlock DB(N);
1264    Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1265    NScope->setParent(Parent);
1266    Parent->addScope(NScope);
1267  }
1268
1269  NScope->setFirstInsn(MI);
1270
1271  if (!Parent && !InlinedAt) {
1272    StringRef SPName = DISubprogram(N).getLinkageName();
1273    if (SPName == MF->getFunction()->getName())
1274      CurrentFnDbgScope = NScope;
1275  }
1276
1277  if (GetConcreteScope) {
1278    ConcreteScopes[InlinedAt] = NScope;
1279    getOrCreateAbstractScope(N);
1280  }
1281
1282  return NScope;
1283}
1284
1285DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1286  assert (N && "Invalid Scope encoding!");
1287
1288  DbgScope *AScope = AbstractScopes.lookup(N);
1289  if (AScope)
1290    return AScope;
1291
1292  DbgScope *Parent = NULL;
1293
1294  DIDescriptor Scope(N);
1295  if (Scope.isLexicalBlock()) {
1296    DILexicalBlock DB(N);
1297    DIDescriptor ParentDesc = DB.getContext();
1298    Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1299  }
1300
1301  AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1302
1303  if (Parent)
1304    Parent->addScope(AScope);
1305  AScope->setAbstractScope();
1306  AbstractScopes[N] = AScope;
1307  if (DIDescriptor(N).isSubprogram())
1308    AbstractScopesList.push_back(AScope);
1309  return AScope;
1310}
1311
1312/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1313/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1314/// If there are global variables in this scope then create and insert
1315/// DIEs for these variables.
1316DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1317
1318 DIE *SPDie = ModuleCU->getDIE(SPNode);
1319 assert (SPDie && "Unable to find subprogram DIE!");
1320 DISubprogram SP(SPNode);
1321 // There is not any need to generate specification DIE for a function
1322 // defined at compile unit level. If a function is defined inside another
1323 // function then gdb prefers the definition at top level and but does not
1324 // expect specification DIE in parent function. So avoid creating
1325 // specification DIE for a function defined inside a function.
1326 if (SP.isDefinition() && !SP.getContext().isCompileUnit()
1327     && !SP.getContext().isFile()
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  if (Start == 0) return 0;
1369
1370  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1371  assert(End->isDefined() && "Invalid end label for an inlined scope!");
1372
1373  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1374  if (Scope->isAbstractScope())
1375    return ScopeDIE;
1376
1377  addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1378           Start ? Start : getDWLabel("func_begin", SubprogramCount));
1379  addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1380           End ? End : getDWLabel("func_end", SubprogramCount));
1381
1382  return ScopeDIE;
1383}
1384
1385/// constructInlinedScopeDIE - This scope represents inlined body of
1386/// a function. Construct DIE to represent this concrete inlined copy
1387/// of the function.
1388DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1389  MCSymbol *StartLabel = Scope->getStartLabel();
1390  MCSymbol *EndLabel = Scope->getEndLabel();
1391  if (StartLabel == 0) return 0;
1392
1393  assert(StartLabel->isDefined() &&
1394         "Invalid starting label for an inlined scope!");
1395  assert(EndLabel->isDefined() &&
1396         "Invalid end label for an inlined scope!");
1397  if (!Scope->getScopeNode())
1398    return NULL;
1399  DIScope DS(Scope->getScopeNode());
1400  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1401
1402  DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1403  DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1404  assert (OriginDIE && "Unable to find Origin DIE!");
1405  addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1406              dwarf::DW_FORM_ref4, OriginDIE);
1407
1408  addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1409  addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1410
1411  InlinedSubprogramDIEs.insert(OriginDIE);
1412
1413  // Track the start label for this inlined function.
1414  DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1415    I = InlineInfo.find(InlinedSP.getNode());
1416
1417  if (I == InlineInfo.end()) {
1418    InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1419                                                             ScopeDIE));
1420    InlinedSPNodes.push_back(InlinedSP.getNode());
1421  } else
1422    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1423
1424  StringPool.insert(InlinedSP.getName());
1425  StringPool.insert(getRealLinkageName(InlinedSP.getLinkageName()));
1426
1427  DILocation DL(Scope->getInlinedAt());
1428  addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1429  addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1430
1431  return ScopeDIE;
1432}
1433
1434
1435/// constructVariableDIE - Construct a DIE for the given DbgVariable.
1436DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1437  // Get the descriptor.
1438  const DIVariable &VD = DV->getVariable();
1439  StringRef Name = VD.getName();
1440  if (Name.empty())
1441    return NULL;
1442
1443  // Translate tag to proper Dwarf tag.  The result variable is dropped for
1444  // now.
1445  unsigned Tag;
1446  switch (VD.getTag()) {
1447  case dwarf::DW_TAG_return_variable:
1448    return NULL;
1449  case dwarf::DW_TAG_arg_variable:
1450    Tag = dwarf::DW_TAG_formal_parameter;
1451    break;
1452  case dwarf::DW_TAG_auto_variable:    // fall thru
1453  default:
1454    Tag = dwarf::DW_TAG_variable;
1455    break;
1456  }
1457
1458  // Define variable debug information entry.
1459  DIE *VariableDie = new DIE(Tag);
1460
1461
1462  DIE *AbsDIE = NULL;
1463  if (DbgVariable *AV = DV->getAbstractVariable())
1464    AbsDIE = AV->getDIE();
1465
1466  if (AbsDIE) {
1467    DIScope DS(Scope->getScopeNode());
1468    DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1469    DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1470    (void) OriginSPDIE;
1471    assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1472    DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1473    assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1474    addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1475                dwarf::DW_FORM_ref4, AbsDIE);
1476  }
1477  else {
1478    addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1479    addSourceLine(VariableDie, &VD);
1480
1481    // Add variable type.
1482    // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1483    // addresses instead.
1484    if (VD.isBlockByrefVariable())
1485      addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1486    else
1487      addType(VariableDie, VD.getType());
1488  }
1489
1490  // Add variable address.
1491  if (!Scope->isAbstractScope()) {
1492    MachineLocation Location;
1493    unsigned FrameReg;
1494    int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1495    Location.set(FrameReg, Offset);
1496
1497    if (VD.hasComplexAddress())
1498      addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1499    else if (VD.isBlockByrefVariable())
1500      addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1501    else
1502      addAddress(VariableDie, dwarf::DW_AT_location, Location);
1503  }
1504
1505  if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1506    addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1507  DV->setDIE(VariableDie);
1508  return VariableDie;
1509
1510}
1511
1512void DwarfDebug::addPubTypes(DISubprogram SP) {
1513  DICompositeType SPTy = SP.getType();
1514  unsigned SPTag = SPTy.getTag();
1515  if (SPTag != dwarf::DW_TAG_subroutine_type)
1516    return;
1517
1518  DIArray Args = SPTy.getTypeArray();
1519  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1520    DIType ATy(Args.getElement(i).getNode());
1521    if (!ATy.isValid())
1522      continue;
1523    DICompositeType CATy = getDICompositeType(ATy);
1524    if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()) {
1525      if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1526        ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1527    }
1528  }
1529}
1530
1531/// constructScopeDIE - Construct a DIE for this scope.
1532DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1533  if (!Scope || !Scope->getScopeNode())
1534    return NULL;
1535
1536  DIScope DS(Scope->getScopeNode());
1537  DIE *ScopeDIE = NULL;
1538  if (Scope->getInlinedAt())
1539    ScopeDIE = constructInlinedScopeDIE(Scope);
1540  else if (DS.isSubprogram()) {
1541    if (Scope->isAbstractScope())
1542      ScopeDIE = ModuleCU->getDIE(DS.getNode());
1543    else
1544      ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1545  }
1546  else {
1547    ScopeDIE = constructLexicalScopeDIE(Scope);
1548    if (!ScopeDIE) return NULL;
1549  }
1550
1551  // Add variables to scope.
1552  const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1553  for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1554    DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1555    if (VariableDIE)
1556      ScopeDIE->addChild(VariableDIE);
1557  }
1558
1559  // Add nested scopes.
1560  const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1561  for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1562    // Define the Scope debug information entry.
1563    DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1564    if (NestedDIE)
1565      ScopeDIE->addChild(NestedDIE);
1566  }
1567
1568  if (DS.isSubprogram())
1569    addPubTypes(DISubprogram(DS.getNode()));
1570
1571 return ScopeDIE;
1572}
1573
1574/// GetOrCreateSourceID - Look up the source id with the given directory and
1575/// source file names. If none currently exists, create a new id and insert it
1576/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1577/// maps as well.
1578unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
1579  unsigned DId;
1580  StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1581  if (DI != DirectoryIdMap.end()) {
1582    DId = DI->getValue();
1583  } else {
1584    DId = DirectoryNames.size() + 1;
1585    DirectoryIdMap[DirName] = DId;
1586    DirectoryNames.push_back(DirName);
1587  }
1588
1589  unsigned FId;
1590  StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1591  if (FI != SourceFileIdMap.end()) {
1592    FId = FI->getValue();
1593  } else {
1594    FId = SourceFileNames.size() + 1;
1595    SourceFileIdMap[FileName] = FId;
1596    SourceFileNames.push_back(FileName);
1597  }
1598
1599  DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1600    SourceIdMap.find(std::make_pair(DId, FId));
1601  if (SI != SourceIdMap.end())
1602    return SI->second;
1603
1604  unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
1605  SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1606  SourceIds.push_back(std::make_pair(DId, FId));
1607
1608  return SrcId;
1609}
1610
1611/// getOrCreateNameSpace - Create a DIE for DINameSpace.
1612DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1613  DIE *NDie = ModuleCU->getDIE(NS.getNode());
1614  if (NDie)
1615    return NDie;
1616  NDie = new DIE(dwarf::DW_TAG_namespace);
1617  ModuleCU->insertDIE(NS.getNode(), NDie);
1618  if (!NS.getName().empty())
1619    addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1620  addSourceLine(NDie, &NS);
1621  addToContextOwner(NDie, NS.getContext());
1622  return NDie;
1623}
1624
1625void DwarfDebug::constructCompileUnit(MDNode *N) {
1626  DICompileUnit DIUnit(N);
1627  // Use first compile unit marked as isMain as the compile unit for this
1628  // module.
1629  if (ModuleCU || !DIUnit.isMain())
1630    return;
1631  StringRef FN = DIUnit.getFilename();
1632  StringRef Dir = DIUnit.getDirectory();
1633  unsigned ID = GetOrCreateSourceID(Dir, FN);
1634
1635  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1636  // FIXME: Why getting the delta between two identical labels??
1637  addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1638                   getTempLabel("section_line"), getTempLabel("section_line"),
1639                   false);
1640  addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1641            DIUnit.getProducer());
1642  addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1643          DIUnit.getLanguage());
1644  addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1645
1646  if (!Dir.empty())
1647    addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1648  if (DIUnit.isOptimized())
1649    addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1650
1651  StringRef Flags = DIUnit.getFlags();
1652  if (!Flags.empty())
1653    addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1654
1655  unsigned RVer = DIUnit.getRunTimeVersion();
1656  if (RVer)
1657    addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1658            dwarf::DW_FORM_data1, RVer);
1659
1660  assert(!ModuleCU &&
1661         "ModuleCU assigned since the top of constructCompileUnit");
1662  ModuleCU = new CompileUnit(ID, Die);
1663}
1664
1665void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1666  DIGlobalVariable DI_GV(N);
1667
1668  // If debug information is malformed then ignore it.
1669  if (DI_GV.Verify() == false)
1670    return;
1671
1672  // Check for pre-existence.
1673  if (ModuleCU->getDIE(DI_GV.getNode()))
1674    return;
1675
1676  DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1677  if (!VariableDie)
1678    return;
1679
1680  // Add to map.
1681  ModuleCU->insertDIE(N, VariableDie);
1682
1683  // Add to context owner.
1684  DIDescriptor GVContext = DI_GV.getContext();
1685  // Do not create specification DIE if context is either compile unit
1686  // or a subprogram.
1687  if (DI_GV.isDefinition() && !GVContext.isCompileUnit()
1688      && !GVContext.isFile() && !GVContext.isSubprogram()) {
1689    // Create specification DIE.
1690    DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1691    addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1692                dwarf::DW_FORM_ref4, VariableDie);
1693    DIEBlock *Block = new DIEBlock();
1694    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1695    addLabel(Block, 0, dwarf::DW_FORM_udata,
1696             Asm->GetGlobalValueSymbol(DI_GV.getGlobal()));
1697    addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1698    addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1699    ModuleCU->addDie(VariableSpecDIE);
1700  } else {
1701    DIEBlock *Block = new DIEBlock();
1702    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1703    addLabel(Block, 0, dwarf::DW_FORM_udata,
1704             Asm->GetGlobalValueSymbol(DI_GV.getGlobal()));
1705    addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1706  }
1707  addToContextOwner(VariableDie, GVContext);
1708
1709  // Expose as global. FIXME - need to check external flag.
1710  ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1711
1712  DIType GTy = DI_GV.getType();
1713  if (GTy.isCompositeType() && !GTy.getName().empty()) {
1714    DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1715    assert (Entry && "Missing global type!");
1716    ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1717  }
1718  return;
1719}
1720
1721void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1722  DISubprogram SP(N);
1723
1724  // Check for pre-existence.
1725  if (ModuleCU->getDIE(N))
1726    return;
1727
1728  if (!SP.isDefinition())
1729    // This is a method declaration which will be handled while constructing
1730    // class type.
1731    return;
1732
1733  DIE *SubprogramDie = createSubprogramDIE(SP);
1734
1735  // Add to map.
1736  ModuleCU->insertDIE(N, SubprogramDie);
1737
1738  // Add to context owner.
1739  addToContextOwner(SubprogramDie, SP.getContext());
1740
1741  // Expose as global.
1742  ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1743
1744  return;
1745}
1746
1747/// beginModule - Emit all Dwarf sections that should come prior to the
1748/// content. Create global DIEs and emit initial debug info sections.
1749/// This is inovked by the target AsmPrinter.
1750void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1751  this->M = M;
1752
1753  if (TimePassesIsEnabled)
1754    DebugTimer->startTimer();
1755
1756  if (!MAI->doesSupportDebugInformation())
1757    return;
1758
1759  DebugInfoFinder DbgFinder;
1760  DbgFinder.processModule(*M);
1761
1762  // Create all the compile unit DIEs.
1763  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1764         E = DbgFinder.compile_unit_end(); I != E; ++I)
1765    constructCompileUnit(*I);
1766
1767  if (!ModuleCU)
1768    return;
1769
1770  // Create DIEs for each subprogram.
1771  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1772         E = DbgFinder.subprogram_end(); I != E; ++I)
1773    constructSubprogramDIE(*I);
1774
1775  // Create DIEs for each global variable.
1776  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1777         E = DbgFinder.global_variable_end(); I != E; ++I)
1778    constructGlobalVariableDIE(*I);
1779
1780  MMI = mmi;
1781  shouldEmit = true;
1782  MMI->setDebugInfoAvailability(true);
1783
1784  // Prime section data.
1785  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1786
1787  // Print out .file directives to specify files for .loc directives. These are
1788  // printed out early so that they precede any .loc directives.
1789  if (MAI->hasDotLocAndDotFile()) {
1790    for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1791      // Remember source id starts at 1.
1792      std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1793      // FIXME: don't use sys::path for this!  This should not depend on the
1794      // host.
1795      sys::Path FullPath(getSourceDirectoryName(Id.first));
1796      bool AppendOk =
1797        FullPath.appendComponent(getSourceFileName(Id.second));
1798      assert(AppendOk && "Could not append filename to directory!");
1799      AppendOk = false;
1800      Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1801    }
1802  }
1803
1804  // Emit initial sections
1805  emitInitial();
1806
1807  if (TimePassesIsEnabled)
1808    DebugTimer->stopTimer();
1809}
1810
1811/// endModule - Emit all Dwarf sections that should come after the content.
1812///
1813void DwarfDebug::endModule() {
1814  if (!ModuleCU)
1815    return;
1816
1817  if (TimePassesIsEnabled)
1818    DebugTimer->startTimer();
1819
1820  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1821  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1822         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1823    DIE *ISP = *AI;
1824    addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1825  }
1826
1827  // Insert top level DIEs.
1828  for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
1829         TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
1830    ModuleCU->getCUDie()->addChild(*TI);
1831
1832  for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1833         CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1834    DIE *SPDie = CI->first;
1835    MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1836    if (!N) continue;
1837    DIE *NDie = ModuleCU->getDIE(N);
1838    if (!NDie) continue;
1839    addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1840    // FIXME - This is not the correct approach.
1841    // addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1842  }
1843
1844  // Standard sections final addresses.
1845  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1846  Asm->OutStreamer.EmitLabel(getTempLabel("text_end"));
1847  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1848  Asm->OutStreamer.EmitLabel(getTempLabel("data_end"));
1849
1850  // End text sections.
1851  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1852    Asm->OutStreamer.SwitchSection(SectionMap[i]);
1853    Asm->OutStreamer.EmitLabel(getDWLabel("section_end", i));
1854  }
1855
1856  // Emit common frame information.
1857  emitCommonDebugFrame();
1858
1859  // Emit function debug frame information
1860  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1861         E = DebugFrames.end(); I != E; ++I)
1862    emitFunctionDebugFrame(*I);
1863
1864  // Compute DIE offsets and sizes.
1865  computeSizeAndOffsets();
1866
1867  // Emit all the DIEs into a debug info section
1868  emitDebugInfo();
1869
1870  // Corresponding abbreviations into a abbrev section.
1871  emitAbbreviations();
1872
1873  // Emit source line correspondence into a debug line section.
1874  emitDebugLines();
1875
1876  // Emit info into a debug pubnames section.
1877  emitDebugPubNames();
1878
1879  // Emit info into a debug pubtypes section.
1880  emitDebugPubTypes();
1881
1882  // Emit info into a debug str section.
1883  emitDebugStr();
1884
1885  // Emit info into a debug loc section.
1886  emitDebugLoc();
1887
1888  // Emit info into a debug aranges section.
1889  EmitDebugARanges();
1890
1891  // Emit info into a debug ranges section.
1892  emitDebugRanges();
1893
1894  // Emit info into a debug macinfo section.
1895  emitDebugMacInfo();
1896
1897  // Emit inline info.
1898  emitDebugInlineInfo();
1899
1900  delete ModuleCU;
1901  ModuleCU = NULL;  // Reset for the next Module, if any.
1902
1903  if (TimePassesIsEnabled)
1904    DebugTimer->stopTimer();
1905}
1906
1907/// findAbstractVariable - Find abstract variable, if any, associated with Var.
1908DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1909                                              unsigned FrameIdx,
1910                                              DILocation &ScopeLoc) {
1911
1912  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1913  if (AbsDbgVariable)
1914    return AbsDbgVariable;
1915
1916  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1917  if (!Scope)
1918    return NULL;
1919
1920  AbsDbgVariable = new DbgVariable(Var, FrameIdx,
1921                                   NULL /* No more-abstract variable*/);
1922  Scope->addVariable(AbsDbgVariable);
1923  AbstractVariables[Var.getNode()] = AbsDbgVariable;
1924  return AbsDbgVariable;
1925}
1926
1927/// collectVariableInfo - Populate DbgScope entries with variables' info.
1928void DwarfDebug::collectVariableInfo() {
1929  if (!MMI) return;
1930
1931  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1932  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1933         VE = VMap.end(); VI != VE; ++VI) {
1934    MDNode *Var = VI->first;
1935    if (!Var) continue;
1936    DIVariable DV (Var);
1937    std::pair< unsigned, MDNode *> VP = VI->second;
1938    DILocation ScopeLoc(VP.second);
1939
1940    DbgScope *Scope =
1941      ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1942    if (!Scope)
1943      Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1944    // If variable scope is not found then skip this variable.
1945    if (!Scope)
1946      continue;
1947
1948    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, ScopeLoc);
1949    DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
1950    Scope->addVariable(RegVar);
1951  }
1952}
1953
1954/// beginScope - Process beginning of a scope starting at Label.
1955void DwarfDebug::beginScope(const MachineInstr *MI, MCSymbol *Label) {
1956  InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1957  if (I == DbgScopeBeginMap.end())
1958    return;
1959  ScopeVector &SD = I->second;
1960  for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1961       SDI != SDE; ++SDI)
1962    (*SDI)->setStartLabel(Label);
1963}
1964
1965/// endScope - Process end of a scope.
1966void DwarfDebug::endScope(const MachineInstr *MI) {
1967  InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1968  if (I == DbgScopeEndMap.end())
1969    return;
1970
1971  MCSymbol *Label = getDWLabel("label", MMI->NextLabelID());
1972  Asm->OutStreamer.EmitLabel(Label);
1973
1974  SmallVector<DbgScope*, 2> &SD = I->second;
1975  for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1976       SDI != SDE; ++SDI)
1977    (*SDI)->setEndLabel(Label);
1978  return;
1979}
1980
1981/// createDbgScope - Create DbgScope for the scope.
1982void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1983
1984  if (!InlinedAt) {
1985    DbgScope *WScope = DbgScopeMap.lookup(Scope);
1986    if (WScope)
1987      return;
1988    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1989    DbgScopeMap.insert(std::make_pair(Scope, WScope));
1990    if (DIDescriptor(Scope).isLexicalBlock())
1991      createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
1992    return;
1993  }
1994
1995  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1996  if (WScope)
1997    return;
1998
1999  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2000  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2001  DILocation DL(InlinedAt);
2002  createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2003}
2004
2005/// extractScopeInformation - Scan machine instructions in this function
2006/// and collect DbgScopes. Return true, if atleast one scope was found.
2007bool DwarfDebug::extractScopeInformation() {
2008  // If scope information was extracted using .dbg intrinsics then there is not
2009  // any need to extract these information by scanning each instruction.
2010  if (!DbgScopeMap.empty())
2011    return false;
2012
2013  DenseMap<const MachineInstr *, unsigned> MIIndexMap;
2014  unsigned MIIndex = 0;
2015  // Scan each instruction and create scopes. First build working set of scopes.
2016  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2017       I != E; ++I) {
2018    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2019         II != IE; ++II) {
2020      const MachineInstr *MInsn = II;
2021      MIIndexMap[MInsn] = MIIndex++;
2022      DebugLoc DL = MInsn->getDebugLoc();
2023      if (DL.isUnknown()) continue;
2024      DILocation DLT = MF->getDILocation(DL);
2025      DIScope DLTScope = DLT.getScope();
2026      // There is no need to create another DIE for compile unit. For all
2027      // other scopes, create one DbgScope now. This will be translated
2028      // into a scope DIE at the end.
2029      if (DLTScope.isCompileUnit()) continue;
2030      createDbgScope(DLTScope.getNode(), DLT.getOrigLocation().getNode());
2031    }
2032  }
2033
2034
2035  // Build scope hierarchy using working set of scopes.
2036  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2037       I != E; ++I) {
2038    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2039         II != IE; ++II) {
2040      const MachineInstr *MInsn = II;
2041      DebugLoc DL = MInsn->getDebugLoc();
2042      if (DL.isUnknown())  continue;
2043      DILocation DLT = MF->getDILocation(DL);
2044      DIScope DLTScope = DLT.getScope();
2045      // There is no need to create another DIE for compile unit. For all
2046      // other scopes, create one DbgScope now. This will be translated
2047      // into a scope DIE at the end.
2048      if (DLTScope.isCompileUnit()) continue;
2049      DbgScope *Scope = getUpdatedDbgScope(DLTScope.getNode(), MInsn,
2050                                           DLT.getOrigLocation().getNode());
2051      Scope->setLastInsn(MInsn);
2052    }
2053  }
2054
2055  if (!CurrentFnDbgScope)
2056    return false;
2057
2058  CurrentFnDbgScope->fixInstructionMarkers(MIIndexMap);
2059
2060  // Each scope has first instruction and last instruction to mark beginning
2061  // and end of a scope respectively. Create an inverse map that list scopes
2062  // starts (and ends) with an instruction. One instruction may start (or end)
2063  // multiple scopes. Ignore scopes that are not reachable.
2064  SmallVector<DbgScope *, 4> WorkList;
2065  WorkList.push_back(CurrentFnDbgScope);
2066  while (!WorkList.empty()) {
2067    DbgScope *S = WorkList.back(); WorkList.pop_back();
2068
2069    const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2070    if (!Children.empty())
2071      for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2072             SE = Children.end(); SI != SE; ++SI)
2073        WorkList.push_back(*SI);
2074
2075    if (S->isAbstractScope())
2076      continue;
2077    const MachineInstr *MI = S->getFirstInsn();
2078    assert (MI && "DbgScope does not have first instruction!");
2079
2080    InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2081    if (IDI != DbgScopeBeginMap.end())
2082      IDI->second.push_back(S);
2083    else
2084      DbgScopeBeginMap[MI].push_back(S);
2085
2086    MI = S->getLastInsn();
2087    assert (MI && "DbgScope does not have last instruction!");
2088    IDI = DbgScopeEndMap.find(MI);
2089    if (IDI != DbgScopeEndMap.end())
2090      IDI->second.push_back(S);
2091    else
2092      DbgScopeEndMap[MI].push_back(S);
2093  }
2094
2095  return !DbgScopeMap.empty();
2096}
2097
2098/// beginFunction - Gather pre-function debug information.  Assumes being
2099/// emitted immediately after the function entry point.
2100void DwarfDebug::beginFunction(const MachineFunction *MF) {
2101  this->MF = MF;
2102
2103  if (!ShouldEmitDwarfDebug()) return;
2104
2105  if (TimePassesIsEnabled)
2106    DebugTimer->startTimer();
2107
2108  if (!extractScopeInformation())
2109    return;
2110
2111  collectVariableInfo();
2112
2113  // Assumes in correct section after the entry point.
2114  Asm->OutStreamer.EmitLabel(getDWLabel("func_begin", ++SubprogramCount));
2115
2116  // Emit label for the implicitly defined dbg.stoppoint at the start of the
2117  // function.
2118  DebugLoc FDL = MF->getDefaultDebugLoc();
2119  if (!FDL.isUnknown()) {
2120    DILocation DLT = MF->getDILocation(FDL);
2121    DISubprogram SP = getDISubprogram(DLT.getScope().getNode());
2122    unsigned Line, Col;
2123    if (SP.Verify()) {
2124      Line = SP.getLineNumber();
2125      Col = 0;
2126    } else {
2127      Line = DLT.getLineNumber();
2128      Col = DLT.getColumnNumber();
2129    }
2130
2131    recordSourceLine(Line, Col, DLT.getScope().getNode());
2132  }
2133  if (TimePassesIsEnabled)
2134    DebugTimer->stopTimer();
2135}
2136
2137/// endFunction - Gather and emit post-function debug information.
2138///
2139void DwarfDebug::endFunction(const MachineFunction *MF) {
2140  if (!ShouldEmitDwarfDebug()) return;
2141
2142  if (TimePassesIsEnabled)
2143    DebugTimer->startTimer();
2144
2145  if (DbgScopeMap.empty())
2146    return;
2147
2148  if (CurrentFnDbgScope) {
2149    // Define end label for subprogram.
2150    Asm->OutStreamer.EmitLabel(getDWLabel("func_end", SubprogramCount));
2151
2152    // Get function line info.
2153    if (!Lines.empty()) {
2154      // Get section line info.
2155      unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2156      if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2157      std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2158      // Append the function info to section info.
2159      SectionLineInfos.insert(SectionLineInfos.end(),
2160                              Lines.begin(), Lines.end());
2161    }
2162
2163    // Construct abstract scopes.
2164    for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2165           AE = AbstractScopesList.end(); AI != AE; ++AI)
2166      constructScopeDIE(*AI);
2167
2168    constructScopeDIE(CurrentFnDbgScope);
2169
2170    DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2171                                                 MMI->getFrameMoves()));
2172  }
2173
2174  // Clear debug info
2175  CurrentFnDbgScope = NULL;
2176  DeleteContainerSeconds(DbgScopeMap);
2177  DbgScopeBeginMap.clear();
2178  DbgScopeEndMap.clear();
2179  ConcreteScopes.clear();
2180  DeleteContainerSeconds(AbstractScopes);
2181  AbstractScopesList.clear();
2182  AbstractVariables.clear();
2183  Lines.clear();
2184
2185  if (TimePassesIsEnabled)
2186    DebugTimer->stopTimer();
2187}
2188
2189/// recordSourceLine - Register a source line with debug info. Returns the
2190/// unique label that was emitted and which provides correspondence to
2191/// the source line list.
2192MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
2193  if (!MMI)
2194    return 0;
2195
2196  if (TimePassesIsEnabled)
2197    DebugTimer->startTimer();
2198
2199  StringRef Dir;
2200  StringRef Fn;
2201
2202  DIDescriptor Scope(S);
2203  if (Scope.isCompileUnit()) {
2204    DICompileUnit CU(S);
2205    Dir = CU.getDirectory();
2206    Fn = CU.getFilename();
2207  } else if (Scope.isSubprogram()) {
2208    DISubprogram SP(S);
2209    Dir = SP.getDirectory();
2210    Fn = SP.getFilename();
2211  } else if (Scope.isLexicalBlock()) {
2212    DILexicalBlock DB(S);
2213    Dir = DB.getDirectory();
2214    Fn = DB.getFilename();
2215  } else
2216    assert (0 && "Unexpected scope info");
2217
2218  unsigned Src = GetOrCreateSourceID(Dir, Fn);
2219  unsigned ID = MMI->NextLabelID();
2220  Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2221
2222  if (TimePassesIsEnabled)
2223    DebugTimer->stopTimer();
2224
2225  MCSymbol *Label = getDWLabel("label", ID);
2226  Asm->OutStreamer.EmitLabel(Label);
2227  return Label;
2228}
2229
2230/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2231/// timed. Look up the source id with the given directory and source file
2232/// names. If none currently exists, create a new id and insert it in the
2233/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2234/// well.
2235unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2236                                         const std::string &FileName) {
2237  if (TimePassesIsEnabled)
2238    DebugTimer->startTimer();
2239
2240  unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2241
2242  if (TimePassesIsEnabled)
2243    DebugTimer->stopTimer();
2244
2245  return SrcId;
2246}
2247
2248//===----------------------------------------------------------------------===//
2249// Emit Methods
2250//===----------------------------------------------------------------------===//
2251
2252/// computeSizeAndOffset - Compute the size and offset of a DIE.
2253///
2254unsigned
2255DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2256  // Get the children.
2257  const std::vector<DIE *> &Children = Die->getChildren();
2258
2259  // If not last sibling and has children then add sibling offset attribute.
2260  if (!Last && !Children.empty()) Die->addSiblingOffset();
2261
2262  // Record the abbreviation.
2263  assignAbbrevNumber(Die->getAbbrev());
2264
2265  // Get the abbreviation for this DIE.
2266  unsigned AbbrevNumber = Die->getAbbrevNumber();
2267  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2268
2269  // Set DIE offset
2270  Die->setOffset(Offset);
2271
2272  // Start the size with the size of abbreviation code.
2273  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2274
2275  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2276  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2277
2278  // Size the DIE attribute values.
2279  for (unsigned i = 0, N = Values.size(); i < N; ++i)
2280    // Size attribute value.
2281    Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2282
2283  // Size the DIE children if any.
2284  if (!Children.empty()) {
2285    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2286           "Children flag not set");
2287
2288    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2289      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2290
2291    // End of children marker.
2292    Offset += sizeof(int8_t);
2293  }
2294
2295  Die->setSize(Offset - Die->getOffset());
2296  return Offset;
2297}
2298
2299/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2300///
2301void DwarfDebug::computeSizeAndOffsets() {
2302  // Compute size of compile unit header.
2303  static unsigned Offset =
2304    sizeof(int32_t) + // Length of Compilation Unit Info
2305    sizeof(int16_t) + // DWARF version number
2306    sizeof(int32_t) + // Offset Into Abbrev. Section
2307    sizeof(int8_t);   // Pointer Size (in bytes)
2308
2309  computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2310  CompileUnitOffsets[ModuleCU] = 0;
2311}
2312
2313/// emitInitial - Emit initial Dwarf declarations.  This is necessary for cc
2314/// tools to recognize the object file contains Dwarf information.
2315void DwarfDebug::emitInitial() {
2316  // Check to see if we already emitted intial headers.
2317  if (didInitial) return;
2318  didInitial = true;
2319
2320  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2321
2322  // Dwarf sections base addresses.
2323  if (MAI->doesDwarfRequireFrameSection()) {
2324    Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2325    Asm->OutStreamer.EmitLabel(getTempLabel("section_debug_frame"));
2326  }
2327
2328  Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2329  Asm->OutStreamer.EmitLabel(getTempLabel("section_info"));
2330  Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2331  Asm->OutStreamer.EmitLabel(getTempLabel("section_abbrev"));
2332  Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2333  Asm->OutStreamer.EmitLabel(getTempLabel("section_aranges"));
2334
2335  if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2336    Asm->OutStreamer.SwitchSection(LineInfoDirective);
2337    Asm->OutStreamer.EmitLabel(getTempLabel("section_macinfo"));
2338  }
2339
2340  Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2341  Asm->OutStreamer.EmitLabel(getTempLabel("section_line"));
2342  Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2343  Asm->OutStreamer.EmitLabel(getTempLabel("section_loc"));
2344  Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2345  Asm->OutStreamer.EmitLabel(getTempLabel("section_pubnames"));
2346  Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
2347  Asm->OutStreamer.EmitLabel(getTempLabel("section_pubtypes"));
2348  Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2349  Asm->OutStreamer.EmitLabel(getTempLabel("section_str"));
2350  Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2351  Asm->OutStreamer.EmitLabel(getTempLabel("section_ranges"));
2352
2353  Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2354  Asm->OutStreamer.EmitLabel(getTempLabel("text_begin"));
2355  Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2356  Asm->OutStreamer.EmitLabel(getTempLabel("data_begin"));
2357}
2358
2359/// emitDIE - Recusively Emits a debug information entry.
2360///
2361void DwarfDebug::emitDIE(DIE *Die) {
2362  // Get the abbreviation for this DIE.
2363  unsigned AbbrevNumber = Die->getAbbrevNumber();
2364  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2365
2366  // Emit the code (index) for the abbreviation.
2367  if (Asm->VerboseAsm)
2368    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2369                                Twine::utohexstr(Die->getOffset()) + ":0x" +
2370                                Twine::utohexstr(Die->getSize()) + " " +
2371                                dwarf::TagString(Abbrev->getTag()));
2372  EmitULEB128(AbbrevNumber);
2373
2374  SmallVector<DIEValue*, 32> &Values = Die->getValues();
2375  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2376
2377  // Emit the DIE attribute values.
2378  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2379    unsigned Attr = AbbrevData[i].getAttribute();
2380    unsigned Form = AbbrevData[i].getForm();
2381    assert(Form && "Too many attributes for DIE (check abbreviation)");
2382
2383    if (Asm->VerboseAsm)
2384      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2385
2386    switch (Attr) {
2387    case dwarf::DW_AT_sibling:
2388      Asm->EmitInt32(Die->getSiblingOffset());
2389      break;
2390    case dwarf::DW_AT_abstract_origin: {
2391      DIEEntry *E = cast<DIEEntry>(Values[i]);
2392      DIE *Origin = E->getEntry();
2393      unsigned Addr = Origin->getOffset();
2394      Asm->EmitInt32(Addr);
2395      break;
2396    }
2397    default:
2398      // Emit an attribute using the defined form.
2399      Values[i]->EmitValue(this, Form);
2400      break;
2401    }
2402  }
2403
2404  // Emit the DIE children if any.
2405  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2406    const std::vector<DIE *> &Children = Die->getChildren();
2407
2408    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2409      emitDIE(Children[j]);
2410
2411    if (Asm->VerboseAsm)
2412      Asm->OutStreamer.AddComment("End Of Children Mark");
2413    Asm->EmitInt8(0);
2414  }
2415}
2416
2417/// emitDebugInfo - Emit the debug info section.
2418///
2419void DwarfDebug::emitDebugInfo() {
2420  // Start debug info section.
2421  Asm->OutStreamer.SwitchSection(
2422                            Asm->getObjFileLowering().getDwarfInfoSection());
2423  DIE *Die = ModuleCU->getCUDie();
2424
2425  // Emit the compile units header.
2426  Asm->OutStreamer.EmitLabel(getDWLabel("info_begin", ModuleCU->getID()));
2427
2428  // Emit size of content not including length itself
2429  unsigned ContentSize = Die->getSize() +
2430    sizeof(int16_t) + // DWARF version number
2431    sizeof(int32_t) + // Offset Into Abbrev. Section
2432    sizeof(int8_t) +  // Pointer Size (in bytes)
2433    sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2434
2435  Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2436  Asm->EmitInt32(ContentSize);
2437  Asm->OutStreamer.AddComment("DWARF version number");
2438  Asm->EmitInt16(dwarf::DWARF_VERSION);
2439  Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2440  EmitSectionOffset(getTempLabel("abbrev_begin"),getTempLabel("section_abbrev"),
2441                    true, false);
2442  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2443  Asm->EmitInt8(TD->getPointerSize());
2444
2445  emitDIE(Die);
2446  // FIXME - extra padding for gdb bug.
2447  Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2448  Asm->EmitInt8(0);
2449  Asm->EmitInt8(0);
2450  Asm->EmitInt8(0);
2451  Asm->EmitInt8(0);
2452  Asm->OutStreamer.EmitLabel(getDWLabel("info_end", ModuleCU->getID()));
2453}
2454
2455/// emitAbbreviations - Emit the abbreviation section.
2456///
2457void DwarfDebug::emitAbbreviations() const {
2458  // Check to see if it is worth the effort.
2459  if (!Abbreviations.empty()) {
2460    // Start the debug abbrev section.
2461    Asm->OutStreamer.SwitchSection(
2462                            Asm->getObjFileLowering().getDwarfAbbrevSection());
2463
2464    Asm->OutStreamer.EmitLabel(getTempLabel("abbrev_begin"));
2465
2466    // For each abbrevation.
2467    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2468      // Get abbreviation data
2469      const DIEAbbrev *Abbrev = Abbreviations[i];
2470
2471      // Emit the abbrevations code (base 1 index.)
2472      EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2473
2474      // Emit the abbreviations data.
2475      Abbrev->Emit(this);
2476    }
2477
2478    // Mark end of abbreviations.
2479    EmitULEB128(0, "EOM(3)");
2480
2481    Asm->OutStreamer.EmitLabel(getTempLabel("abbrev_end"));
2482  }
2483}
2484
2485/// emitEndOfLineMatrix - Emit the last address of the section and the end of
2486/// the line matrix.
2487///
2488void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2489  // Define last address of section.
2490  Asm->OutStreamer.AddComment("Extended Op");
2491  Asm->EmitInt8(0);
2492
2493  Asm->OutStreamer.AddComment("Op size");
2494  Asm->EmitInt8(TD->getPointerSize() + 1);
2495  Asm->OutStreamer.AddComment("DW_LNE_set_address");
2496  Asm->EmitInt8(dwarf::DW_LNE_set_address);
2497
2498  Asm->OutStreamer.AddComment("Section end label");
2499
2500  Asm->OutStreamer.EmitSymbolValue(getDWLabel("section_end", SectionEnd),
2501                                   TD->getPointerSize(), 0/*AddrSpace*/);
2502
2503  // Mark end of matrix.
2504  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2505  Asm->EmitInt8(0);
2506  Asm->EmitInt8(1);
2507  Asm->EmitInt8(1);
2508}
2509
2510/// emitDebugLines - Emit source line information.
2511///
2512void DwarfDebug::emitDebugLines() {
2513  // If the target is using .loc/.file, the assembler will be emitting the
2514  // .debug_line table automatically.
2515  if (MAI->hasDotLocAndDotFile())
2516    return;
2517
2518  // Minimum line delta, thus ranging from -10..(255-10).
2519  const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2520  // Maximum line delta, thus ranging from -10..(255-10).
2521  const int MaxLineDelta = 255 + MinLineDelta;
2522
2523  // Start the dwarf line section.
2524  Asm->OutStreamer.SwitchSection(
2525                            Asm->getObjFileLowering().getDwarfLineSection());
2526
2527  // Construct the section header.
2528  Asm->OutStreamer.AddComment("Length of Source Line Info");
2529  EmitDifference(getTempLabel("line_end"), getTempLabel("line_begin"), true);
2530  Asm->OutStreamer.EmitLabel(getTempLabel("line_begin"));
2531
2532  Asm->OutStreamer.AddComment("DWARF version number");
2533  Asm->EmitInt16(dwarf::DWARF_VERSION);
2534
2535  Asm->OutStreamer.AddComment("Prolog Length");
2536  EmitDifference(getTempLabel("line_prolog_end"),
2537                 getTempLabel("line_prolog_begin"), true);
2538  Asm->OutStreamer.EmitLabel(getTempLabel("line_prolog_begin"));
2539
2540  Asm->OutStreamer.AddComment("Minimum Instruction Length");
2541  Asm->EmitInt8(1);
2542  Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2543  Asm->EmitInt8(1);
2544  Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2545  Asm->EmitInt8(MinLineDelta);
2546  Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2547  Asm->EmitInt8(MaxLineDelta);
2548  Asm->OutStreamer.AddComment("Special Opcode Base");
2549  Asm->EmitInt8(-MinLineDelta);
2550
2551  // Line number standard opcode encodings argument count
2552  Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2553  Asm->EmitInt8(0);
2554  Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2555  Asm->EmitInt8(1);
2556  Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2557  Asm->EmitInt8(1);
2558  Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2559  Asm->EmitInt8(1);
2560  Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2561  Asm->EmitInt8(1);
2562  Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2563  Asm->EmitInt8(0);
2564  Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2565  Asm->EmitInt8(0);
2566  Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2567  Asm->EmitInt8(0);
2568  Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2569  Asm->EmitInt8(1);
2570
2571  // Emit directories.
2572  for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2573    const std::string &Dir = getSourceDirectoryName(DI);
2574    if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("Directory");
2575    Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2576  }
2577
2578  Asm->OutStreamer.AddComment("End of directories");
2579  Asm->EmitInt8(0);
2580
2581  // Emit files.
2582  for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2583    // Remember source id starts at 1.
2584    std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2585    const std::string &FN = getSourceFileName(Id.second);
2586    if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("Source");
2587    Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2588
2589    EmitULEB128(Id.first, "Directory #");
2590    EmitULEB128(0, "Mod date");
2591    EmitULEB128(0, "File size");
2592  }
2593
2594  Asm->OutStreamer.AddComment("End of files");
2595  Asm->EmitInt8(0);
2596
2597  Asm->OutStreamer.EmitLabel(getTempLabel("line_prolog_end"));
2598
2599  // A sequence for each text section.
2600  unsigned SecSrcLinesSize = SectionSourceLines.size();
2601
2602  for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2603    // Isolate current sections line info.
2604    const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2605
2606    // Dwarf assumes we start with first line of first source file.
2607    unsigned Source = 1;
2608    unsigned Line = 1;
2609
2610    // Construct rows of the address, source, line, column matrix.
2611    for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2612      const SrcLineInfo &LineInfo = LineInfos[i];
2613      unsigned LabelID = LineInfo.getLabelID();
2614      if (MMI->isLabelDeleted(LabelID)) continue;
2615
2616      if (LineInfo.getLine() == 0) continue;
2617
2618      if (Asm->isVerbose()) {
2619        std::pair<unsigned, unsigned> SrcID =
2620          getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2621        Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
2622                                    "/" +
2623                                    Twine(getSourceFileName(SrcID.second)) +
2624                                    ":" + Twine(LineInfo.getLine()));
2625      }
2626
2627      // Define the line address.
2628      Asm->OutStreamer.AddComment("Extended Op");
2629      Asm->EmitInt8(0);
2630      Asm->OutStreamer.AddComment("Op size");
2631      Asm->EmitInt8(TD->getPointerSize() + 1);
2632
2633      Asm->OutStreamer.AddComment("DW_LNE_set_address");
2634      Asm->EmitInt8(dwarf::DW_LNE_set_address);
2635
2636      Asm->OutStreamer.AddComment("Location label");
2637      Asm->OutStreamer.EmitSymbolValue(getDWLabel("label", LabelID),
2638                                       TD->getPointerSize(), 0/*AddrSpace*/);
2639
2640      // If change of source, then switch to the new source.
2641      if (Source != LineInfo.getSourceID()) {
2642        Source = LineInfo.getSourceID();
2643        Asm->OutStreamer.AddComment("DW_LNS_set_file");
2644        Asm->EmitInt8(dwarf::DW_LNS_set_file);
2645        EmitULEB128(Source, "New Source");
2646      }
2647
2648      // If change of line.
2649      if (Line != LineInfo.getLine()) {
2650        // Determine offset.
2651        int Offset = LineInfo.getLine() - Line;
2652        int Delta = Offset - MinLineDelta;
2653
2654        // Update line.
2655        Line = LineInfo.getLine();
2656
2657        // If delta is small enough and in range...
2658        if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2659          // ... then use fast opcode.
2660          Asm->OutStreamer.AddComment("Line Delta");
2661          Asm->EmitInt8(Delta - MinLineDelta);
2662        } else {
2663          // ... otherwise use long hand.
2664          Asm->OutStreamer.AddComment("DW_LNS_advance_line");
2665          Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2666          EmitSLEB128(Offset, "Line Offset");
2667          Asm->OutStreamer.AddComment("DW_LNS_copy");
2668          Asm->EmitInt8(dwarf::DW_LNS_copy);
2669        }
2670      } else {
2671        // Copy the previous row (different address or source)
2672        Asm->OutStreamer.AddComment("DW_LNS_copy");
2673        Asm->EmitInt8(dwarf::DW_LNS_copy);
2674      }
2675    }
2676
2677    emitEndOfLineMatrix(j + 1);
2678  }
2679
2680  if (SecSrcLinesSize == 0)
2681    // Because we're emitting a debug_line section, we still need a line
2682    // table. The linker and friends expect it to exist. If there's nothing to
2683    // put into it, emit an empty table.
2684    emitEndOfLineMatrix(1);
2685
2686  Asm->OutStreamer.EmitLabel(getTempLabel("line_end"));
2687}
2688
2689/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2690///
2691void DwarfDebug::emitCommonDebugFrame() {
2692  if (!MAI->doesDwarfRequireFrameSection())
2693    return;
2694
2695  int stackGrowth =
2696    Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2697      TargetFrameInfo::StackGrowsUp ?
2698    TD->getPointerSize() : -TD->getPointerSize();
2699
2700  // Start the dwarf frame section.
2701  Asm->OutStreamer.SwitchSection(
2702                              Asm->getObjFileLowering().getDwarfFrameSection());
2703
2704  Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common"));
2705  Asm->OutStreamer.AddComment("Length of Common Information Entry");
2706  EmitDifference(getTempLabel("debug_frame_common_end"),
2707                 getTempLabel("debug_frame_common_begin"), true);
2708
2709  Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common_begin"));
2710  Asm->OutStreamer.AddComment("CIE Identifier Tag");
2711  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2712  Asm->OutStreamer.AddComment("CIE Version");
2713  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2714  Asm->OutStreamer.AddComment("CIE Augmentation");
2715  Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
2716  EmitULEB128(1, "CIE Code Alignment Factor");
2717  EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
2718  Asm->OutStreamer.AddComment("CIE RA Column");
2719  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2720
2721  std::vector<MachineMove> Moves;
2722  RI->getInitialFrameState(Moves);
2723
2724  EmitFrameMoves(NULL, 0, Moves, false);
2725
2726  Asm->EmitAlignment(2, 0, 0, false);
2727  Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common_end"));
2728}
2729
2730/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2731/// section.
2732void
2733DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2734  if (!MAI->doesDwarfRequireFrameSection())
2735    return;
2736
2737  // Start the dwarf frame section.
2738  Asm->OutStreamer.SwitchSection(
2739                              Asm->getObjFileLowering().getDwarfFrameSection());
2740
2741  Asm->OutStreamer.AddComment("Length of Frame Information Entry");
2742  EmitDifference(getDWLabel("debug_frame_end", DebugFrameInfo.Number),
2743                 getDWLabel("debug_frame_begin", DebugFrameInfo.Number), true);
2744
2745  Asm->OutStreamer.EmitLabel(getDWLabel("debug_frame_begin",
2746                                        DebugFrameInfo.Number));
2747
2748  Asm->OutStreamer.AddComment("FDE CIE offset");
2749  EmitSectionOffset(getTempLabel("debug_frame_common"),
2750                    getTempLabel("section_debug_frame"), true, false);
2751
2752  Asm->OutStreamer.AddComment("FDE initial location");
2753  Asm->OutStreamer.EmitSymbolValue(getDWLabel("func_begin",
2754                                              DebugFrameInfo.Number),
2755                                   TD->getPointerSize(), 0/*AddrSpace*/);
2756
2757
2758
2759  Asm->OutStreamer.AddComment("FDE address range");
2760  EmitDifference(getDWLabel("func_end", DebugFrameInfo.Number),
2761                 getDWLabel("func_begin", DebugFrameInfo.Number));
2762
2763  EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2764                 false);
2765
2766  Asm->EmitAlignment(2, 0, 0, false);
2767  Asm->OutStreamer.EmitLabel(getDWLabel("debug_frame_end",
2768                                        DebugFrameInfo.Number));
2769}
2770
2771/// emitDebugPubNames - Emit visible names into a debug pubnames section.
2772///
2773void DwarfDebug::emitDebugPubNames() {
2774  // Start the dwarf pubnames section.
2775  Asm->OutStreamer.SwitchSection(
2776                          Asm->getObjFileLowering().getDwarfPubNamesSection());
2777
2778  Asm->OutStreamer.AddComment("Length of Public Names Info");
2779  EmitDifference(getDWLabel("pubnames_end", ModuleCU->getID()),
2780                 getDWLabel("pubnames_begin", ModuleCU->getID()), true);
2781
2782  Asm->OutStreamer.EmitLabel(getDWLabel("pubnames_begin", ModuleCU->getID()));
2783
2784  Asm->OutStreamer.AddComment("DWARF Version");
2785  Asm->EmitInt16(dwarf::DWARF_VERSION);
2786
2787  Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2788  EmitSectionOffset(getDWLabel("info_begin", ModuleCU->getID()),
2789                    getTempLabel("section_info"),
2790                    true, false);
2791
2792  Asm->OutStreamer.AddComment("Compilation Unit Length");
2793  EmitDifference(getDWLabel("info_end", ModuleCU->getID()),
2794                 getDWLabel("info_begin", ModuleCU->getID()),
2795                 true);
2796
2797  const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
2798  for (StringMap<DIE*>::const_iterator
2799         GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2800    const char *Name = GI->getKeyData();
2801    DIE *Entity = GI->second;
2802
2803    Asm->OutStreamer.AddComment("DIE offset");
2804    Asm->EmitInt32(Entity->getOffset());
2805
2806    if (Asm->VerboseAsm)
2807      Asm->OutStreamer.AddComment("External Name");
2808    Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2809  }
2810
2811  Asm->OutStreamer.AddComment("End Mark");
2812  Asm->EmitInt32(0);
2813  Asm->OutStreamer.EmitLabel(getDWLabel("pubnames_end", ModuleCU->getID()));
2814}
2815
2816void DwarfDebug::emitDebugPubTypes() {
2817  // Start the dwarf pubnames section.
2818  Asm->OutStreamer.SwitchSection(
2819                          Asm->getObjFileLowering().getDwarfPubTypesSection());
2820  Asm->OutStreamer.AddComment("Length of Public Types Info");
2821  EmitDifference(getDWLabel("pubtypes_end", ModuleCU->getID()),
2822                 getDWLabel("pubtypes_begin", ModuleCU->getID()), true);
2823
2824  Asm->OutStreamer.EmitLabel(getDWLabel("pubtypes_begin", ModuleCU->getID()));
2825
2826  if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DWARF Version");
2827  Asm->EmitInt16(dwarf::DWARF_VERSION);
2828
2829  Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
2830  EmitSectionOffset(getDWLabel("info_begin", ModuleCU->getID()),
2831                    getTempLabel("section_info"), true, false);
2832
2833  Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
2834  EmitDifference(getDWLabel("info_end", ModuleCU->getID()),
2835                 getDWLabel("info_begin", ModuleCU->getID()),
2836                 true);
2837
2838  const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
2839  for (StringMap<DIE*>::const_iterator
2840         GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2841    const char *Name = GI->getKeyData();
2842    DIE * Entity = GI->second;
2843
2844    if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DIE offset");
2845    Asm->EmitInt32(Entity->getOffset());
2846
2847    if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("External Name");
2848    Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2849  }
2850
2851  Asm->OutStreamer.AddComment("End Mark");
2852  Asm->EmitInt32(0);
2853  Asm->OutStreamer.EmitLabel(getDWLabel("pubtypes_end", ModuleCU->getID()));
2854}
2855
2856/// emitDebugStr - Emit visible names into a debug str section.
2857///
2858void DwarfDebug::emitDebugStr() {
2859  // Check to see if it is worth the effort.
2860  if (StringPool.empty()) return;
2861
2862  // Start the dwarf str section.
2863  Asm->OutStreamer.SwitchSection(
2864                                Asm->getObjFileLowering().getDwarfStrSection());
2865
2866  // For each of strings in the string pool.
2867  for (unsigned StringID = 1, N = StringPool.size(); StringID <= N; ++StringID){
2868    // Emit a label for reference from debug information entries.
2869    Asm->OutStreamer.EmitLabel(getDWLabel("string", StringID));
2870
2871    // Emit the string itself.
2872    const std::string &String = StringPool[StringID];
2873    Asm->OutStreamer.EmitBytes(StringRef(String.c_str(), String.size()+1), 0);
2874  }
2875}
2876
2877/// emitDebugLoc - Emit visible names into a debug loc section.
2878///
2879void DwarfDebug::emitDebugLoc() {
2880  // Start the dwarf loc section.
2881  Asm->OutStreamer.SwitchSection(
2882                              Asm->getObjFileLowering().getDwarfLocSection());
2883}
2884
2885/// EmitDebugARanges - Emit visible names into a debug aranges section.
2886///
2887void DwarfDebug::EmitDebugARanges() {
2888  // Start the dwarf aranges section.
2889  Asm->OutStreamer.SwitchSection(
2890                          Asm->getObjFileLowering().getDwarfARangesSection());
2891}
2892
2893/// emitDebugRanges - Emit visible names into a debug ranges section.
2894///
2895void DwarfDebug::emitDebugRanges() {
2896  // Start the dwarf ranges section.
2897  Asm->OutStreamer.SwitchSection(
2898                            Asm->getObjFileLowering().getDwarfRangesSection());
2899}
2900
2901/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2902///
2903void DwarfDebug::emitDebugMacInfo() {
2904  if (const MCSection *LineInfo =
2905      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2906    // Start the dwarf macinfo section.
2907    Asm->OutStreamer.SwitchSection(LineInfo);
2908  }
2909}
2910
2911/// emitDebugInlineInfo - Emit inline info using following format.
2912/// Section Header:
2913/// 1. length of section
2914/// 2. Dwarf version number
2915/// 3. address size.
2916///
2917/// Entries (one "entry" for each function that was inlined):
2918///
2919/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2920///   otherwise offset into __debug_str for regular function name.
2921/// 2. offset into __debug_str section for regular function name.
2922/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2923/// instances for the function.
2924///
2925/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2926/// inlined instance; the die_offset points to the inlined_subroutine die in the
2927/// __debug_info section, and the low_pc is the starting address for the
2928/// inlining instance.
2929void DwarfDebug::emitDebugInlineInfo() {
2930  if (!MAI->doesDwarfUsesInlineInfoSection())
2931    return;
2932
2933  if (!ModuleCU)
2934    return;
2935
2936  Asm->OutStreamer.SwitchSection(
2937                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
2938
2939  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2940  EmitDifference(getDWLabel("debug_inlined_end", 1),
2941                 getDWLabel("debug_inlined_begin", 1), true);
2942
2943  Asm->OutStreamer.EmitLabel(getDWLabel("debug_inlined_begin", 1));
2944
2945  Asm->OutStreamer.AddComment("Dwarf Version");
2946  Asm->EmitInt16(dwarf::DWARF_VERSION);
2947  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2948  Asm->EmitInt8(TD->getPointerSize());
2949
2950  for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2951         E = InlinedSPNodes.end(); I != E; ++I) {
2952
2953    MDNode *Node = *I;
2954    DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2955      = InlineInfo.find(Node);
2956    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2957    DISubprogram SP(Node);
2958    StringRef LName = SP.getLinkageName();
2959    StringRef Name = SP.getName();
2960
2961    Asm->OutStreamer.AddComment("MIPS linkage name");
2962    if (LName.empty()) {
2963      Asm->OutStreamer.EmitBytes(Name, 0);
2964      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2965    } else
2966      EmitSectionOffset(getDWLabel("string",
2967                                   StringPool.idFor(getRealLinkageName(LName))),
2968                        getTempLabel("section_str"), true);
2969
2970    Asm->OutStreamer.AddComment("Function name");
2971    EmitSectionOffset(getDWLabel("string", StringPool.idFor(Name)),
2972                      getTempLabel("section_str"), false, true);
2973    EmitULEB128(Labels.size(), "Inline count");
2974
2975    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2976           LE = Labels.end(); LI != LE; ++LI) {
2977      if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DIE offset");
2978      Asm->EmitInt32(LI->second->getOffset());
2979
2980      if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("low_pc");
2981      Asm->OutStreamer.EmitSymbolValue(LI->first, TD->getPointerSize(), 0);
2982    }
2983  }
2984
2985  Asm->OutStreamer.EmitLabel(getDWLabel("debug_inlined_end", 1));
2986}
2987