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