DwarfDebug.cpp revision 1005c8e1ce2cde1625a753fc841e7e866adb66d4
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(InsnBeforeLabelMap.lookup(RI->first));
1397      DebugRangeSymbols.push_back(InsnAfterLabelMap.lookup(RI->second));
1398    }
1399    DebugRangeSymbols.push_back(NULL);
1400    DebugRangeSymbols.push_back(NULL);
1401    return ScopeDIE;
1402  }
1403
1404  MCSymbol *Start = InsnBeforeLabelMap.lookup(RI->first);
1405  MCSymbol *End = InsnAfterLabelMap.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 = InsnBeforeLabelMap.lookup(RI->first);
1433  MCSymbol *EndLabel = InsnAfterLabelMap.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  addLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, TextSectionSym);
1743  addLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1744           Asm->GetTempSymbol("text_end"));
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      DIVariable DV(
2085        const_cast<MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2086                               .getMetadata()));
2087      if (DV.getTag() == dwarf::DW_TAG_arg_variable)  {
2088        // FIXME Handle inlined subroutine arguments.
2089        DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2090        CurrentFnDbgScope->addVariable(ArgVar);
2091        DbgValueStartMap[MInsn] = ArgVar;
2092        continue;
2093      }
2094
2095      DebugLoc DL = MInsn->getDebugLoc();
2096      if (DL.isUnknown()) continue;
2097      DbgScope *Scope = 0;
2098      if (MDNode *IA = DL.getInlinedAt(Ctx))
2099        Scope = ConcreteScopes.lookup(IA);
2100      if (Scope == 0)
2101        Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2102
2103      // If variable scope is not found then skip this variable.
2104      if (Scope == 0)
2105        continue;
2106
2107      DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2108      DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2109      DbgValueStartMap[MInsn] = RegVar;
2110      Scope->addVariable(RegVar);
2111    }
2112  }
2113}
2114
2115/// beginScope - Process beginning of a scope.
2116void DwarfDebug::beginScope(const MachineInstr *MI) {
2117  // Check location.
2118  DebugLoc DL = MI->getDebugLoc();
2119  if (DL.isUnknown())
2120    return;
2121
2122  MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2123
2124  // FIXME: Should only verify each scope once!
2125  if (!DIScope(Scope).Verify())
2126    return;
2127
2128  // DBG_VALUE instruction establishes new value.
2129  if (MI->isDebugValue()) {
2130    DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2131      = DbgValueStartMap.find(MI);
2132    if (DI != DbgValueStartMap.end()) {
2133      MCSymbol *Label = NULL;
2134      if (DL == PrevInstLoc)
2135        Label = PrevLabel;
2136      else {
2137        Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2138        PrevInstLoc = DL;
2139        PrevLabel = Label;
2140      }
2141      DI->second->setDbgValueLabel(Label);
2142    }
2143    return;
2144  }
2145
2146  // Emit a label to indicate location change. This is used for line
2147  // table even if this instruction does not start a new scope.
2148  MCSymbol *Label = NULL;
2149  if (DL == PrevInstLoc)
2150    Label = PrevLabel;
2151  else {
2152    Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2153    PrevInstLoc = DL;
2154    PrevLabel = Label;
2155  }
2156
2157  // If this instruction begins a scope then note down corresponding label.
2158  if (InsnsBeginScopeSet.count(MI) != 0)
2159    InsnBeforeLabelMap[MI] = Label;
2160}
2161
2162/// endScope - Process end of a scope.
2163void DwarfDebug::endScope(const MachineInstr *MI) {
2164  if (InsnsEndScopeSet.count(MI) != 0) {
2165    // Emit a label if this instruction ends a scope.
2166    MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2167    Asm->OutStreamer.EmitLabel(Label);
2168    InsnAfterLabelMap[MI] = Label;
2169  }
2170}
2171
2172/// getOrCreateDbgScope - Create DbgScope for the scope.
2173DbgScope *DwarfDebug::getOrCreateDbgScope(MDNode *Scope, MDNode *InlinedAt) {
2174  if (!InlinedAt) {
2175    DbgScope *WScope = DbgScopeMap.lookup(Scope);
2176    if (WScope)
2177      return WScope;
2178    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2179    DbgScopeMap.insert(std::make_pair(Scope, WScope));
2180    if (DIDescriptor(Scope).isLexicalBlock()) {
2181      DbgScope *Parent =
2182        getOrCreateDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2183      WScope->setParent(Parent);
2184      Parent->addScope(WScope);
2185    }
2186
2187    if (!WScope->getParent()) {
2188      StringRef SPName = DISubprogram(Scope).getLinkageName();
2189      if (SPName == Asm->MF->getFunction()->getName())
2190        CurrentFnDbgScope = WScope;
2191    }
2192
2193    return WScope;
2194  }
2195
2196  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2197  if (WScope)
2198    return WScope;
2199
2200  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2201  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2202  DILocation DL(InlinedAt);
2203  DbgScope *Parent =
2204    getOrCreateDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2205  WScope->setParent(Parent);
2206  Parent->addScope(WScope);
2207
2208  ConcreteScopes[InlinedAt] = WScope;
2209  getOrCreateAbstractScope(Scope);
2210
2211  return WScope;
2212}
2213
2214/// hasValidLocation - Return true if debug location entry attached with
2215/// machine instruction encodes valid location info.
2216static bool hasValidLocation(LLVMContext &Ctx,
2217                             const MachineInstr *MInsn,
2218                             MDNode *&Scope, MDNode *&InlinedAt) {
2219  if (MInsn->isDebugValue())
2220    return false;
2221  DebugLoc DL = MInsn->getDebugLoc();
2222  if (DL.isUnknown()) return false;
2223
2224  MDNode *S = DL.getScope(Ctx);
2225
2226  // There is no need to create another DIE for compile unit. For all
2227  // other scopes, create one DbgScope now. This will be translated
2228  // into a scope DIE at the end.
2229  if (DIScope(S).isCompileUnit()) return false;
2230
2231  Scope = S;
2232  InlinedAt = DL.getInlinedAt(Ctx);
2233  return true;
2234}
2235
2236/// calculateDominanceGraph - Calculate dominance graph for DbgScope
2237/// hierarchy.
2238static void calculateDominanceGraph(DbgScope *Scope) {
2239  assert (Scope && "Unable to calculate scop edominance graph!");
2240  SmallVector<DbgScope *, 4> WorkStack;
2241  WorkStack.push_back(Scope);
2242  unsigned Counter = 0;
2243  while (!WorkStack.empty()) {
2244    DbgScope *WS = WorkStack.back();
2245    const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2246    bool visitedChildren = false;
2247    for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2248           SE = Children.end(); SI != SE; ++SI) {
2249      DbgScope *ChildScope = *SI;
2250      if (!ChildScope->getDFSOut()) {
2251        WorkStack.push_back(ChildScope);
2252        visitedChildren = true;
2253        ChildScope->setDFSIn(++Counter);
2254        break;
2255      }
2256    }
2257    if (!visitedChildren) {
2258      WorkStack.pop_back();
2259      WS->setDFSOut(++Counter);
2260    }
2261  }
2262}
2263
2264/// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2265static
2266void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2267                       DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2268{
2269#ifndef NDEBUG
2270  unsigned PrevDFSIn = 0;
2271  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2272       I != E; ++I) {
2273    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2274         II != IE; ++II) {
2275      const MachineInstr *MInsn = II;
2276      MDNode *Scope = NULL;
2277      MDNode *InlinedAt = NULL;
2278
2279      // Check if instruction has valid location information.
2280      if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2281        dbgs() << " [ ";
2282        if (InlinedAt)
2283          dbgs() << "*";
2284        DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2285          MI2ScopeMap.find(MInsn);
2286        if (DI != MI2ScopeMap.end()) {
2287          DbgScope *S = DI->second;
2288          dbgs() << S->getDFSIn();
2289          PrevDFSIn = S->getDFSIn();
2290        } else
2291          dbgs() << PrevDFSIn;
2292      } else
2293        dbgs() << " [ x" << PrevDFSIn;
2294      dbgs() << " ]";
2295      MInsn->dump();
2296    }
2297    dbgs() << "\n";
2298  }
2299#endif
2300}
2301/// extractScopeInformation - Scan machine instructions in this function
2302/// and collect DbgScopes. Return true, if at least one scope was found.
2303bool DwarfDebug::extractScopeInformation() {
2304  // If scope information was extracted using .dbg intrinsics then there is not
2305  // any need to extract these information by scanning each instruction.
2306  if (!DbgScopeMap.empty())
2307    return false;
2308
2309  // Scan each instruction and create scopes. First build working set of scopes.
2310  LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2311  SmallVector<DbgRange, 4> MIRanges;
2312  DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2313  MDNode *PrevScope = NULL;
2314  MDNode *PrevInlinedAt = NULL;
2315  const MachineInstr *RangeBeginMI = NULL;
2316  const MachineInstr *PrevMI = NULL;
2317  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2318       I != E; ++I) {
2319    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2320         II != IE; ++II) {
2321      const MachineInstr *MInsn = II;
2322      MDNode *Scope = NULL;
2323      MDNode *InlinedAt = NULL;
2324
2325      // Check if instruction has valid location information.
2326      if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2327        PrevMI = MInsn;
2328        continue;
2329      }
2330
2331      // If scope has not changed then skip this instruction.
2332      if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2333        PrevMI = MInsn;
2334        continue;
2335      }
2336
2337      if (RangeBeginMI) {
2338        // If we have alread seen a beginning of a instruction range and
2339        // current instruction scope does not match scope of first instruction
2340        // in this range then create a new instruction range.
2341        DbgRange R(RangeBeginMI, PrevMI);
2342        MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2343        MIRanges.push_back(R);
2344      }
2345
2346      // This is a beginning of a new instruction range.
2347      RangeBeginMI = MInsn;
2348
2349      // Reset previous markers.
2350      PrevMI = MInsn;
2351      PrevScope = Scope;
2352      PrevInlinedAt = InlinedAt;
2353    }
2354  }
2355
2356  // Create last instruction range.
2357  if (RangeBeginMI && PrevMI && PrevScope) {
2358    DbgRange R(RangeBeginMI, PrevMI);
2359    MIRanges.push_back(R);
2360    MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2361  }
2362
2363  if (!CurrentFnDbgScope)
2364    return false;
2365
2366  calculateDominanceGraph(CurrentFnDbgScope);
2367  if (PrintDbgScope)
2368    printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2369
2370  // Find ranges of instructions covered by each DbgScope;
2371  DbgScope *PrevDbgScope = NULL;
2372  for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2373         RE = MIRanges.end(); RI != RE; ++RI) {
2374    const DbgRange &R = *RI;
2375    DbgScope *S = MI2ScopeMap.lookup(R.first);
2376    assert (S && "Lost DbgScope for a machine instruction!");
2377    if (PrevDbgScope && !PrevDbgScope->dominates(S))
2378      PrevDbgScope->closeInsnRange(S);
2379    S->openInsnRange(R.first);
2380    S->extendInsnRange(R.second);
2381    PrevDbgScope = S;
2382  }
2383
2384  if (PrevDbgScope)
2385    PrevDbgScope->closeInsnRange();
2386
2387  identifyScopeMarkers();
2388
2389  return !DbgScopeMap.empty();
2390}
2391
2392/// identifyScopeMarkers() -
2393/// Each DbgScope has first instruction and last instruction to mark beginning
2394/// and end of a scope respectively. Create an inverse map that list scopes
2395/// starts (and ends) with an instruction. One instruction may start (or end)
2396/// multiple scopes. Ignore scopes that are not reachable.
2397void DwarfDebug::identifyScopeMarkers() {
2398  SmallVector<DbgScope *, 4> WorkList;
2399  WorkList.push_back(CurrentFnDbgScope);
2400  while (!WorkList.empty()) {
2401    DbgScope *S = WorkList.pop_back_val();
2402
2403    const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2404    if (!Children.empty())
2405      for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2406             SE = Children.end(); SI != SE; ++SI)
2407        WorkList.push_back(*SI);
2408
2409    if (S->isAbstractScope())
2410      continue;
2411
2412    const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2413    if (Ranges.empty())
2414      continue;
2415    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2416           RE = Ranges.end(); RI != RE; ++RI) {
2417      assert(RI->first && "DbgRange does not have first instruction!");
2418      assert(RI->second && "DbgRange does not have second instruction!");
2419      InsnsBeginScopeSet.insert(RI->first);
2420      InsnsEndScopeSet.insert(RI->second);
2421    }
2422  }
2423}
2424
2425/// FindFirstDebugLoc - Find the first debug location in the function. This
2426/// is intended to be an approximation for the source position of the
2427/// beginning of the function.
2428static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2429  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2430       I != E; ++I)
2431    for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2432         MBBI != MBBE; ++MBBI) {
2433      DebugLoc DL = MBBI->getDebugLoc();
2434      if (!DL.isUnknown())
2435        return DL;
2436    }
2437  return DebugLoc();
2438}
2439
2440/// beginFunction - Gather pre-function debug information.  Assumes being
2441/// emitted immediately after the function entry point.
2442void DwarfDebug::beginFunction(const MachineFunction *MF) {
2443  if (!MMI->hasDebugInfo()) return;
2444  if (!extractScopeInformation()) return;
2445
2446  collectVariableInfo();
2447
2448  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2449                                        Asm->getFunctionNumber());
2450  // Assumes in correct section after the entry point.
2451  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2452
2453  // Emit label for the implicitly defined dbg.stoppoint at the start of the
2454  // function.
2455  DebugLoc FDL = FindFirstDebugLoc(MF);
2456  if (FDL.isUnknown()) return;
2457
2458  MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2459
2460  DISubprogram SP = getDISubprogram(Scope);
2461  unsigned Line, Col;
2462  if (SP.Verify()) {
2463    Line = SP.getLineNumber();
2464    Col = 0;
2465  } else {
2466    Line = FDL.getLine();
2467    Col = FDL.getCol();
2468  }
2469
2470  recordSourceLine(Line, Col, Scope);
2471}
2472
2473/// endFunction - Gather and emit post-function debug information.
2474///
2475void DwarfDebug::endFunction(const MachineFunction *MF) {
2476  if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2477
2478  if (CurrentFnDbgScope) {
2479    // Define end label for subprogram.
2480    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2481                                                  Asm->getFunctionNumber()));
2482
2483    // Get function line info.
2484    if (!Lines.empty()) {
2485      // Get section line info.
2486      unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2487      if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2488      std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2489      // Append the function info to section info.
2490      SectionLineInfos.insert(SectionLineInfos.end(),
2491                              Lines.begin(), Lines.end());
2492    }
2493
2494    // Construct abstract scopes.
2495    for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2496           AE = AbstractScopesList.end(); AI != AE; ++AI)
2497      constructScopeDIE(*AI);
2498
2499    constructScopeDIE(CurrentFnDbgScope);
2500
2501    DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2502                                                 MMI->getFrameMoves()));
2503  }
2504
2505  // Clear debug info
2506  CurrentFnDbgScope = NULL;
2507  DeleteContainerSeconds(DbgScopeMap);
2508  InsnsBeginScopeSet.clear();
2509  InsnsEndScopeSet.clear();
2510  DbgValueStartMap.clear();
2511  ConcreteScopes.clear();
2512  DeleteContainerSeconds(AbstractScopes);
2513  AbstractScopesList.clear();
2514  AbstractVariables.clear();
2515  InsnBeforeLabelMap.clear();
2516  InsnAfterLabelMap.clear();
2517  Lines.clear();
2518  PrevLabel = NULL;
2519}
2520
2521/// recordSourceLine - Register a source line with debug info. Returns the
2522/// unique label that was emitted and which provides correspondence to
2523/// the source line list.
2524MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
2525  StringRef Dir;
2526  StringRef Fn;
2527
2528  DIDescriptor Scope(S);
2529  if (Scope.isCompileUnit()) {
2530    DICompileUnit CU(S);
2531    Dir = CU.getDirectory();
2532    Fn = CU.getFilename();
2533  } else if (Scope.isSubprogram()) {
2534    DISubprogram SP(S);
2535    Dir = SP.getDirectory();
2536    Fn = SP.getFilename();
2537  } else if (Scope.isLexicalBlock()) {
2538    DILexicalBlock DB(S);
2539    Dir = DB.getDirectory();
2540    Fn = DB.getFilename();
2541  } else
2542    assert(0 && "Unexpected scope info");
2543
2544  unsigned Src = GetOrCreateSourceID(Dir, Fn);
2545  MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2546  Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2547
2548  Asm->OutStreamer.EmitLabel(Label);
2549  return Label;
2550}
2551
2552//===----------------------------------------------------------------------===//
2553// Emit Methods
2554//===----------------------------------------------------------------------===//
2555
2556/// computeSizeAndOffset - Compute the size and offset of a DIE.
2557///
2558unsigned
2559DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2560  // Get the children.
2561  const std::vector<DIE *> &Children = Die->getChildren();
2562
2563  // If not last sibling and has children then add sibling offset attribute.
2564  if (!Last && !Children.empty())
2565    Die->addSiblingOffset(DIEValueAllocator);
2566
2567  // Record the abbreviation.
2568  assignAbbrevNumber(Die->getAbbrev());
2569
2570  // Get the abbreviation for this DIE.
2571  unsigned AbbrevNumber = Die->getAbbrevNumber();
2572  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2573
2574  // Set DIE offset
2575  Die->setOffset(Offset);
2576
2577  // Start the size with the size of abbreviation code.
2578  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2579
2580  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2581  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2582
2583  // Size the DIE attribute values.
2584  for (unsigned i = 0, N = Values.size(); i < N; ++i)
2585    // Size attribute value.
2586    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2587
2588  // Size the DIE children if any.
2589  if (!Children.empty()) {
2590    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2591           "Children flag not set");
2592
2593    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2594      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2595
2596    // End of children marker.
2597    Offset += sizeof(int8_t);
2598  }
2599
2600  Die->setSize(Offset - Die->getOffset());
2601  return Offset;
2602}
2603
2604/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2605///
2606void DwarfDebug::computeSizeAndOffsets() {
2607  // Compute size of compile unit header.
2608  static unsigned Offset =
2609    sizeof(int32_t) + // Length of Compilation Unit Info
2610    sizeof(int16_t) + // DWARF version number
2611    sizeof(int32_t) + // Offset Into Abbrev. Section
2612    sizeof(int8_t);   // Pointer Size (in bytes)
2613
2614  computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2615}
2616
2617/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2618/// temporary label to it if SymbolStem is specified.
2619static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2620                                const char *SymbolStem = 0) {
2621  Asm->OutStreamer.SwitchSection(Section);
2622  if (!SymbolStem) return 0;
2623
2624  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2625  Asm->OutStreamer.EmitLabel(TmpSym);
2626  return TmpSym;
2627}
2628
2629/// EmitSectionLabels - Emit initial Dwarf sections with a label at
2630/// the start of each one.
2631void DwarfDebug::EmitSectionLabels() {
2632  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2633
2634  // Dwarf sections base addresses.
2635  if (Asm->MAI->doesDwarfRequireFrameSection()) {
2636    DwarfFrameSectionSym =
2637      EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2638   }
2639
2640  DwarfInfoSectionSym =
2641    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2642  DwarfAbbrevSectionSym =
2643    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2644  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2645
2646  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2647    EmitSectionSym(Asm, MacroInfo);
2648
2649  EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2650  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2651  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2652  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2653  DwarfStrSectionSym =
2654    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2655  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2656                                             "debug_range");
2657
2658  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2659  EmitSectionSym(Asm, TLOF.getDataSection());
2660}
2661
2662/// emitDIE - Recusively Emits a debug information entry.
2663///
2664void DwarfDebug::emitDIE(DIE *Die) {
2665  // Get the abbreviation for this DIE.
2666  unsigned AbbrevNumber = Die->getAbbrevNumber();
2667  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2668
2669  // Emit the code (index) for the abbreviation.
2670  if (Asm->isVerbose())
2671    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2672                                Twine::utohexstr(Die->getOffset()) + ":0x" +
2673                                Twine::utohexstr(Die->getSize()) + " " +
2674                                dwarf::TagString(Abbrev->getTag()));
2675  Asm->EmitULEB128(AbbrevNumber);
2676
2677  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2678  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2679
2680  // Emit the DIE attribute values.
2681  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2682    unsigned Attr = AbbrevData[i].getAttribute();
2683    unsigned Form = AbbrevData[i].getForm();
2684    assert(Form && "Too many attributes for DIE (check abbreviation)");
2685
2686    if (Asm->isVerbose())
2687      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2688
2689    switch (Attr) {
2690    case dwarf::DW_AT_sibling:
2691      Asm->EmitInt32(Die->getSiblingOffset());
2692      break;
2693    case dwarf::DW_AT_abstract_origin: {
2694      DIEEntry *E = cast<DIEEntry>(Values[i]);
2695      DIE *Origin = E->getEntry();
2696      unsigned Addr = Origin->getOffset();
2697      Asm->EmitInt32(Addr);
2698      break;
2699    }
2700    case dwarf::DW_AT_ranges: {
2701      // DW_AT_range Value encodes offset in debug_range section.
2702      DIEInteger *V = cast<DIEInteger>(Values[i]);
2703      Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2704                                     V->getValue(),
2705                                     DwarfDebugRangeSectionSym,
2706                                     4);
2707      break;
2708    }
2709    default:
2710      // Emit an attribute using the defined form.
2711      Values[i]->EmitValue(Asm, Form);
2712      break;
2713    }
2714  }
2715
2716  // Emit the DIE children if any.
2717  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2718    const std::vector<DIE *> &Children = Die->getChildren();
2719
2720    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2721      emitDIE(Children[j]);
2722
2723    if (Asm->isVerbose())
2724      Asm->OutStreamer.AddComment("End Of Children Mark");
2725    Asm->EmitInt8(0);
2726  }
2727}
2728
2729/// emitDebugInfo - Emit the debug info section.
2730///
2731void DwarfDebug::emitDebugInfo() {
2732  // Start debug info section.
2733  Asm->OutStreamer.SwitchSection(
2734                            Asm->getObjFileLowering().getDwarfInfoSection());
2735  DIE *Die = ModuleCU->getCUDie();
2736
2737  // Emit the compile units header.
2738  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2739                                                ModuleCU->getID()));
2740
2741  // Emit size of content not including length itself
2742  unsigned ContentSize = Die->getSize() +
2743    sizeof(int16_t) + // DWARF version number
2744    sizeof(int32_t) + // Offset Into Abbrev. Section
2745    sizeof(int8_t) +  // Pointer Size (in bytes)
2746    sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2747
2748  Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2749  Asm->EmitInt32(ContentSize);
2750  Asm->OutStreamer.AddComment("DWARF version number");
2751  Asm->EmitInt16(dwarf::DWARF_VERSION);
2752  Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2753  Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2754                         DwarfAbbrevSectionSym);
2755  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2756  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2757
2758  emitDIE(Die);
2759  // FIXME - extra padding for gdb bug.
2760  Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2761  Asm->EmitInt8(0);
2762  Asm->EmitInt8(0);
2763  Asm->EmitInt8(0);
2764  Asm->EmitInt8(0);
2765  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID()));
2766}
2767
2768/// emitAbbreviations - Emit the abbreviation section.
2769///
2770void DwarfDebug::emitAbbreviations() const {
2771  // Check to see if it is worth the effort.
2772  if (!Abbreviations.empty()) {
2773    // Start the debug abbrev section.
2774    Asm->OutStreamer.SwitchSection(
2775                            Asm->getObjFileLowering().getDwarfAbbrevSection());
2776
2777    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2778
2779    // For each abbrevation.
2780    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2781      // Get abbreviation data
2782      const DIEAbbrev *Abbrev = Abbreviations[i];
2783
2784      // Emit the abbrevations code (base 1 index.)
2785      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2786
2787      // Emit the abbreviations data.
2788      Abbrev->Emit(Asm);
2789    }
2790
2791    // Mark end of abbreviations.
2792    Asm->EmitULEB128(0, "EOM(3)");
2793
2794    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2795  }
2796}
2797
2798/// emitEndOfLineMatrix - Emit the last address of the section and the end of
2799/// the line matrix.
2800///
2801void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2802  // Define last address of section.
2803  Asm->OutStreamer.AddComment("Extended Op");
2804  Asm->EmitInt8(0);
2805
2806  Asm->OutStreamer.AddComment("Op size");
2807  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2808  Asm->OutStreamer.AddComment("DW_LNE_set_address");
2809  Asm->EmitInt8(dwarf::DW_LNE_set_address);
2810
2811  Asm->OutStreamer.AddComment("Section end label");
2812
2813  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2814                                   Asm->getTargetData().getPointerSize(),
2815                                   0/*AddrSpace*/);
2816
2817  // Mark end of matrix.
2818  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2819  Asm->EmitInt8(0);
2820  Asm->EmitInt8(1);
2821  Asm->EmitInt8(1);
2822}
2823
2824/// emitDebugLines - Emit source line information.
2825///
2826void DwarfDebug::emitDebugLines() {
2827  // If the target is using .loc/.file, the assembler will be emitting the
2828  // .debug_line table automatically.
2829  if (Asm->MAI->hasDotLocAndDotFile())
2830    return;
2831
2832  // Minimum line delta, thus ranging from -10..(255-10).
2833  const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2834  // Maximum line delta, thus ranging from -10..(255-10).
2835  const int MaxLineDelta = 255 + MinLineDelta;
2836
2837  // Start the dwarf line section.
2838  Asm->OutStreamer.SwitchSection(
2839                            Asm->getObjFileLowering().getDwarfLineSection());
2840
2841  // Construct the section header.
2842  Asm->OutStreamer.AddComment("Length of Source Line Info");
2843  Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2844                           Asm->GetTempSymbol("line_begin"), 4);
2845  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2846
2847  Asm->OutStreamer.AddComment("DWARF version number");
2848  Asm->EmitInt16(dwarf::DWARF_VERSION);
2849
2850  Asm->OutStreamer.AddComment("Prolog Length");
2851  Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2852                           Asm->GetTempSymbol("line_prolog_begin"), 4);
2853  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2854
2855  Asm->OutStreamer.AddComment("Minimum Instruction Length");
2856  Asm->EmitInt8(1);
2857  Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2858  Asm->EmitInt8(1);
2859  Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2860  Asm->EmitInt8(MinLineDelta);
2861  Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2862  Asm->EmitInt8(MaxLineDelta);
2863  Asm->OutStreamer.AddComment("Special Opcode Base");
2864  Asm->EmitInt8(-MinLineDelta);
2865
2866  // Line number standard opcode encodings argument count
2867  Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2868  Asm->EmitInt8(0);
2869  Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2870  Asm->EmitInt8(1);
2871  Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2872  Asm->EmitInt8(1);
2873  Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2874  Asm->EmitInt8(1);
2875  Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2876  Asm->EmitInt8(1);
2877  Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2878  Asm->EmitInt8(0);
2879  Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2880  Asm->EmitInt8(0);
2881  Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2882  Asm->EmitInt8(0);
2883  Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2884  Asm->EmitInt8(1);
2885
2886  // Emit directories.
2887  for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2888    const std::string &Dir = getSourceDirectoryName(DI);
2889    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
2890    Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2891  }
2892
2893  Asm->OutStreamer.AddComment("End of directories");
2894  Asm->EmitInt8(0);
2895
2896  // Emit files.
2897  for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2898    // Remember source id starts at 1.
2899    std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2900    const std::string &FN = getSourceFileName(Id.second);
2901    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
2902    Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2903
2904    Asm->EmitULEB128(Id.first, "Directory #");
2905    Asm->EmitULEB128(0, "Mod date");
2906    Asm->EmitULEB128(0, "File size");
2907  }
2908
2909  Asm->OutStreamer.AddComment("End of files");
2910  Asm->EmitInt8(0);
2911
2912  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
2913
2914  // A sequence for each text section.
2915  unsigned SecSrcLinesSize = SectionSourceLines.size();
2916
2917  for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2918    // Isolate current sections line info.
2919    const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2920
2921    // Dwarf assumes we start with first line of first source file.
2922    unsigned Source = 1;
2923    unsigned Line = 1;
2924
2925    // Construct rows of the address, source, line, column matrix.
2926    for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2927      const SrcLineInfo &LineInfo = LineInfos[i];
2928      MCSymbol *Label = LineInfo.getLabel();
2929      if (!Label->isDefined()) continue; // Not emitted, in dead code.
2930
2931      if (LineInfo.getLine() == 0) continue;
2932
2933      if (Asm->isVerbose()) {
2934        std::pair<unsigned, unsigned> SrcID =
2935          getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2936        Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
2937                                    "/" +
2938                                    Twine(getSourceFileName(SrcID.second)) +
2939                                    ":" + Twine(LineInfo.getLine()));
2940      }
2941
2942      // Define the line address.
2943      Asm->OutStreamer.AddComment("Extended Op");
2944      Asm->EmitInt8(0);
2945      Asm->OutStreamer.AddComment("Op size");
2946      Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2947
2948      Asm->OutStreamer.AddComment("DW_LNE_set_address");
2949      Asm->EmitInt8(dwarf::DW_LNE_set_address);
2950
2951      Asm->OutStreamer.AddComment("Location label");
2952      Asm->OutStreamer.EmitSymbolValue(Label,
2953                                       Asm->getTargetData().getPointerSize(),
2954                                       0/*AddrSpace*/);
2955
2956      // If change of source, then switch to the new source.
2957      if (Source != LineInfo.getSourceID()) {
2958        Source = LineInfo.getSourceID();
2959        Asm->OutStreamer.AddComment("DW_LNS_set_file");
2960        Asm->EmitInt8(dwarf::DW_LNS_set_file);
2961        Asm->EmitULEB128(Source, "New Source");
2962      }
2963
2964      // If change of line.
2965      if (Line != LineInfo.getLine()) {
2966        // Determine offset.
2967        int Offset = LineInfo.getLine() - Line;
2968        int Delta = Offset - MinLineDelta;
2969
2970        // Update line.
2971        Line = LineInfo.getLine();
2972
2973        // If delta is small enough and in range...
2974        if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2975          // ... then use fast opcode.
2976          Asm->OutStreamer.AddComment("Line Delta");
2977          Asm->EmitInt8(Delta - MinLineDelta);
2978        } else {
2979          // ... otherwise use long hand.
2980          Asm->OutStreamer.AddComment("DW_LNS_advance_line");
2981          Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2982          Asm->EmitSLEB128(Offset, "Line Offset");
2983          Asm->OutStreamer.AddComment("DW_LNS_copy");
2984          Asm->EmitInt8(dwarf::DW_LNS_copy);
2985        }
2986      } else {
2987        // Copy the previous row (different address or source)
2988        Asm->OutStreamer.AddComment("DW_LNS_copy");
2989        Asm->EmitInt8(dwarf::DW_LNS_copy);
2990      }
2991    }
2992
2993    emitEndOfLineMatrix(j + 1);
2994  }
2995
2996  if (SecSrcLinesSize == 0)
2997    // Because we're emitting a debug_line section, we still need a line
2998    // table. The linker and friends expect it to exist. If there's nothing to
2999    // put into it, emit an empty table.
3000    emitEndOfLineMatrix(1);
3001
3002  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3003}
3004
3005/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3006///
3007void DwarfDebug::emitCommonDebugFrame() {
3008  if (!Asm->MAI->doesDwarfRequireFrameSection())
3009    return;
3010
3011  int stackGrowth = Asm->getTargetData().getPointerSize();
3012  if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3013      TargetFrameInfo::StackGrowsDown)
3014    stackGrowth *= -1;
3015
3016  // Start the dwarf frame section.
3017  Asm->OutStreamer.SwitchSection(
3018                              Asm->getObjFileLowering().getDwarfFrameSection());
3019
3020  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3021  Asm->OutStreamer.AddComment("Length of Common Information Entry");
3022  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3023                           Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3024
3025  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3026  Asm->OutStreamer.AddComment("CIE Identifier Tag");
3027  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3028  Asm->OutStreamer.AddComment("CIE Version");
3029  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3030  Asm->OutStreamer.AddComment("CIE Augmentation");
3031  Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3032  Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3033  Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3034  Asm->OutStreamer.AddComment("CIE RA Column");
3035  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3036  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3037
3038  std::vector<MachineMove> Moves;
3039  RI->getInitialFrameState(Moves);
3040
3041  Asm->EmitFrameMoves(Moves, 0, false);
3042
3043  Asm->EmitAlignment(2, 0, 0, false);
3044  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3045}
3046
3047/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3048/// section.
3049void DwarfDebug::
3050emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3051  if (!Asm->MAI->doesDwarfRequireFrameSection())
3052    return;
3053
3054  // Start the dwarf frame section.
3055  Asm->OutStreamer.SwitchSection(
3056                              Asm->getObjFileLowering().getDwarfFrameSection());
3057
3058  Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3059  MCSymbol *DebugFrameBegin =
3060    Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3061  MCSymbol *DebugFrameEnd =
3062    Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3063  Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3064
3065  Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3066
3067  Asm->OutStreamer.AddComment("FDE CIE offset");
3068  Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3069                         DwarfFrameSectionSym);
3070
3071  Asm->OutStreamer.AddComment("FDE initial location");
3072  MCSymbol *FuncBeginSym =
3073    Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3074  Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3075                                   Asm->getTargetData().getPointerSize(),
3076                                   0/*AddrSpace*/);
3077
3078
3079  Asm->OutStreamer.AddComment("FDE address range");
3080  Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3081                           FuncBeginSym, Asm->getTargetData().getPointerSize());
3082
3083  Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3084
3085  Asm->EmitAlignment(2, 0, 0, false);
3086  Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3087}
3088
3089/// emitDebugPubNames - Emit visible names into a debug pubnames section.
3090///
3091void DwarfDebug::emitDebugPubNames() {
3092  // Start the dwarf pubnames section.
3093  Asm->OutStreamer.SwitchSection(
3094                          Asm->getObjFileLowering().getDwarfPubNamesSection());
3095
3096  Asm->OutStreamer.AddComment("Length of Public Names Info");
3097  Asm->EmitLabelDifference(
3098                 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()),
3099                 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4);
3100
3101  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3102                                                ModuleCU->getID()));
3103
3104  Asm->OutStreamer.AddComment("DWARF Version");
3105  Asm->EmitInt16(dwarf::DWARF_VERSION);
3106
3107  Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3108  Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3109                         DwarfInfoSectionSym);
3110
3111  Asm->OutStreamer.AddComment("Compilation Unit Length");
3112  Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3113                           Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3114                           4);
3115
3116  const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
3117  for (StringMap<DIE*>::const_iterator
3118         GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3119    const char *Name = GI->getKeyData();
3120    DIE *Entity = GI->second;
3121
3122    Asm->OutStreamer.AddComment("DIE offset");
3123    Asm->EmitInt32(Entity->getOffset());
3124
3125    if (Asm->isVerbose())
3126      Asm->OutStreamer.AddComment("External Name");
3127    Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3128  }
3129
3130  Asm->OutStreamer.AddComment("End Mark");
3131  Asm->EmitInt32(0);
3132  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3133                                                ModuleCU->getID()));
3134}
3135
3136void DwarfDebug::emitDebugPubTypes() {
3137  // Start the dwarf pubnames section.
3138  Asm->OutStreamer.SwitchSection(
3139                          Asm->getObjFileLowering().getDwarfPubTypesSection());
3140  Asm->OutStreamer.AddComment("Length of Public Types Info");
3141  Asm->EmitLabelDifference(
3142                    Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()),
3143                    Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4);
3144
3145  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3146                                                ModuleCU->getID()));
3147
3148  if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3149  Asm->EmitInt16(dwarf::DWARF_VERSION);
3150
3151  Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
3152  Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3153                         DwarfInfoSectionSym);
3154
3155  Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
3156  Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3157                           Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3158                           4);
3159
3160  const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
3161  for (StringMap<DIE*>::const_iterator
3162         GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3163    const char *Name = GI->getKeyData();
3164    DIE * Entity = GI->second;
3165
3166    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3167    Asm->EmitInt32(Entity->getOffset());
3168
3169    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3170    Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3171  }
3172
3173  Asm->OutStreamer.AddComment("End Mark");
3174  Asm->EmitInt32(0);
3175  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3176                                                ModuleCU->getID()));
3177}
3178
3179/// emitDebugStr - Emit visible names into a debug str section.
3180///
3181void DwarfDebug::emitDebugStr() {
3182  // Check to see if it is worth the effort.
3183  if (StringPool.empty()) return;
3184
3185  // Start the dwarf str section.
3186  Asm->OutStreamer.SwitchSection(
3187                                Asm->getObjFileLowering().getDwarfStrSection());
3188
3189  // Get all of the string pool entries and put them in an array by their ID so
3190  // we can sort them.
3191  SmallVector<std::pair<unsigned,
3192      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3193
3194  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3195       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3196    Entries.push_back(std::make_pair(I->second.second, &*I));
3197
3198  array_pod_sort(Entries.begin(), Entries.end());
3199
3200  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3201    // Emit a label for reference from debug information entries.
3202    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3203
3204    // Emit the string itself.
3205    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3206  }
3207}
3208
3209/// emitDebugLoc - Emit visible names into a debug loc section.
3210///
3211void DwarfDebug::emitDebugLoc() {
3212  // Start the dwarf loc section.
3213  Asm->OutStreamer.SwitchSection(
3214                              Asm->getObjFileLowering().getDwarfLocSection());
3215}
3216
3217/// EmitDebugARanges - Emit visible names into a debug aranges section.
3218///
3219void DwarfDebug::EmitDebugARanges() {
3220  // Start the dwarf aranges section.
3221  Asm->OutStreamer.SwitchSection(
3222                          Asm->getObjFileLowering().getDwarfARangesSection());
3223}
3224
3225/// emitDebugRanges - Emit visible names into a debug ranges section.
3226///
3227void DwarfDebug::emitDebugRanges() {
3228  // Start the dwarf ranges section.
3229  Asm->OutStreamer.SwitchSection(
3230    Asm->getObjFileLowering().getDwarfRangesSection());
3231  for (SmallVector<const MCSymbol *, 8>::const_iterator I = DebugRangeSymbols.begin(),
3232         E = DebugRangeSymbols.end(); I != E; ++I) {
3233    if (*I)
3234      Asm->EmitLabelDifference(*I, TextSectionSym,
3235                               Asm->getTargetData().getPointerSize());
3236    else
3237      Asm->OutStreamer.EmitIntValue(0, Asm->getTargetData().getPointerSize(),
3238                                    /*addrspace*/0);
3239  }
3240}
3241
3242/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3243///
3244void DwarfDebug::emitDebugMacInfo() {
3245  if (const MCSection *LineInfo =
3246      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3247    // Start the dwarf macinfo section.
3248    Asm->OutStreamer.SwitchSection(LineInfo);
3249  }
3250}
3251
3252/// emitDebugInlineInfo - Emit inline info using following format.
3253/// Section Header:
3254/// 1. length of section
3255/// 2. Dwarf version number
3256/// 3. address size.
3257///
3258/// Entries (one "entry" for each function that was inlined):
3259///
3260/// 1. offset into __debug_str section for MIPS linkage name, if exists;
3261///   otherwise offset into __debug_str for regular function name.
3262/// 2. offset into __debug_str section for regular function name.
3263/// 3. an unsigned LEB128 number indicating the number of distinct inlining
3264/// instances for the function.
3265///
3266/// The rest of the entry consists of a {die_offset, low_pc} pair for each
3267/// inlined instance; the die_offset points to the inlined_subroutine die in the
3268/// __debug_info section, and the low_pc is the starting address for the
3269/// inlining instance.
3270void DwarfDebug::emitDebugInlineInfo() {
3271  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3272    return;
3273
3274  if (!ModuleCU)
3275    return;
3276
3277  Asm->OutStreamer.SwitchSection(
3278                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
3279
3280  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3281  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3282                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3283
3284  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3285
3286  Asm->OutStreamer.AddComment("Dwarf Version");
3287  Asm->EmitInt16(dwarf::DWARF_VERSION);
3288  Asm->OutStreamer.AddComment("Address Size (in bytes)");
3289  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3290
3291  for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3292         E = InlinedSPNodes.end(); I != E; ++I) {
3293
3294    MDNode *Node = *I;
3295    DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3296      = InlineInfo.find(Node);
3297    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3298    DISubprogram SP(Node);
3299    StringRef LName = SP.getLinkageName();
3300    StringRef Name = SP.getName();
3301
3302    Asm->OutStreamer.AddComment("MIPS linkage name");
3303    if (LName.empty()) {
3304      Asm->OutStreamer.EmitBytes(Name, 0);
3305      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3306    } else
3307      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3308                             DwarfStrSectionSym);
3309
3310    Asm->OutStreamer.AddComment("Function name");
3311    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3312    Asm->EmitULEB128(Labels.size(), "Inline count");
3313
3314    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3315           LE = Labels.end(); LI != LE; ++LI) {
3316      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3317      Asm->EmitInt32(LI->second->getOffset());
3318
3319      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3320      Asm->OutStreamer.EmitSymbolValue(LI->first,
3321                                       Asm->getTargetData().getPointerSize(),0);
3322    }
3323  }
3324
3325  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
3326}
3327