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