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