DwarfDebug.cpp revision 3cf763dc7a9741c14432710943ab66b439562881
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        DISubprogram SP(Element);
1074        ElemDie = createSubprogramDIE(DISubprogram(Element));
1075        if (SP.isProtected())
1076          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1077                  dwarf::DW_ACCESS_protected);
1078        else if (SP.isPrivate())
1079          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1080                  dwarf::DW_ACCESS_private);
1081        else
1082          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1083            dwarf::DW_ACCESS_public);
1084      }
1085      else if (Element.isVariable()) {
1086        DIVariable DV(Element);
1087        ElemDie = new DIE(dwarf::DW_TAG_variable);
1088        addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1089                  DV.getName());
1090        addType(ElemDie, DV.getType());
1091        addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1092        addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1093        addSourceLine(ElemDie, DV);
1094      } else if (Element.isDerivedType())
1095        ElemDie = createMemberDIE(DIDerivedType(Element));
1096      else
1097        continue;
1098      Buffer.addChild(ElemDie);
1099    }
1100
1101    if (CTy.isAppleBlockExtension())
1102      addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1103
1104    unsigned RLang = CTy.getRunTimeLang();
1105    if (RLang)
1106      addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1107              dwarf::DW_FORM_data1, RLang);
1108
1109    DICompositeType ContainingType = CTy.getContainingType();
1110    if (DIDescriptor(ContainingType).isCompositeType())
1111      addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1112                  getOrCreateTypeDIE(DIType(ContainingType)));
1113    else {
1114      DIDescriptor Context = CTy.getContext();
1115      addToContextOwner(&Buffer, Context);
1116    }
1117    break;
1118  }
1119  default:
1120    break;
1121  }
1122
1123  // Add name if not anonymous or intermediate type.
1124  if (!Name.empty())
1125    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1126
1127  if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
1128      || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1129    {
1130    // Add size if non-zero (derived types might be zero-sized.)
1131    if (Size)
1132      addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1133    else {
1134      // Add zero size if it is not a forward declaration.
1135      if (CTy.isForwardDecl())
1136        addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1137      else
1138        addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1139    }
1140
1141    // Add source line info if available.
1142    if (!CTy.isForwardDecl())
1143      addSourceLine(&Buffer, CTy);
1144  }
1145}
1146
1147/// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1148void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1149  int64_t L = SR.getLo();
1150  int64_t H = SR.getHi();
1151  DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1152
1153  addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1154  if (L)
1155    addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1156  addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1157
1158  Buffer.addChild(DW_Subrange);
1159}
1160
1161/// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1162void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1163                                       DICompositeType *CTy) {
1164  Buffer.setTag(dwarf::DW_TAG_array_type);
1165  if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1166    addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1167
1168  // Emit derived type.
1169  addType(&Buffer, CTy->getTypeDerivedFrom());
1170  DIArray Elements = CTy->getTypeArray();
1171
1172  // Get an anonymous type for index type.
1173  CompileUnit *TheCU = getCompileUnit(*CTy);
1174  DIE *IdxTy = TheCU->getIndexTyDie();
1175  if (!IdxTy) {
1176    // Construct an anonymous type for index type.
1177    IdxTy = new DIE(dwarf::DW_TAG_base_type);
1178    addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1179    addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1180            dwarf::DW_ATE_signed);
1181    TheCU->addDie(IdxTy);
1182    TheCU->setIndexTyDie(IdxTy);
1183  }
1184
1185  // Add subranges to array type.
1186  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1187    DIDescriptor Element = Elements.getElement(i);
1188    if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1189      constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1190  }
1191}
1192
1193/// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1194DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1195  DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1196  StringRef Name = ETy.getName();
1197  addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1198  int64_t Value = ETy.getEnumValue();
1199  addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1200  return Enumerator;
1201}
1202
1203/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1204/// printer to not emit usual symbol prefix before the symbol name is used then
1205/// return linkage name after skipping this special LLVM prefix.
1206static StringRef getRealLinkageName(StringRef LinkageName) {
1207  char One = '\1';
1208  if (LinkageName.startswith(StringRef(&One, 1)))
1209    return LinkageName.substr(1);
1210  return LinkageName;
1211}
1212
1213/// createMemberDIE - Create new member DIE.
1214DIE *DwarfDebug::createMemberDIE(DIDerivedType DT) {
1215  DIE *MemberDie = new DIE(DT.getTag());
1216  StringRef Name = DT.getName();
1217  if (!Name.empty())
1218    addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1219
1220  addType(MemberDie, DT.getTypeDerivedFrom());
1221
1222  addSourceLine(MemberDie, DT);
1223
1224  DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1225  addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1226
1227  uint64_t Size = DT.getSizeInBits();
1228  uint64_t FieldSize = DT.getOriginalTypeSize();
1229
1230  if (Size != FieldSize) {
1231    // Handle bitfield.
1232    addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1233    addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1234
1235    uint64_t Offset = DT.getOffsetInBits();
1236    uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1237    uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1238    uint64_t FieldOffset = (HiMark - FieldSize);
1239    Offset -= FieldOffset;
1240
1241    // Maybe we need to work from the other end.
1242    if (Asm->getTargetData().isLittleEndian())
1243      Offset = FieldSize - (Offset + Size);
1244    addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1245
1246    // Here WD_AT_data_member_location points to the anonymous
1247    // field that includes this bit field.
1248    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1249
1250  } else
1251    // This is not a bitfield.
1252    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1253
1254  if (DT.getTag() == dwarf::DW_TAG_inheritance
1255      && DT.isVirtual()) {
1256
1257    // For C++, virtual base classes are not at fixed offset. Use following
1258    // expression to extract appropriate offset from vtable.
1259    // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1260
1261    DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1262    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1263    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1264    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1265    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1266    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1267    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1268    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1269
1270    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1271             VBaseLocationDie);
1272  } else
1273    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1274
1275  if (DT.isProtected())
1276    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1277            dwarf::DW_ACCESS_protected);
1278  else if (DT.isPrivate())
1279    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1280            dwarf::DW_ACCESS_private);
1281  // Otherwise C++ member and base classes are considered public.
1282  else if (DT.getCompileUnit().getLanguage() == dwarf::DW_LANG_C_plus_plus)
1283    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1284            dwarf::DW_ACCESS_public);
1285  if (DT.isVirtual())
1286    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1287            dwarf::DW_VIRTUALITY_virtual);
1288  return MemberDie;
1289}
1290
1291/// createSubprogramDIE - Create new DIE using SP.
1292DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
1293  CompileUnit *SPCU = getCompileUnit(SP);
1294  DIE *SPDie = SPCU->getDIE(SP);
1295  if (SPDie)
1296    return SPDie;
1297
1298  SPDie = new DIE(dwarf::DW_TAG_subprogram);
1299  // Constructors and operators for anonymous aggregates do not have names.
1300  if (!SP.getName().empty())
1301    addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1302
1303  StringRef LinkageName = SP.getLinkageName();
1304  if (!LinkageName.empty())
1305    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1306              getRealLinkageName(LinkageName));
1307
1308  addSourceLine(SPDie, SP);
1309
1310  // Add prototyped tag, if C or ObjC.
1311  unsigned Lang = SP.getCompileUnit().getLanguage();
1312  if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1313      Lang == dwarf::DW_LANG_ObjC)
1314    addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1315
1316  // Add Return Type.
1317  DICompositeType SPTy = SP.getType();
1318  DIArray Args = SPTy.getTypeArray();
1319  unsigned SPTag = SPTy.getTag();
1320
1321  if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1322    addType(SPDie, SPTy);
1323  else
1324    addType(SPDie, DIType(Args.getElement(0)));
1325
1326  unsigned VK = SP.getVirtuality();
1327  if (VK) {
1328    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1329    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1330    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1331    addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1332    addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1333    ContainingTypeMap.insert(std::make_pair(SPDie,
1334                                            SP.getContainingType()));
1335  }
1336
1337  if (!SP.isDefinition()) {
1338    addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1339
1340    // Add arguments. Do not add arguments for subprogram definition. They will
1341    // be handled while processing variables.
1342    DICompositeType SPTy = SP.getType();
1343    DIArray Args = SPTy.getTypeArray();
1344    unsigned SPTag = SPTy.getTag();
1345
1346    if (SPTag == dwarf::DW_TAG_subroutine_type)
1347      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1348        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1349        DIType ATy = DIType(DIType(Args.getElement(i)));
1350        addType(Arg, ATy);
1351        if (ATy.isArtificial())
1352          addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1353        SPDie->addChild(Arg);
1354      }
1355  }
1356
1357  if (SP.isArtificial())
1358    addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1359
1360  if (!SP.isLocalToUnit())
1361    addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1362
1363  if (SP.isOptimized())
1364    addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1365
1366  if (unsigned isa = Asm->getISAEncoding()) {
1367    addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1368  }
1369
1370  // DW_TAG_inlined_subroutine may refer to this DIE.
1371  SPCU->insertDIE(SP, SPDie);
1372
1373  // Add to context owner.
1374  addToContextOwner(SPDie, SP.getContext());
1375
1376  return SPDie;
1377}
1378
1379DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1380  assert(N && "Invalid Scope encoding!");
1381
1382  DbgScope *AScope = AbstractScopes.lookup(N);
1383  if (AScope)
1384    return AScope;
1385
1386  DbgScope *Parent = NULL;
1387
1388  DIDescriptor Scope(N);
1389  if (Scope.isLexicalBlock()) {
1390    DILexicalBlock DB(N);
1391    DIDescriptor ParentDesc = DB.getContext();
1392    Parent = getOrCreateAbstractScope(ParentDesc);
1393  }
1394
1395  AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1396
1397  if (Parent)
1398    Parent->addScope(AScope);
1399  AScope->setAbstractScope();
1400  AbstractScopes[N] = AScope;
1401  if (DIDescriptor(N).isSubprogram())
1402    AbstractScopesList.push_back(AScope);
1403  return AScope;
1404}
1405
1406/// isSubprogramContext - Return true if Context is either a subprogram
1407/// or another context nested inside a subprogram.
1408static bool isSubprogramContext(const MDNode *Context) {
1409  if (!Context)
1410    return false;
1411  DIDescriptor D(Context);
1412  if (D.isSubprogram())
1413    return true;
1414  if (D.isType())
1415    return isSubprogramContext(DIType(Context).getContext());
1416  return false;
1417}
1418
1419/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1420/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1421/// If there are global variables in this scope then create and insert
1422/// DIEs for these variables.
1423DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1424  CompileUnit *SPCU = getCompileUnit(SPNode);
1425  DIE *SPDie = SPCU->getDIE(SPNode);
1426
1427  assert(SPDie && "Unable to find subprogram DIE!");
1428  DISubprogram SP(SPNode);
1429
1430  // There is not any need to generate specification DIE for a function
1431  // defined at compile unit level. If a function is defined inside another
1432  // function then gdb prefers the definition at top level and but does not
1433  // expect specification DIE in parent function. So avoid creating
1434  // specification DIE for a function defined inside a function.
1435  if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1436      !SP.getContext().isFile() &&
1437      !isSubprogramContext(SP.getContext())) {
1438    addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1439
1440    // Add arguments.
1441    DICompositeType SPTy = SP.getType();
1442    DIArray Args = SPTy.getTypeArray();
1443    unsigned SPTag = SPTy.getTag();
1444    if (SPTag == dwarf::DW_TAG_subroutine_type)
1445      for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1446        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1447        DIType ATy = DIType(DIType(Args.getElement(i)));
1448        addType(Arg, ATy);
1449        if (ATy.isArtificial())
1450          addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1451        SPDie->addChild(Arg);
1452      }
1453    DIE *SPDeclDie = SPDie;
1454    SPDie = new DIE(dwarf::DW_TAG_subprogram);
1455    addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1456                SPDeclDie);
1457    SPCU->addDie(SPDie);
1458  }
1459
1460  // Pick up abstract subprogram DIE.
1461  if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
1462    SPDie = new DIE(dwarf::DW_TAG_subprogram);
1463    addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
1464                dwarf::DW_FORM_ref4, AbsSPDIE);
1465    SPCU->addDie(SPDie);
1466  }
1467
1468  addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1469           Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1470  addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1471           Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1472  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1473  MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1474  addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1475
1476  return SPDie;
1477}
1478
1479/// constructLexicalScope - Construct new DW_TAG_lexical_block
1480/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1481DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1482
1483  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1484  if (Scope->isAbstractScope())
1485    return ScopeDIE;
1486
1487  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1488  if (Ranges.empty())
1489    return 0;
1490
1491  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1492  if (Ranges.size() > 1) {
1493    // .debug_range section has not been laid out yet. Emit offset in
1494    // .debug_range as a uint, size 4, for now. emitDIE will handle
1495    // DW_AT_ranges appropriately.
1496    addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1497            DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1498    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1499         RE = Ranges.end(); RI != RE; ++RI) {
1500      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
1501      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
1502    }
1503    DebugRangeSymbols.push_back(NULL);
1504    DebugRangeSymbols.push_back(NULL);
1505    return ScopeDIE;
1506  }
1507
1508  const MCSymbol *Start = getLabelBeforeInsn(RI->first);
1509  const MCSymbol *End = getLabelAfterInsn(RI->second);
1510
1511  if (End == 0) return 0;
1512
1513  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1514  assert(End->isDefined() && "Invalid end label for an inlined scope!");
1515
1516  addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1517  addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1518
1519  return ScopeDIE;
1520}
1521
1522/// constructInlinedScopeDIE - This scope represents inlined body of
1523/// a function. Construct DIE to represent this concrete inlined copy
1524/// of the function.
1525DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1526
1527  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1528  assert (Ranges.empty() == false
1529          && "DbgScope does not have instruction markers!");
1530
1531  // FIXME : .debug_inlined section specification does not clearly state how
1532  // to emit inlined scope that is split into multiple instruction ranges.
1533  // For now, use first instruction range and emit low_pc/high_pc pair and
1534  // corresponding .debug_inlined section entry for this pair.
1535  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1536  const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
1537  const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
1538
1539  if (StartLabel == 0 || EndLabel == 0) {
1540    assert (0 && "Unexpected Start and End  labels for a inlined scope!");
1541    return 0;
1542  }
1543  assert(StartLabel->isDefined() &&
1544         "Invalid starting label for an inlined scope!");
1545  assert(EndLabel->isDefined() &&
1546         "Invalid end label for an inlined scope!");
1547
1548  if (!Scope->getScopeNode())
1549    return NULL;
1550  DIScope DS(Scope->getScopeNode());
1551  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1552
1553  DISubprogram InlinedSP = getDISubprogram(DS);
1554  CompileUnit *TheCU = getCompileUnit(InlinedSP);
1555  DIE *OriginDIE = TheCU->getDIE(InlinedSP);
1556  assert(OriginDIE && "Unable to find Origin DIE!");
1557  addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1558              dwarf::DW_FORM_ref4, OriginDIE);
1559
1560  addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1561  addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1562
1563  InlinedSubprogramDIEs.insert(OriginDIE);
1564
1565  // Track the start label for this inlined function.
1566  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1567    I = InlineInfo.find(InlinedSP);
1568
1569  if (I == InlineInfo.end()) {
1570    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1571                                                             ScopeDIE));
1572    InlinedSPNodes.push_back(InlinedSP);
1573  } else
1574    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1575
1576  DILocation DL(Scope->getInlinedAt());
1577  addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
1578  addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1579
1580  return ScopeDIE;
1581}
1582
1583
1584/// constructVariableDIE - Construct a DIE for the given DbgVariable.
1585DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1586  StringRef Name = DV->getName();
1587  if (Name.empty())
1588    return NULL;
1589
1590  // Translate tag to proper Dwarf tag.  The result variable is dropped for
1591  // now.
1592  unsigned Tag;
1593  switch (DV->getTag()) {
1594  case dwarf::DW_TAG_return_variable:
1595    return NULL;
1596  case dwarf::DW_TAG_arg_variable:
1597    Tag = dwarf::DW_TAG_formal_parameter;
1598    break;
1599  case dwarf::DW_TAG_auto_variable:    // fall thru
1600  default:
1601    Tag = dwarf::DW_TAG_variable;
1602    break;
1603  }
1604
1605  // Define variable debug information entry.
1606  DIE *VariableDie = new DIE(Tag);
1607
1608  DIE *AbsDIE = NULL;
1609  DenseMap<const DbgVariable *, const DbgVariable *>::iterator
1610    V2AVI = VarToAbstractVarMap.find(DV);
1611  if (V2AVI != VarToAbstractVarMap.end())
1612    AbsDIE = V2AVI->second->getDIE();
1613
1614  if (AbsDIE)
1615    addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1616                dwarf::DW_FORM_ref4, AbsDIE);
1617  else {
1618    addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1619    addSourceLine(VariableDie, DV->getVariable());
1620
1621    // Add variable type.
1622    addType(VariableDie, DV->getType());
1623  }
1624
1625  if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
1626    addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1627  else if (DIVariable(DV->getVariable()).isArtificial())
1628    addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1629
1630  if (Scope->isAbstractScope()) {
1631    DV->setDIE(VariableDie);
1632    return VariableDie;
1633  }
1634
1635  // Add variable address.
1636
1637  unsigned Offset = DV->getDotDebugLocOffset();
1638  if (Offset != ~0U) {
1639    addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1640             Asm->GetTempSymbol("debug_loc", Offset));
1641    DV->setDIE(VariableDie);
1642    UseDotDebugLocEntry.insert(VariableDie);
1643    return VariableDie;
1644  }
1645
1646  // Check if variable is described by a  DBG_VALUE instruction.
1647  DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
1648    DbgVariableToDbgInstMap.find(DV);
1649  if (DVI != DbgVariableToDbgInstMap.end()) {
1650    const MachineInstr *DVInsn = DVI->second;
1651    const MCSymbol *DVLabel = findVariableLabel(DV);
1652    bool updated = false;
1653    // FIXME : Handle getNumOperands != 3
1654    if (DVInsn->getNumOperands() == 3) {
1655      if (DVInsn->getOperand(0).isReg()) {
1656        const MachineOperand RegOp = DVInsn->getOperand(0);
1657        const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1658        if (DVInsn->getOperand(1).isImm() &&
1659            TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1660          addVariableAddress(DV, VariableDie, DVInsn->getOperand(1).getImm());
1661          updated = true;
1662        } else
1663          updated = addRegisterAddress(VariableDie, DVLabel, RegOp);
1664      }
1665      else if (DVInsn->getOperand(0).isImm())
1666        updated = addConstantValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1667      else if (DVInsn->getOperand(0).isFPImm())
1668        updated =
1669          addConstantFPValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1670    } else {
1671      MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1672      if (Location.getReg()) {
1673        addAddress(VariableDie, dwarf::DW_AT_location, Location);
1674        if (DVLabel)
1675          addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1676                   DVLabel);
1677        updated = true;
1678      }
1679    }
1680    if (!updated) {
1681      // If variableDie is not updated then DBG_VALUE instruction does not
1682      // have valid variable info.
1683      delete VariableDie;
1684      return NULL;
1685    }
1686    DV->setDIE(VariableDie);
1687    return VariableDie;
1688  }
1689
1690  // .. else use frame index, if available.
1691  int FI = 0;
1692  if (findVariableFrameIndex(DV, &FI))
1693    addVariableAddress(DV, VariableDie, FI);
1694
1695  DV->setDIE(VariableDie);
1696  return VariableDie;
1697
1698}
1699
1700void DwarfDebug::addPubTypes(DISubprogram SP) {
1701  DICompositeType SPTy = SP.getType();
1702  unsigned SPTag = SPTy.getTag();
1703  if (SPTag != dwarf::DW_TAG_subroutine_type)
1704    return;
1705
1706  DIArray Args = SPTy.getTypeArray();
1707  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1708    DIType ATy(Args.getElement(i));
1709    if (!ATy.Verify())
1710      continue;
1711    DICompositeType CATy = getDICompositeType(ATy);
1712    if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1713        && !CATy.isForwardDecl()) {
1714      CompileUnit *TheCU = getCompileUnit(CATy);
1715      if (DIEEntry *Entry = TheCU->getDIEEntry(CATy))
1716        TheCU->addGlobalType(CATy.getName(), Entry->getEntry());
1717    }
1718  }
1719}
1720
1721/// constructScopeDIE - Construct a DIE for this scope.
1722DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1723  if (!Scope || !Scope->getScopeNode())
1724    return NULL;
1725
1726  DIScope DS(Scope->getScopeNode());
1727  DIE *ScopeDIE = NULL;
1728  if (Scope->getInlinedAt())
1729    ScopeDIE = constructInlinedScopeDIE(Scope);
1730  else if (DS.isSubprogram()) {
1731    ProcessedSPNodes.insert(DS);
1732    if (Scope->isAbstractScope()) {
1733      ScopeDIE = getCompileUnit(DS)->getDIE(DS);
1734      // Note down abstract DIE.
1735      if (ScopeDIE)
1736        AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
1737    }
1738    else
1739      ScopeDIE = updateSubprogramScopeDIE(DS);
1740  }
1741  else
1742    ScopeDIE = constructLexicalScopeDIE(Scope);
1743  if (!ScopeDIE) return NULL;
1744
1745  // Add variables to scope.
1746  const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1747  for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1748    DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1749    if (VariableDIE)
1750      ScopeDIE->addChild(VariableDIE);
1751  }
1752
1753  // Add nested scopes.
1754  const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1755  for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1756    // Define the Scope debug information entry.
1757    DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1758    if (NestedDIE)
1759      ScopeDIE->addChild(NestedDIE);
1760  }
1761
1762  if (DS.isSubprogram())
1763    addPubTypes(DISubprogram(DS));
1764
1765 return ScopeDIE;
1766}
1767
1768/// GetOrCreateSourceID - Look up the source id with the given directory and
1769/// source file names. If none currently exists, create a new id and insert it
1770/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1771/// maps as well.
1772unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1773  unsigned DId;
1774  assert (DirName.empty() == false && "Invalid directory name!");
1775
1776  // If FE did not provide a file name, then assume stdin.
1777  if (FileName.empty())
1778    return GetOrCreateSourceID(DirName, "<stdin>");
1779
1780  StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1781  if (DI != DirectoryIdMap.end()) {
1782    DId = DI->getValue();
1783  } else {
1784    DId = DirectoryNames.size() + 1;
1785    DirectoryIdMap[DirName] = DId;
1786    DirectoryNames.push_back(DirName);
1787  }
1788
1789  unsigned FId;
1790  StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1791  if (FI != SourceFileIdMap.end()) {
1792    FId = FI->getValue();
1793  } else {
1794    FId = SourceFileNames.size() + 1;
1795    SourceFileIdMap[FileName] = FId;
1796    SourceFileNames.push_back(FileName);
1797  }
1798
1799  DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1800    SourceIdMap.find(std::make_pair(DId, FId));
1801  if (SI != SourceIdMap.end())
1802    return SI->second;
1803
1804  unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
1805  SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1806  SourceIds.push_back(std::make_pair(DId, FId));
1807
1808  return SrcId;
1809}
1810
1811/// getOrCreateNameSpace - Create a DIE for DINameSpace.
1812DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1813  CompileUnit *TheCU = getCompileUnit(NS);
1814  DIE *NDie = TheCU->getDIE(NS);
1815  if (NDie)
1816    return NDie;
1817  NDie = new DIE(dwarf::DW_TAG_namespace);
1818  TheCU->insertDIE(NS, NDie);
1819  if (!NS.getName().empty())
1820    addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1821  addSourceLine(NDie, NS);
1822  addToContextOwner(NDie, NS.getContext());
1823  return NDie;
1824}
1825
1826/// constructCompileUnit - Create new CompileUnit for the given
1827/// metadata node with tag DW_TAG_compile_unit.
1828void DwarfDebug::constructCompileUnit(const MDNode *N) {
1829  DICompileUnit DIUnit(N);
1830  StringRef FN = DIUnit.getFilename();
1831  StringRef Dir = DIUnit.getDirectory();
1832  unsigned ID = GetOrCreateSourceID(Dir, FN);
1833
1834  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1835  addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1836            DIUnit.getProducer());
1837  addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1838          DIUnit.getLanguage());
1839  addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1840  // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1841  // simplifies debug range entries.
1842  addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
1843  // DW_AT_stmt_list is a offset of line number information for this
1844  // compile unit in debug_line section.
1845  if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
1846    addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
1847             Asm->GetTempSymbol("section_line"));
1848  else
1849    addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1850
1851  if (!Dir.empty())
1852    addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1853  if (DIUnit.isOptimized())
1854    addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1855
1856  StringRef Flags = DIUnit.getFlags();
1857  if (!Flags.empty())
1858    addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1859
1860  unsigned RVer = DIUnit.getRunTimeVersion();
1861  if (RVer)
1862    addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1863            dwarf::DW_FORM_data1, RVer);
1864
1865  CompileUnit *NewCU = new CompileUnit(ID, Die);
1866  if (!FirstCU)
1867    FirstCU = NewCU;
1868  CUMap.insert(std::make_pair(N, NewCU));
1869}
1870
1871/// getCompielUnit - Get CompileUnit DIE.
1872CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
1873  assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
1874  DIDescriptor D(N);
1875  const MDNode *CUNode = NULL;
1876  if (D.isCompileUnit())
1877    CUNode = N;
1878  else if (D.isSubprogram())
1879    CUNode = DISubprogram(N).getCompileUnit();
1880  else if (D.isType())
1881    CUNode = DIType(N).getCompileUnit();
1882  else if (D.isGlobalVariable())
1883    CUNode = DIGlobalVariable(N).getCompileUnit();
1884  else if (D.isVariable())
1885    CUNode = DIVariable(N).getCompileUnit();
1886  else if (D.isNameSpace())
1887    CUNode = DINameSpace(N).getCompileUnit();
1888  else if (D.isFile())
1889    CUNode = DIFile(N).getCompileUnit();
1890  else
1891    return FirstCU;
1892
1893  DenseMap<const MDNode *, CompileUnit *>::const_iterator I
1894    = CUMap.find(CUNode);
1895  if (I == CUMap.end())
1896    return FirstCU;
1897  return I->second;
1898}
1899
1900/// isUnsignedDIType - Return true if type encoding is unsigned.
1901static bool isUnsignedDIType(DIType Ty) {
1902  DIDerivedType DTy(Ty);
1903  if (DTy.Verify())
1904    return isUnsignedDIType(DTy.getTypeDerivedFrom());
1905
1906  DIBasicType BTy(Ty);
1907  if (BTy.Verify()) {
1908    unsigned Encoding = BTy.getEncoding();
1909    if (Encoding == dwarf::DW_ATE_unsigned ||
1910        Encoding == dwarf::DW_ATE_unsigned_char)
1911      return true;
1912  }
1913  return false;
1914}
1915
1916/// constructGlobalVariableDIE - Construct global variable DIE.
1917void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1918  DIGlobalVariable GV(N);
1919
1920  // If debug information is malformed then ignore it.
1921  if (GV.Verify() == false)
1922    return;
1923
1924  // Check for pre-existence.
1925  CompileUnit *TheCU = getCompileUnit(N);
1926  if (TheCU->getDIE(GV))
1927    return;
1928
1929  DIType GTy = GV.getType();
1930  DIE *VariableDIE = new DIE(GV.getTag());
1931
1932  bool isGlobalVariable = GV.getGlobal() != NULL;
1933
1934  // Add name.
1935  addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1936            GV.getDisplayName());
1937  StringRef LinkageName = GV.getLinkageName();
1938  if (!LinkageName.empty() && isGlobalVariable)
1939    addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1940              getRealLinkageName(LinkageName));
1941  // Add type.
1942  addType(VariableDIE, GTy);
1943  if (GTy.isCompositeType() && !GTy.getName().empty()
1944      && !GTy.isForwardDecl()) {
1945    DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1946    assert(Entry && "Missing global type!");
1947    TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1948  }
1949  // Add scoping info.
1950  if (!GV.isLocalToUnit()) {
1951    addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1952    // Expose as global.
1953    TheCU->addGlobal(GV.getName(), VariableDIE);
1954  }
1955  // Add line number info.
1956  addSourceLine(VariableDIE, GV);
1957  // Add to map.
1958  TheCU->insertDIE(N, VariableDIE);
1959  // Add to context owner.
1960  DIDescriptor GVContext = GV.getContext();
1961  addToContextOwner(VariableDIE, GVContext);
1962  // Add location.
1963  if (isGlobalVariable) {
1964    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1965    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1966    addLabel(Block, 0, dwarf::DW_FORM_udata,
1967             Asm->Mang->getSymbol(GV.getGlobal()));
1968    // Do not create specification DIE if context is either compile unit
1969    // or a subprogram.
1970    if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1971        !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1972      // Create specification DIE.
1973      DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1974      addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1975                  dwarf::DW_FORM_ref4, VariableDIE);
1976      addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1977      addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1978      TheCU->addDie(VariableSpecDIE);
1979    } else {
1980      addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1981    }
1982  } else if (Constant *C = GV.getConstant()) {
1983    if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1984      if (isUnsignedDIType(GTy))
1985          addUInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
1986                  CI->getZExtValue());
1987        else
1988          addSInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1989                 CI->getSExtValue());
1990    }
1991  }
1992  return;
1993}
1994
1995/// construct SubprogramDIE - Construct subprogram DIE.
1996void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1997  DISubprogram SP(N);
1998
1999  // Check for pre-existence.
2000  CompileUnit *TheCU = getCompileUnit(N);
2001  if (TheCU->getDIE(N))
2002    return;
2003
2004  if (!SP.isDefinition())
2005    // This is a method declaration which will be handled while constructing
2006    // class type.
2007    return;
2008
2009  DIE *SubprogramDie = createSubprogramDIE(SP);
2010
2011  // Add to map.
2012  TheCU->insertDIE(N, SubprogramDie);
2013
2014  // Add to context owner.
2015  addToContextOwner(SubprogramDie, SP.getContext());
2016
2017  // Expose as global.
2018  TheCU->addGlobal(SP.getName(), SubprogramDie);
2019
2020  return;
2021}
2022
2023/// beginModule - Emit all Dwarf sections that should come prior to the
2024/// content. Create global DIEs and emit initial debug info sections.
2025/// This is inovked by the target AsmPrinter.
2026void DwarfDebug::beginModule(Module *M) {
2027  if (DisableDebugInfoPrinting)
2028    return;
2029
2030  DebugInfoFinder DbgFinder;
2031  DbgFinder.processModule(*M);
2032
2033  bool HasDebugInfo = false;
2034
2035  // Scan all the compile-units to see if there are any marked as the main unit.
2036  // if not, we do not generate debug info.
2037  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2038       E = DbgFinder.compile_unit_end(); I != E; ++I) {
2039    if (DICompileUnit(*I).isMain()) {
2040      HasDebugInfo = true;
2041      break;
2042    }
2043  }
2044
2045  if (!HasDebugInfo) return;
2046
2047  // Tell MMI that we have debug info.
2048  MMI->setDebugInfoAvailability(true);
2049
2050  // Emit initial sections.
2051  EmitSectionLabels();
2052
2053  // Create all the compile unit DIEs.
2054  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2055         E = DbgFinder.compile_unit_end(); I != E; ++I)
2056    constructCompileUnit(*I);
2057
2058  // Create DIEs for each subprogram.
2059  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
2060         E = DbgFinder.subprogram_end(); I != E; ++I)
2061    constructSubprogramDIE(*I);
2062
2063  // Create DIEs for each global variable.
2064  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
2065         E = DbgFinder.global_variable_end(); I != E; ++I)
2066    constructGlobalVariableDIE(*I);
2067
2068  //getOrCreateTypeDIE
2069  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
2070    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2071      getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2072
2073  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
2074    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2075      getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2076
2077  // Prime section data.
2078  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
2079
2080  // Print out .file directives to specify files for .loc directives. These are
2081  // printed out early so that they precede any .loc directives.
2082  if (Asm->MAI->hasDotLocAndDotFile()) {
2083    for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2084      // Remember source id starts at 1.
2085      std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2086      // FIXME: don't use sys::path for this!  This should not depend on the
2087      // host.
2088      sys::Path FullPath(getSourceDirectoryName(Id.first));
2089      bool AppendOk =
2090        FullPath.appendComponent(getSourceFileName(Id.second));
2091      assert(AppendOk && "Could not append filename to directory!");
2092      AppendOk = false;
2093      Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
2094    }
2095  }
2096}
2097
2098/// endModule - Emit all Dwarf sections that should come after the content.
2099///
2100void DwarfDebug::endModule() {
2101  if (!FirstCU) return;
2102  const Module *M = MMI->getModule();
2103  DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
2104  if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
2105    for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
2106      if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
2107      DISubprogram SP(AllSPs->getOperand(SI));
2108      if (!SP.Verify()) continue;
2109
2110      // Collect info for variables that were optimized out.
2111      if (!SP.isDefinition()) continue;
2112      StringRef FName = SP.getLinkageName();
2113      if (FName.empty())
2114        FName = SP.getName();
2115      NamedMDNode *NMD =
2116        M->getNamedMetadata(Twine("llvm.dbg.lv.", getRealLinkageName(FName)));
2117      if (!NMD) continue;
2118      unsigned E = NMD->getNumOperands();
2119      if (!E) continue;
2120      DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
2121      DeadFnScopeMap[SP] = Scope;
2122      for (unsigned I = 0; I != E; ++I) {
2123        DIVariable DV(NMD->getOperand(I));
2124        if (!DV.Verify()) continue;
2125        Scope->addVariable(new DbgVariable(DV));
2126      }
2127
2128      // Construct subprogram DIE and add variables DIEs.
2129      constructSubprogramDIE(SP);
2130      DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
2131      const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
2132      for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2133        DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
2134        if (VariableDIE)
2135          ScopeDIE->addChild(VariableDIE);
2136      }
2137    }
2138  }
2139
2140  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
2141  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
2142         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
2143    DIE *ISP = *AI;
2144    addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
2145  }
2146
2147  for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
2148         CE = ContainingTypeMap.end(); CI != CE; ++CI) {
2149    DIE *SPDie = CI->first;
2150    const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
2151    if (!N) continue;
2152    DIE *NDie = getCompileUnit(N)->getDIE(N);
2153    if (!NDie) continue;
2154    addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
2155  }
2156
2157  // Standard sections final addresses.
2158  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
2159  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
2160  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
2161  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
2162
2163  // End text sections.
2164  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2165    Asm->OutStreamer.SwitchSection(SectionMap[i]);
2166    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
2167  }
2168
2169  // Emit common frame information.
2170  emitCommonDebugFrame();
2171
2172  // Emit function debug frame information
2173  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2174         E = DebugFrames.end(); I != E; ++I)
2175    emitFunctionDebugFrame(*I);
2176
2177  // Compute DIE offsets and sizes.
2178  computeSizeAndOffsets();
2179
2180  // Emit all the DIEs into a debug info section
2181  emitDebugInfo();
2182
2183  // Corresponding abbreviations into a abbrev section.
2184  emitAbbreviations();
2185
2186  // Emit source line correspondence into a debug line section.
2187  emitDebugLines();
2188
2189  // Emit info into a debug pubnames section.
2190  emitDebugPubNames();
2191
2192  // Emit info into a debug pubtypes section.
2193  emitDebugPubTypes();
2194
2195  // Emit info into a debug loc section.
2196  emitDebugLoc();
2197
2198  // Emit info into a debug aranges section.
2199  EmitDebugARanges();
2200
2201  // Emit info into a debug ranges section.
2202  emitDebugRanges();
2203
2204  // Emit info into a debug macinfo section.
2205  emitDebugMacInfo();
2206
2207  // Emit inline info.
2208  emitDebugInlineInfo();
2209
2210  // Emit info into a debug str section.
2211  emitDebugStr();
2212
2213  // clean up.
2214  DeleteContainerSeconds(DeadFnScopeMap);
2215  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2216         E = CUMap.end(); I != E; ++I)
2217    delete I->second;
2218  FirstCU = NULL;  // Reset for the next Module, if any.
2219}
2220
2221/// findAbstractVariable - Find abstract variable, if any, associated with Var.
2222DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2223                                              DebugLoc ScopeLoc) {
2224
2225  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2226  if (AbsDbgVariable)
2227    return AbsDbgVariable;
2228
2229  LLVMContext &Ctx = Var->getContext();
2230  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2231  if (!Scope)
2232    return NULL;
2233
2234  AbsDbgVariable = new DbgVariable(Var);
2235  Scope->addVariable(AbsDbgVariable);
2236  AbstractVariables[Var] = AbsDbgVariable;
2237  return AbsDbgVariable;
2238}
2239
2240/// collectVariableInfoFromMMITable - Collect variable information from
2241/// side table maintained by MMI.
2242void
2243DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
2244                                   SmallPtrSet<const MDNode *, 16> &Processed) {
2245  const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2246  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2247  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2248         VE = VMap.end(); VI != VE; ++VI) {
2249    const MDNode *Var = VI->first;
2250    if (!Var) continue;
2251    Processed.insert(Var);
2252    DIVariable DV(Var);
2253    const std::pair<unsigned, DebugLoc> &VP = VI->second;
2254
2255    DbgScope *Scope = 0;
2256    if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2257      Scope = ConcreteScopes.lookup(IA);
2258    if (Scope == 0)
2259      Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2260
2261    // If variable scope is not found then skip this variable.
2262    if (Scope == 0)
2263      continue;
2264
2265    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
2266    DbgVariable *RegVar = new DbgVariable(DV);
2267    recordVariableFrameIndex(RegVar, VP.first);
2268    Scope->addVariable(RegVar);
2269    if (AbsDbgVariable) {
2270      recordVariableFrameIndex(AbsDbgVariable, VP.first);
2271      VarToAbstractVarMap[RegVar] = AbsDbgVariable;
2272    }
2273  }
2274}
2275
2276/// isDbgValueInUndefinedReg - Return true if debug value, encoded by
2277/// DBG_VALUE instruction, is in undefined reg.
2278static bool isDbgValueInUndefinedReg(const MachineInstr *MI) {
2279  assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2280  if (MI->getOperand(0).isReg() && !MI->getOperand(0).getReg())
2281    return true;
2282  return false;
2283}
2284
2285/// isDbgValueInDefinedReg - Return true if debug value, encoded by
2286/// DBG_VALUE instruction, is in a defined reg.
2287static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
2288  assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2289  if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
2290    return true;
2291  return false;
2292}
2293
2294/// collectVariableInfo - Populate DbgScope entries with variables' info.
2295void
2296DwarfDebug::collectVariableInfo(const MachineFunction *MF,
2297                                SmallPtrSet<const MDNode *, 16> &Processed) {
2298
2299  /// collection info from MMI table.
2300  collectVariableInfoFromMMITable(MF, Processed);
2301
2302  SmallVector<const MachineInstr *, 8> DbgValues;
2303  // Collect variable information from DBG_VALUE machine instructions;
2304  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2305       I != E; ++I)
2306    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2307         II != IE; ++II) {
2308      const MachineInstr *MInsn = II;
2309      if (!MInsn->isDebugValue() || isDbgValueInUndefinedReg(MInsn))
2310        continue;
2311      DbgValues.push_back(MInsn);
2312    }
2313
2314  // This is a collection of DBV_VALUE instructions describing same variable.
2315  SmallVector<const MachineInstr *, 4> MultipleValues;
2316  for(SmallVector<const MachineInstr *, 8>::iterator I = DbgValues.begin(),
2317        E = DbgValues.end(); I != E; ++I) {
2318    const MachineInstr *MInsn = *I;
2319    MultipleValues.clear();
2320    if (isDbgValueInDefinedReg(MInsn))
2321      MultipleValues.push_back(MInsn);
2322    DIVariable DV(MInsn->getOperand(MInsn->getNumOperands() - 1).getMetadata());
2323    if (Processed.count(DV) != 0)
2324      continue;
2325
2326    const MachineInstr *PrevMI = MInsn;
2327    for (SmallVector<const MachineInstr *, 8>::iterator MI = I+1,
2328           ME = DbgValues.end(); MI != ME; ++MI) {
2329      const MDNode *Var =
2330        (*MI)->getOperand((*MI)->getNumOperands()-1).getMetadata();
2331      if (Var == DV && isDbgValueInDefinedReg(*MI) &&
2332          !PrevMI->isIdenticalTo(*MI))
2333        MultipleValues.push_back(*MI);
2334      PrevMI = *MI;
2335    }
2336
2337    DbgScope *Scope = findDbgScope(MInsn);
2338    bool CurFnArg = false;
2339    if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
2340        DISubprogram(DV.getContext()).describes(MF->getFunction()))
2341      CurFnArg = true;
2342    if (!Scope && CurFnArg)
2343      Scope = CurrentFnDbgScope;
2344    // If variable scope is not found then skip this variable.
2345    if (!Scope)
2346      continue;
2347
2348    Processed.insert(DV);
2349    DbgVariable *RegVar = new DbgVariable(DV);
2350    Scope->addVariable(RegVar);
2351    if (!CurFnArg)
2352      DbgVariableLabelsMap[RegVar] = getLabelBeforeInsn(MInsn);
2353    if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
2354      DbgVariableToDbgInstMap[AbsVar] = MInsn;
2355      VarToAbstractVarMap[RegVar] = AbsVar;
2356    }
2357    if (MultipleValues.size() <= 1) {
2358      DbgVariableToDbgInstMap[RegVar] = MInsn;
2359      continue;
2360    }
2361
2362    // handle multiple DBG_VALUE instructions describing one variable.
2363    if (DotDebugLocEntries.empty())
2364      RegVar->setDotDebugLocOffset(0);
2365    else
2366      RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
2367    const MachineInstr *Begin = NULL;
2368    const MachineInstr *End = NULL;
2369    for (SmallVector<const MachineInstr *, 4>::iterator
2370           MVI = MultipleValues.begin(), MVE = MultipleValues.end();
2371         MVI != MVE; ++MVI) {
2372      if (!Begin) {
2373        Begin = *MVI;
2374        continue;
2375      }
2376      End = *MVI;
2377      MachineLocation MLoc;
2378      if (Begin->getNumOperands() == 3) {
2379        if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2380          MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2381      } else
2382        MLoc = Asm->getDebugValueLocation(Begin);
2383
2384      const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
2385      const MCSymbol *SLabel = getLabelBeforeInsn(End);
2386      if (MLoc.getReg())
2387        DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
2388
2389      Begin = End;
2390      if (MVI + 1 == MVE) {
2391        // If End is the last instruction then its value is valid
2392        // until the end of the funtion.
2393        MachineLocation EMLoc;
2394        if (End->getNumOperands() == 3) {
2395          if (End->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2396          EMLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2397        } else
2398          EMLoc = Asm->getDebugValueLocation(End);
2399        if (EMLoc.getReg())
2400          DotDebugLocEntries.
2401            push_back(DotDebugLocEntry(SLabel, FunctionEndSym, EMLoc));
2402      }
2403    }
2404    DotDebugLocEntries.push_back(DotDebugLocEntry());
2405  }
2406
2407  // Collect info for variables that were optimized out.
2408  const Function *F = MF->getFunction();
2409  const Module *M = F->getParent();
2410  if (NamedMDNode *NMD =
2411      M->getNamedMetadata(Twine("llvm.dbg.lv.",
2412                                getRealLinkageName(F->getName())))) {
2413    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2414      DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2415      if (!DV || !Processed.insert(DV))
2416        continue;
2417      DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
2418      if (Scope)
2419        Scope->addVariable(new DbgVariable(DV));
2420    }
2421  }
2422}
2423
2424/// getLabelBeforeInsn - Return Label preceding the instruction.
2425const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
2426  DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2427    LabelsBeforeInsn.find(MI);
2428  if (I == LabelsBeforeInsn.end())
2429    // FunctionBeginSym always preceeds all the instruction in current function.
2430    return FunctionBeginSym;
2431  return I->second;
2432}
2433
2434/// getLabelAfterInsn - Return Label immediately following the instruction.
2435const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
2436  DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2437    LabelsAfterInsn.find(MI);
2438  if (I == LabelsAfterInsn.end())
2439    return NULL;
2440  return I->second;
2441}
2442
2443/// beginScope - Process beginning of a scope.
2444void DwarfDebug::beginScope(const MachineInstr *MI) {
2445  if (InsnNeedsLabel.count(MI) == 0) {
2446    LabelsBeforeInsn[MI] = PrevLabel;
2447    return;
2448  }
2449
2450  // Check location.
2451  DebugLoc DL = MI->getDebugLoc();
2452  if (!DL.isUnknown()) {
2453    const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2454    PrevLabel = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2455    PrevInstLoc = DL;
2456    LabelsBeforeInsn[MI] = PrevLabel;
2457    return;
2458  }
2459
2460  // If location is unknown then use temp label for this DBG_VALUE
2461  // instruction.
2462  if (MI->isDebugValue()) {
2463    PrevLabel = MMI->getContext().CreateTempSymbol();
2464    Asm->OutStreamer.EmitLabel(PrevLabel);
2465    LabelsBeforeInsn[MI] = PrevLabel;
2466    return;
2467  }
2468
2469  if (UnknownLocations) {
2470    PrevLabel = recordSourceLine(0, 0, 0);
2471    LabelsBeforeInsn[MI] = PrevLabel;
2472    return;
2473  }
2474
2475  assert (0 && "Instruction is not processed!");
2476}
2477
2478/// endScope - Process end of a scope.
2479void DwarfDebug::endScope(const MachineInstr *MI) {
2480  if (InsnsEndScopeSet.count(MI) != 0) {
2481    // Emit a label if this instruction ends a scope.
2482    MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2483    Asm->OutStreamer.EmitLabel(Label);
2484    LabelsAfterInsn[MI] = Label;
2485  }
2486}
2487
2488/// getOrCreateDbgScope - Create DbgScope for the scope.
2489DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
2490                                          const MDNode *InlinedAt) {
2491  if (!InlinedAt) {
2492    DbgScope *WScope = DbgScopeMap.lookup(Scope);
2493    if (WScope)
2494      return WScope;
2495    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2496    DbgScopeMap.insert(std::make_pair(Scope, WScope));
2497    if (DIDescriptor(Scope).isLexicalBlock()) {
2498      DbgScope *Parent =
2499        getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2500      WScope->setParent(Parent);
2501      Parent->addScope(WScope);
2502    }
2503
2504    if (!WScope->getParent()) {
2505      StringRef SPName = DISubprogram(Scope).getLinkageName();
2506      // We used to check only for a linkage name, but that fails
2507      // since we began omitting the linkage name for private
2508      // functions.  The new way is to check for the name in metadata,
2509      // but that's not supported in old .ll test cases.  Ergo, we
2510      // check both.
2511      if (SPName == Asm->MF->getFunction()->getName() ||
2512          DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
2513        CurrentFnDbgScope = WScope;
2514    }
2515
2516    return WScope;
2517  }
2518
2519  getOrCreateAbstractScope(Scope);
2520  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2521  if (WScope)
2522    return WScope;
2523
2524  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2525  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2526  DILocation DL(InlinedAt);
2527  DbgScope *Parent =
2528    getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2529  WScope->setParent(Parent);
2530  Parent->addScope(WScope);
2531
2532  ConcreteScopes[InlinedAt] = WScope;
2533
2534  return WScope;
2535}
2536
2537/// hasValidLocation - Return true if debug location entry attached with
2538/// machine instruction encodes valid location info.
2539static bool hasValidLocation(LLVMContext &Ctx,
2540                             const MachineInstr *MInsn,
2541                             const MDNode *&Scope, const MDNode *&InlinedAt) {
2542  DebugLoc DL = MInsn->getDebugLoc();
2543  if (DL.isUnknown()) return false;
2544
2545  const MDNode *S = DL.getScope(Ctx);
2546
2547  // There is no need to create another DIE for compile unit. For all
2548  // other scopes, create one DbgScope now. This will be translated
2549  // into a scope DIE at the end.
2550  if (DIScope(S).isCompileUnit()) return false;
2551
2552  Scope = S;
2553  InlinedAt = DL.getInlinedAt(Ctx);
2554  return true;
2555}
2556
2557/// calculateDominanceGraph - Calculate dominance graph for DbgScope
2558/// hierarchy.
2559static void calculateDominanceGraph(DbgScope *Scope) {
2560  assert (Scope && "Unable to calculate scop edominance graph!");
2561  SmallVector<DbgScope *, 4> WorkStack;
2562  WorkStack.push_back(Scope);
2563  unsigned Counter = 0;
2564  while (!WorkStack.empty()) {
2565    DbgScope *WS = WorkStack.back();
2566    const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2567    bool visitedChildren = false;
2568    for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2569           SE = Children.end(); SI != SE; ++SI) {
2570      DbgScope *ChildScope = *SI;
2571      if (!ChildScope->getDFSOut()) {
2572        WorkStack.push_back(ChildScope);
2573        visitedChildren = true;
2574        ChildScope->setDFSIn(++Counter);
2575        break;
2576      }
2577    }
2578    if (!visitedChildren) {
2579      WorkStack.pop_back();
2580      WS->setDFSOut(++Counter);
2581    }
2582  }
2583}
2584
2585/// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2586static
2587void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2588                       DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2589{
2590#ifndef NDEBUG
2591  unsigned PrevDFSIn = 0;
2592  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2593       I != E; ++I) {
2594    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2595         II != IE; ++II) {
2596      const MachineInstr *MInsn = II;
2597      const MDNode *Scope = NULL;
2598      const MDNode *InlinedAt = NULL;
2599
2600      // Check if instruction has valid location information.
2601      if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2602        dbgs() << " [ ";
2603        if (InlinedAt)
2604          dbgs() << "*";
2605        DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2606          MI2ScopeMap.find(MInsn);
2607        if (DI != MI2ScopeMap.end()) {
2608          DbgScope *S = DI->second;
2609          dbgs() << S->getDFSIn();
2610          PrevDFSIn = S->getDFSIn();
2611        } else
2612          dbgs() << PrevDFSIn;
2613      } else
2614        dbgs() << " [ x" << PrevDFSIn;
2615      dbgs() << " ]";
2616      MInsn->dump();
2617    }
2618    dbgs() << "\n";
2619  }
2620#endif
2621}
2622/// extractScopeInformation - Scan machine instructions in this function
2623/// and collect DbgScopes. Return true, if at least one scope was found.
2624bool DwarfDebug::extractScopeInformation() {
2625  // If scope information was extracted using .dbg intrinsics then there is not
2626  // any need to extract these information by scanning each instruction.
2627  if (!DbgScopeMap.empty())
2628    return false;
2629
2630  // Scan each instruction and create scopes. First build working set of scopes.
2631  LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2632  SmallVector<DbgRange, 4> MIRanges;
2633  DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2634  const MDNode *PrevScope = NULL;
2635  const MDNode *PrevInlinedAt = NULL;
2636  const MachineInstr *RangeBeginMI = NULL;
2637  const MachineInstr *PrevMI = NULL;
2638  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2639       I != E; ++I) {
2640    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2641         II != IE; ++II) {
2642      const MachineInstr *MInsn = II;
2643      const MDNode *Scope = NULL;
2644      const MDNode *InlinedAt = NULL;
2645
2646      // Check if instruction has valid location information.
2647      if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2648        PrevMI = MInsn;
2649        continue;
2650      }
2651
2652      // If scope has not changed then skip this instruction.
2653      if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2654        PrevMI = MInsn;
2655        continue;
2656      }
2657
2658      if (RangeBeginMI) {
2659        // If we have alread seen a beginning of a instruction range and
2660        // current instruction scope does not match scope of first instruction
2661        // in this range then create a new instruction range.
2662        DbgRange R(RangeBeginMI, PrevMI);
2663        MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
2664                                                        PrevInlinedAt);
2665        MIRanges.push_back(R);
2666      }
2667
2668      // This is a beginning of a new instruction range.
2669      RangeBeginMI = MInsn;
2670
2671      // Reset previous markers.
2672      PrevMI = MInsn;
2673      PrevScope = Scope;
2674      PrevInlinedAt = InlinedAt;
2675    }
2676  }
2677
2678  // Create last instruction range.
2679  if (RangeBeginMI && PrevMI && PrevScope) {
2680    DbgRange R(RangeBeginMI, PrevMI);
2681    MIRanges.push_back(R);
2682    MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2683  }
2684
2685  if (!CurrentFnDbgScope)
2686    return false;
2687
2688  calculateDominanceGraph(CurrentFnDbgScope);
2689  if (PrintDbgScope)
2690    printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2691
2692  // Find ranges of instructions covered by each DbgScope;
2693  DbgScope *PrevDbgScope = NULL;
2694  for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2695         RE = MIRanges.end(); RI != RE; ++RI) {
2696    const DbgRange &R = *RI;
2697    DbgScope *S = MI2ScopeMap.lookup(R.first);
2698    assert (S && "Lost DbgScope for a machine instruction!");
2699    if (PrevDbgScope && !PrevDbgScope->dominates(S))
2700      PrevDbgScope->closeInsnRange(S);
2701    S->openInsnRange(R.first);
2702    S->extendInsnRange(R.second);
2703    PrevDbgScope = S;
2704  }
2705
2706  if (PrevDbgScope)
2707    PrevDbgScope->closeInsnRange();
2708
2709  identifyScopeMarkers();
2710
2711  return !DbgScopeMap.empty();
2712}
2713
2714/// identifyScopeMarkers() -
2715/// Each DbgScope has first instruction and last instruction to mark beginning
2716/// and end of a scope respectively. Create an inverse map that list scopes
2717/// starts (and ends) with an instruction. One instruction may start (or end)
2718/// multiple scopes. Ignore scopes that are not reachable.
2719void DwarfDebug::identifyScopeMarkers() {
2720  SmallVector<DbgScope *, 4> WorkList;
2721  WorkList.push_back(CurrentFnDbgScope);
2722  while (!WorkList.empty()) {
2723    DbgScope *S = WorkList.pop_back_val();
2724
2725    const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2726    if (!Children.empty())
2727      for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2728             SE = Children.end(); SI != SE; ++SI)
2729        WorkList.push_back(*SI);
2730
2731    if (S->isAbstractScope())
2732      continue;
2733
2734    const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2735    if (Ranges.empty())
2736      continue;
2737    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2738           RE = Ranges.end(); RI != RE; ++RI) {
2739      assert(RI->first && "DbgRange does not have first instruction!");
2740      assert(RI->second && "DbgRange does not have second instruction!");
2741      InsnsEndScopeSet.insert(RI->second);
2742    }
2743  }
2744}
2745
2746/// FindFirstDebugLoc - Find the first debug location in the function. This
2747/// is intended to be an approximation for the source position of the
2748/// beginning of the function.
2749static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2750  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2751       I != E; ++I)
2752    for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2753         MBBI != MBBE; ++MBBI) {
2754      DebugLoc DL = MBBI->getDebugLoc();
2755      if (!DL.isUnknown())
2756        return DL;
2757    }
2758  return DebugLoc();
2759}
2760
2761/// beginFunction - Gather pre-function debug information.  Assumes being
2762/// emitted immediately after the function entry point.
2763void DwarfDebug::beginFunction(const MachineFunction *MF) {
2764  if (!MMI->hasDebugInfo()) return;
2765  if (!extractScopeInformation()) return;
2766
2767  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2768                                        Asm->getFunctionNumber());
2769  // Assumes in correct section after the entry point.
2770  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2771
2772  // Emit label for the implicitly defined dbg.stoppoint at the start of the
2773  // function.
2774  DebugLoc FDL = FindFirstDebugLoc(MF);
2775  if (FDL.isUnknown()) return;
2776
2777  const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2778  const MDNode *TheScope = 0;
2779
2780  DISubprogram SP = getDISubprogram(Scope);
2781  unsigned Line, Col;
2782  if (SP.Verify()) {
2783    Line = SP.getLineNumber();
2784    Col = 0;
2785    TheScope = SP;
2786  } else {
2787    Line = FDL.getLine();
2788    Col = FDL.getCol();
2789    TheScope = Scope;
2790  }
2791
2792  recordSourceLine(Line, Col, TheScope);
2793
2794  /// ProcessedArgs - Collection of arguments already processed.
2795  SmallPtrSet<const MDNode *, 8> ProcessedArgs;
2796
2797  DebugLoc PrevLoc;
2798  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2799       I != E; ++I)
2800    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2801         II != IE; ++II) {
2802      const MachineInstr *MI = II;
2803      DebugLoc DL = MI->getDebugLoc();
2804      if (MI->isDebugValue()) {
2805        assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
2806        DIVariable DV(MI->getOperand(MI->getNumOperands() - 1).getMetadata());
2807        if (!DV.Verify()) continue;
2808        // If DBG_VALUE is for a local variable then it needs a label.
2809        if (DV.getTag() != dwarf::DW_TAG_arg_variable
2810            && isDbgValueInUndefinedReg(MI) == false)
2811          InsnNeedsLabel.insert(MI);
2812        // DBG_VALUE for inlined functions argument needs a label.
2813        else if (!DISubprogram(getDISubprogram(DV.getContext())).
2814                 describes(MF->getFunction()))
2815          InsnNeedsLabel.insert(MI);
2816        // DBG_VALUE indicating argument location change needs a label.
2817        else if (isDbgValueInUndefinedReg(MI) == false
2818                 && !ProcessedArgs.insert(DV))
2819          InsnNeedsLabel.insert(MI);
2820      } else {
2821        // If location is unknown then instruction needs a location only if
2822        // UnknownLocations flag is set.
2823        if (DL.isUnknown()) {
2824          if (UnknownLocations && !PrevLoc.isUnknown())
2825            InsnNeedsLabel.insert(MI);
2826        } else if (DL != PrevLoc)
2827          // Otherwise, instruction needs a location only if it is new location.
2828          InsnNeedsLabel.insert(MI);
2829      }
2830
2831      if (!DL.isUnknown() || UnknownLocations)
2832        PrevLoc = DL;
2833    }
2834
2835  PrevLabel = FunctionBeginSym;
2836}
2837
2838/// endFunction - Gather and emit post-function debug information.
2839///
2840void DwarfDebug::endFunction(const MachineFunction *MF) {
2841  if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2842
2843  if (CurrentFnDbgScope) {
2844
2845    // Define end label for subprogram.
2846    FunctionEndSym = Asm->GetTempSymbol("func_end",
2847                                        Asm->getFunctionNumber());
2848    // Assumes in correct section after the entry point.
2849    Asm->OutStreamer.EmitLabel(FunctionEndSym);
2850
2851    SmallPtrSet<const MDNode *, 16> ProcessedVars;
2852    collectVariableInfo(MF, ProcessedVars);
2853
2854    // Get function line info.
2855    if (!Lines.empty()) {
2856      // Get section line info.
2857      unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2858      if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2859      std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2860      // Append the function info to section info.
2861      SectionLineInfos.insert(SectionLineInfos.end(),
2862                              Lines.begin(), Lines.end());
2863    }
2864
2865    // Construct abstract scopes.
2866    for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2867           AE = AbstractScopesList.end(); AI != AE; ++AI) {
2868      DISubprogram SP((*AI)->getScopeNode());
2869      if (SP.Verify()) {
2870        // Collect info for variables that were optimized out.
2871        StringRef FName = SP.getLinkageName();
2872        if (FName.empty())
2873          FName = SP.getName();
2874        const Module *M = MF->getFunction()->getParent();
2875        if (NamedMDNode *NMD =
2876            M->getNamedMetadata(Twine("llvm.dbg.lv.",
2877                                      getRealLinkageName(FName)))) {
2878          for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2879          DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2880          if (!DV || !ProcessedVars.insert(DV))
2881            continue;
2882          DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2883          if (Scope)
2884            Scope->addVariable(new DbgVariable(DV));
2885          }
2886        }
2887      }
2888      if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2889        constructScopeDIE(*AI);
2890    }
2891
2892    DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2893
2894    if (!DisableFramePointerElim(*MF))
2895      addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
2896              dwarf::DW_FORM_flag, 1);
2897
2898
2899    DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2900                                                 MMI->getFrameMoves()));
2901  }
2902
2903  // Clear debug info
2904  CurrentFnDbgScope = NULL;
2905  InsnNeedsLabel.clear();
2906  DbgVariableToFrameIndexMap.clear();
2907  VarToAbstractVarMap.clear();
2908  DbgVariableToDbgInstMap.clear();
2909  DbgVariableLabelsMap.clear();
2910  DeleteContainerSeconds(DbgScopeMap);
2911  InsnsEndScopeSet.clear();
2912  ConcreteScopes.clear();
2913  DeleteContainerSeconds(AbstractScopes);
2914  AbstractScopesList.clear();
2915  AbstractVariables.clear();
2916  LabelsBeforeInsn.clear();
2917  LabelsAfterInsn.clear();
2918  Lines.clear();
2919  PrevLabel = NULL;
2920}
2921
2922/// recordVariableFrameIndex - Record a variable's index.
2923void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2924  assert (V && "Invalid DbgVariable!");
2925  DbgVariableToFrameIndexMap[V] = Index;
2926}
2927
2928/// findVariableFrameIndex - Return true if frame index for the variable
2929/// is found. Update FI to hold value of the index.
2930bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2931  assert (V && "Invalid DbgVariable!");
2932  DenseMap<const DbgVariable *, int>::iterator I =
2933    DbgVariableToFrameIndexMap.find(V);
2934  if (I == DbgVariableToFrameIndexMap.end())
2935    return false;
2936  *FI = I->second;
2937  return true;
2938}
2939
2940/// findVariableLabel - Find MCSymbol for the variable.
2941const MCSymbol *DwarfDebug::findVariableLabel(const DbgVariable *V) {
2942  DenseMap<const DbgVariable *, const MCSymbol *>::iterator I
2943    = DbgVariableLabelsMap.find(V);
2944  if (I == DbgVariableLabelsMap.end())
2945    return NULL;
2946  else return I->second;
2947}
2948
2949/// findDbgScope - Find DbgScope for the debug loc attached with an
2950/// instruction.
2951DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2952  DbgScope *Scope = NULL;
2953  LLVMContext &Ctx =
2954    MInsn->getParent()->getParent()->getFunction()->getContext();
2955  DebugLoc DL = MInsn->getDebugLoc();
2956
2957  if (DL.isUnknown())
2958    return Scope;
2959
2960  if (const MDNode *IA = DL.getInlinedAt(Ctx))
2961    Scope = ConcreteScopes.lookup(IA);
2962  if (Scope == 0)
2963    Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2964
2965  return Scope;
2966}
2967
2968
2969/// recordSourceLine - Register a source line with debug info. Returns the
2970/// unique label that was emitted and which provides correspondence to
2971/// the source line list.
2972MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2973                                       const MDNode *S) {
2974  StringRef Dir;
2975  StringRef Fn;
2976
2977  unsigned Src = 1;
2978  if (S) {
2979    DIDescriptor Scope(S);
2980
2981    if (Scope.isCompileUnit()) {
2982      DICompileUnit CU(S);
2983      Dir = CU.getDirectory();
2984      Fn = CU.getFilename();
2985    } else if (Scope.isSubprogram()) {
2986      DISubprogram SP(S);
2987      Dir = SP.getDirectory();
2988      Fn = SP.getFilename();
2989    } else if (Scope.isLexicalBlock()) {
2990      DILexicalBlock DB(S);
2991      Dir = DB.getDirectory();
2992      Fn = DB.getFilename();
2993    } else
2994      assert(0 && "Unexpected scope info");
2995
2996    Src = GetOrCreateSourceID(Dir, Fn);
2997  }
2998
2999  MCSymbol *Label = MMI->getContext().CreateTempSymbol();
3000  Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
3001
3002  Asm->OutStreamer.EmitLabel(Label);
3003  return Label;
3004}
3005
3006//===----------------------------------------------------------------------===//
3007// Emit Methods
3008//===----------------------------------------------------------------------===//
3009
3010/// computeSizeAndOffset - Compute the size and offset of a DIE.
3011///
3012unsigned
3013DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
3014  // Get the children.
3015  const std::vector<DIE *> &Children = Die->getChildren();
3016
3017  // If not last sibling and has children then add sibling offset attribute.
3018  if (!Last && !Children.empty())
3019    Die->addSiblingOffset(DIEValueAllocator);
3020
3021  // Record the abbreviation.
3022  assignAbbrevNumber(Die->getAbbrev());
3023
3024  // Get the abbreviation for this DIE.
3025  unsigned AbbrevNumber = Die->getAbbrevNumber();
3026  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3027
3028  // Set DIE offset
3029  Die->setOffset(Offset);
3030
3031  // Start the size with the size of abbreviation code.
3032  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
3033
3034  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3035  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3036
3037  // Size the DIE attribute values.
3038  for (unsigned i = 0, N = Values.size(); i < N; ++i)
3039    // Size attribute value.
3040    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
3041
3042  // Size the DIE children if any.
3043  if (!Children.empty()) {
3044    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
3045           "Children flag not set");
3046
3047    for (unsigned j = 0, M = Children.size(); j < M; ++j)
3048      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
3049
3050    // End of children marker.
3051    Offset += sizeof(int8_t);
3052  }
3053
3054  Die->setSize(Offset - Die->getOffset());
3055  return Offset;
3056}
3057
3058/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
3059///
3060void DwarfDebug::computeSizeAndOffsets() {
3061  unsigned PrevOffset = 0;
3062  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3063         E = CUMap.end(); I != E; ++I) {
3064    // Compute size of compile unit header.
3065    static unsigned Offset = PrevOffset +
3066      sizeof(int32_t) + // Length of Compilation Unit Info
3067      sizeof(int16_t) + // DWARF version number
3068      sizeof(int32_t) + // Offset Into Abbrev. Section
3069      sizeof(int8_t);   // Pointer Size (in bytes)
3070    computeSizeAndOffset(I->second->getCUDie(), Offset, true);
3071    PrevOffset = Offset;
3072  }
3073}
3074
3075/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
3076/// temporary label to it if SymbolStem is specified.
3077static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
3078                                const char *SymbolStem = 0) {
3079  Asm->OutStreamer.SwitchSection(Section);
3080  if (!SymbolStem) return 0;
3081
3082  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
3083  Asm->OutStreamer.EmitLabel(TmpSym);
3084  return TmpSym;
3085}
3086
3087/// EmitSectionLabels - Emit initial Dwarf sections with a label at
3088/// the start of each one.
3089void DwarfDebug::EmitSectionLabels() {
3090  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
3091
3092  // Dwarf sections base addresses.
3093  if (Asm->MAI->doesDwarfRequireFrameSection()) {
3094    DwarfFrameSectionSym =
3095      EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
3096   }
3097
3098  DwarfInfoSectionSym =
3099    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
3100  DwarfAbbrevSectionSym =
3101    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
3102  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
3103
3104  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
3105    EmitSectionSym(Asm, MacroInfo);
3106
3107  EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
3108  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
3109  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
3110  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
3111  DwarfStrSectionSym =
3112    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
3113  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
3114                                             "debug_range");
3115
3116  DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
3117                                           "section_debug_loc");
3118
3119  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
3120  EmitSectionSym(Asm, TLOF.getDataSection());
3121}
3122
3123/// emitDIE - Recusively Emits a debug information entry.
3124///
3125void DwarfDebug::emitDIE(DIE *Die) {
3126  // Get the abbreviation for this DIE.
3127  unsigned AbbrevNumber = Die->getAbbrevNumber();
3128  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3129
3130  // Emit the code (index) for the abbreviation.
3131  if (Asm->isVerbose())
3132    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
3133                                Twine::utohexstr(Die->getOffset()) + ":0x" +
3134                                Twine::utohexstr(Die->getSize()) + " " +
3135                                dwarf::TagString(Abbrev->getTag()));
3136  Asm->EmitULEB128(AbbrevNumber);
3137
3138  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3139  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3140
3141  // Emit the DIE attribute values.
3142  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3143    unsigned Attr = AbbrevData[i].getAttribute();
3144    unsigned Form = AbbrevData[i].getForm();
3145    assert(Form && "Too many attributes for DIE (check abbreviation)");
3146
3147    if (Asm->isVerbose())
3148      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
3149
3150    switch (Attr) {
3151    case dwarf::DW_AT_sibling:
3152      Asm->EmitInt32(Die->getSiblingOffset());
3153      break;
3154    case dwarf::DW_AT_abstract_origin: {
3155      DIEEntry *E = cast<DIEEntry>(Values[i]);
3156      DIE *Origin = E->getEntry();
3157      unsigned Addr = Origin->getOffset();
3158      Asm->EmitInt32(Addr);
3159      break;
3160    }
3161    case dwarf::DW_AT_ranges: {
3162      // DW_AT_range Value encodes offset in debug_range section.
3163      DIEInteger *V = cast<DIEInteger>(Values[i]);
3164
3165      if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
3166        Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
3167                                 V->getValue(),
3168                                 4);
3169      } else {
3170        Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
3171                                       V->getValue(),
3172                                       DwarfDebugRangeSectionSym,
3173                                       4);
3174      }
3175      break;
3176    }
3177    case dwarf::DW_AT_location: {
3178      if (UseDotDebugLocEntry.count(Die) != 0) {
3179        DIELabel *L = cast<DIELabel>(Values[i]);
3180        Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
3181      } else
3182        Values[i]->EmitValue(Asm, Form);
3183      break;
3184    }
3185    case dwarf::DW_AT_accessibility: {
3186      if (Asm->isVerbose()) {
3187        DIEInteger *V = cast<DIEInteger>(Values[i]);
3188        Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
3189      }
3190      Values[i]->EmitValue(Asm, Form);
3191      break;
3192    }
3193    default:
3194      // Emit an attribute using the defined form.
3195      Values[i]->EmitValue(Asm, Form);
3196      break;
3197    }
3198  }
3199
3200  // Emit the DIE children if any.
3201  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
3202    const std::vector<DIE *> &Children = Die->getChildren();
3203
3204    for (unsigned j = 0, M = Children.size(); j < M; ++j)
3205      emitDIE(Children[j]);
3206
3207    if (Asm->isVerbose())
3208      Asm->OutStreamer.AddComment("End Of Children Mark");
3209    Asm->EmitInt8(0);
3210  }
3211}
3212
3213/// emitDebugInfo - Emit the debug info section.
3214///
3215void DwarfDebug::emitDebugInfo() {
3216  // Start debug info section.
3217  Asm->OutStreamer.SwitchSection(
3218                            Asm->getObjFileLowering().getDwarfInfoSection());
3219  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3220         E = CUMap.end(); I != E; ++I) {
3221    CompileUnit *TheCU = I->second;
3222    DIE *Die = TheCU->getCUDie();
3223
3224    // Emit the compile units header.
3225    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
3226                                                  TheCU->getID()));
3227
3228    // Emit size of content not including length itself
3229    unsigned ContentSize = Die->getSize() +
3230      sizeof(int16_t) + // DWARF version number
3231      sizeof(int32_t) + // Offset Into Abbrev. Section
3232      sizeof(int8_t) +  // Pointer Size (in bytes)
3233      sizeof(int32_t);  // FIXME - extra pad for gdb bug.
3234
3235    Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
3236    Asm->EmitInt32(ContentSize);
3237    Asm->OutStreamer.AddComment("DWARF version number");
3238    Asm->EmitInt16(dwarf::DWARF_VERSION);
3239    Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
3240    Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
3241                           DwarfAbbrevSectionSym);
3242    Asm->OutStreamer.AddComment("Address Size (in bytes)");
3243    Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3244
3245    emitDIE(Die);
3246    // FIXME - extra padding for gdb bug.
3247    Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
3248    Asm->EmitInt8(0);
3249    Asm->EmitInt8(0);
3250    Asm->EmitInt8(0);
3251    Asm->EmitInt8(0);
3252    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
3253  }
3254}
3255
3256/// emitAbbreviations - Emit the abbreviation section.
3257///
3258void DwarfDebug::emitAbbreviations() const {
3259  // Check to see if it is worth the effort.
3260  if (!Abbreviations.empty()) {
3261    // Start the debug abbrev section.
3262    Asm->OutStreamer.SwitchSection(
3263                            Asm->getObjFileLowering().getDwarfAbbrevSection());
3264
3265    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
3266
3267    // For each abbrevation.
3268    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3269      // Get abbreviation data
3270      const DIEAbbrev *Abbrev = Abbreviations[i];
3271
3272      // Emit the abbrevations code (base 1 index.)
3273      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
3274
3275      // Emit the abbreviations data.
3276      Abbrev->Emit(Asm);
3277    }
3278
3279    // Mark end of abbreviations.
3280    Asm->EmitULEB128(0, "EOM(3)");
3281
3282    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
3283  }
3284}
3285
3286/// emitEndOfLineMatrix - Emit the last address of the section and the end of
3287/// the line matrix.
3288///
3289void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
3290  // Define last address of section.
3291  Asm->OutStreamer.AddComment("Extended Op");
3292  Asm->EmitInt8(0);
3293
3294  Asm->OutStreamer.AddComment("Op size");
3295  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3296  Asm->OutStreamer.AddComment("DW_LNE_set_address");
3297  Asm->EmitInt8(dwarf::DW_LNE_set_address);
3298
3299  Asm->OutStreamer.AddComment("Section end label");
3300
3301  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
3302                                   Asm->getTargetData().getPointerSize(),
3303                                   0/*AddrSpace*/);
3304
3305  // Mark end of matrix.
3306  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
3307  Asm->EmitInt8(0);
3308  Asm->EmitInt8(1);
3309  Asm->EmitInt8(1);
3310}
3311
3312/// emitDebugLines - Emit source line information.
3313///
3314void DwarfDebug::emitDebugLines() {
3315  // If the target is using .loc/.file, the assembler will be emitting the
3316  // .debug_line table automatically.
3317  if (Asm->MAI->hasDotLocAndDotFile())
3318    return;
3319
3320  // Minimum line delta, thus ranging from -10..(255-10).
3321  const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
3322  // Maximum line delta, thus ranging from -10..(255-10).
3323  const int MaxLineDelta = 255 + MinLineDelta;
3324
3325  // Start the dwarf line section.
3326  Asm->OutStreamer.SwitchSection(
3327                            Asm->getObjFileLowering().getDwarfLineSection());
3328
3329  // Construct the section header.
3330  Asm->OutStreamer.AddComment("Length of Source Line Info");
3331  Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
3332                           Asm->GetTempSymbol("line_begin"), 4);
3333  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
3334
3335  Asm->OutStreamer.AddComment("DWARF version number");
3336  Asm->EmitInt16(dwarf::DWARF_VERSION);
3337
3338  Asm->OutStreamer.AddComment("Prolog Length");
3339  Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
3340                           Asm->GetTempSymbol("line_prolog_begin"), 4);
3341  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
3342
3343  Asm->OutStreamer.AddComment("Minimum Instruction Length");
3344  Asm->EmitInt8(1);
3345  Asm->OutStreamer.AddComment("Default is_stmt_start flag");
3346  Asm->EmitInt8(1);
3347  Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
3348  Asm->EmitInt8(MinLineDelta);
3349  Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
3350  Asm->EmitInt8(MaxLineDelta);
3351  Asm->OutStreamer.AddComment("Special Opcode Base");
3352  Asm->EmitInt8(-MinLineDelta);
3353
3354  // Line number standard opcode encodings argument count
3355  Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
3356  Asm->EmitInt8(0);
3357  Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
3358  Asm->EmitInt8(1);
3359  Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
3360  Asm->EmitInt8(1);
3361  Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
3362  Asm->EmitInt8(1);
3363  Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
3364  Asm->EmitInt8(1);
3365  Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
3366  Asm->EmitInt8(0);
3367  Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
3368  Asm->EmitInt8(0);
3369  Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
3370  Asm->EmitInt8(0);
3371  Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
3372  Asm->EmitInt8(1);
3373
3374  // Emit directories.
3375  for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
3376    const std::string &Dir = getSourceDirectoryName(DI);
3377    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
3378    Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
3379  }
3380
3381  Asm->OutStreamer.AddComment("End of directories");
3382  Asm->EmitInt8(0);
3383
3384  // Emit files.
3385  for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
3386    // Remember source id starts at 1.
3387    std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
3388    const std::string &FN = getSourceFileName(Id.second);
3389    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
3390    Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
3391
3392    Asm->EmitULEB128(Id.first, "Directory #");
3393    Asm->EmitULEB128(0, "Mod date");
3394    Asm->EmitULEB128(0, "File size");
3395  }
3396
3397  Asm->OutStreamer.AddComment("End of files");
3398  Asm->EmitInt8(0);
3399
3400  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
3401
3402  // A sequence for each text section.
3403  unsigned SecSrcLinesSize = SectionSourceLines.size();
3404
3405  for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3406    // Isolate current sections line info.
3407    const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
3408
3409    // Dwarf assumes we start with first line of first source file.
3410    unsigned Source = 1;
3411    unsigned Line = 1;
3412
3413    // Construct rows of the address, source, line, column matrix.
3414    for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3415      const SrcLineInfo &LineInfo = LineInfos[i];
3416      MCSymbol *Label = LineInfo.getLabel();
3417      if (!Label->isDefined()) continue; // Not emitted, in dead code.
3418
3419      if (Asm->isVerbose()) {
3420        std::pair<unsigned, unsigned> SrcID =
3421          getSourceDirectoryAndFileIds(LineInfo.getSourceID());
3422        Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
3423                                    "/" +
3424                                    Twine(getSourceFileName(SrcID.second)) +
3425                                    ":" + Twine(LineInfo.getLine()));
3426      }
3427
3428      // Define the line address.
3429      Asm->OutStreamer.AddComment("Extended Op");
3430      Asm->EmitInt8(0);
3431      Asm->OutStreamer.AddComment("Op size");
3432      Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3433
3434      Asm->OutStreamer.AddComment("DW_LNE_set_address");
3435      Asm->EmitInt8(dwarf::DW_LNE_set_address);
3436
3437      Asm->OutStreamer.AddComment("Location label");
3438      Asm->OutStreamer.EmitSymbolValue(Label,
3439                                       Asm->getTargetData().getPointerSize(),
3440                                       0/*AddrSpace*/);
3441
3442      // If change of source, then switch to the new source.
3443      if (Source != LineInfo.getSourceID()) {
3444        Source = LineInfo.getSourceID();
3445        Asm->OutStreamer.AddComment("DW_LNS_set_file");
3446        Asm->EmitInt8(dwarf::DW_LNS_set_file);
3447        Asm->EmitULEB128(Source, "New Source");
3448      }
3449
3450      // If change of line.
3451      if (Line != LineInfo.getLine()) {
3452        // Determine offset.
3453        int Offset = LineInfo.getLine() - Line;
3454        int Delta = Offset - MinLineDelta;
3455
3456        // Update line.
3457        Line = LineInfo.getLine();
3458
3459        // If delta is small enough and in range...
3460        if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3461          // ... then use fast opcode.
3462          Asm->OutStreamer.AddComment("Line Delta");
3463          Asm->EmitInt8(Delta - MinLineDelta);
3464        } else {
3465          // ... otherwise use long hand.
3466          Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3467          Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3468          Asm->EmitSLEB128(Offset, "Line Offset");
3469          Asm->OutStreamer.AddComment("DW_LNS_copy");
3470          Asm->EmitInt8(dwarf::DW_LNS_copy);
3471        }
3472      } else {
3473        // Copy the previous row (different address or source)
3474        Asm->OutStreamer.AddComment("DW_LNS_copy");
3475        Asm->EmitInt8(dwarf::DW_LNS_copy);
3476      }
3477    }
3478
3479    emitEndOfLineMatrix(j + 1);
3480  }
3481
3482  if (SecSrcLinesSize == 0)
3483    // Because we're emitting a debug_line section, we still need a line
3484    // table. The linker and friends expect it to exist. If there's nothing to
3485    // put into it, emit an empty table.
3486    emitEndOfLineMatrix(1);
3487
3488  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3489}
3490
3491/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3492///
3493void DwarfDebug::emitCommonDebugFrame() {
3494  if (!Asm->MAI->doesDwarfRequireFrameSection())
3495    return;
3496
3497  int stackGrowth = Asm->getTargetData().getPointerSize();
3498  if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3499      TargetFrameInfo::StackGrowsDown)
3500    stackGrowth *= -1;
3501
3502  // Start the dwarf frame section.
3503  Asm->OutStreamer.SwitchSection(
3504                              Asm->getObjFileLowering().getDwarfFrameSection());
3505
3506  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3507  Asm->OutStreamer.AddComment("Length of Common Information Entry");
3508  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3509                           Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3510
3511  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3512  Asm->OutStreamer.AddComment("CIE Identifier Tag");
3513  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3514  Asm->OutStreamer.AddComment("CIE Version");
3515  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3516  Asm->OutStreamer.AddComment("CIE Augmentation");
3517  Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3518  Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3519  Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3520  Asm->OutStreamer.AddComment("CIE RA Column");
3521  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3522  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3523
3524  std::vector<MachineMove> Moves;
3525  RI->getInitialFrameState(Moves);
3526
3527  Asm->EmitFrameMoves(Moves, 0, false);
3528
3529  Asm->EmitAlignment(2);
3530  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3531}
3532
3533/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3534/// section.
3535void DwarfDebug::
3536emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3537  if (!Asm->MAI->doesDwarfRequireFrameSection())
3538    return;
3539
3540  // Start the dwarf frame section.
3541  Asm->OutStreamer.SwitchSection(
3542                              Asm->getObjFileLowering().getDwarfFrameSection());
3543
3544  Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3545  MCSymbol *DebugFrameBegin =
3546    Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3547  MCSymbol *DebugFrameEnd =
3548    Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3549  Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3550
3551  Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3552
3553  Asm->OutStreamer.AddComment("FDE CIE offset");
3554  Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3555                         DwarfFrameSectionSym);
3556
3557  Asm->OutStreamer.AddComment("FDE initial location");
3558  MCSymbol *FuncBeginSym =
3559    Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3560  Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3561                                   Asm->getTargetData().getPointerSize(),
3562                                   0/*AddrSpace*/);
3563
3564
3565  Asm->OutStreamer.AddComment("FDE address range");
3566  Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3567                           FuncBeginSym, Asm->getTargetData().getPointerSize());
3568
3569  Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3570
3571  Asm->EmitAlignment(2);
3572  Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3573}
3574
3575/// emitDebugPubNames - Emit visible names into a debug pubnames section.
3576///
3577void DwarfDebug::emitDebugPubNames() {
3578  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3579         E = CUMap.end(); I != E; ++I) {
3580    CompileUnit *TheCU = I->second;
3581    // Start the dwarf pubnames section.
3582    Asm->OutStreamer.SwitchSection(
3583      Asm->getObjFileLowering().getDwarfPubNamesSection());
3584
3585    Asm->OutStreamer.AddComment("Length of Public Names Info");
3586    Asm->EmitLabelDifference(
3587      Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
3588      Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
3589
3590    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3591                                                  TheCU->getID()));
3592
3593    Asm->OutStreamer.AddComment("DWARF Version");
3594    Asm->EmitInt16(dwarf::DWARF_VERSION);
3595
3596    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3597    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3598                           DwarfInfoSectionSym);
3599
3600    Asm->OutStreamer.AddComment("Compilation Unit Length");
3601    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3602                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
3603                             4);
3604
3605    const StringMap<DIE*> &Globals = TheCU->getGlobals();
3606    for (StringMap<DIE*>::const_iterator
3607           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3608      const char *Name = GI->getKeyData();
3609      DIE *Entity = GI->second;
3610
3611      Asm->OutStreamer.AddComment("DIE offset");
3612      Asm->EmitInt32(Entity->getOffset());
3613
3614      if (Asm->isVerbose())
3615        Asm->OutStreamer.AddComment("External Name");
3616      Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3617    }
3618
3619    Asm->OutStreamer.AddComment("End Mark");
3620    Asm->EmitInt32(0);
3621    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3622                                                TheCU->getID()));
3623  }
3624}
3625
3626void DwarfDebug::emitDebugPubTypes() {
3627  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3628         E = CUMap.end(); I != E; ++I) {
3629    CompileUnit *TheCU = I->second;
3630    // Start the dwarf pubnames section.
3631    Asm->OutStreamer.SwitchSection(
3632      Asm->getObjFileLowering().getDwarfPubTypesSection());
3633    Asm->OutStreamer.AddComment("Length of Public Types Info");
3634    Asm->EmitLabelDifference(
3635      Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
3636      Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
3637
3638    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3639                                                  TheCU->getID()));
3640
3641    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3642    Asm->EmitInt16(dwarf::DWARF_VERSION);
3643
3644    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3645    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3646                           DwarfInfoSectionSym);
3647
3648    Asm->OutStreamer.AddComment("Compilation Unit Length");
3649    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3650                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
3651                             4);
3652
3653    const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
3654    for (StringMap<DIE*>::const_iterator
3655           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3656      const char *Name = GI->getKeyData();
3657      DIE * Entity = GI->second;
3658
3659      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3660      Asm->EmitInt32(Entity->getOffset());
3661
3662      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3663      Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3664    }
3665
3666    Asm->OutStreamer.AddComment("End Mark");
3667    Asm->EmitInt32(0);
3668    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3669                                                  TheCU->getID()));
3670  }
3671}
3672
3673/// emitDebugStr - Emit visible names into a debug str section.
3674///
3675void DwarfDebug::emitDebugStr() {
3676  // Check to see if it is worth the effort.
3677  if (StringPool.empty()) return;
3678
3679  // Start the dwarf str section.
3680  Asm->OutStreamer.SwitchSection(
3681                                Asm->getObjFileLowering().getDwarfStrSection());
3682
3683  // Get all of the string pool entries and put them in an array by their ID so
3684  // we can sort them.
3685  SmallVector<std::pair<unsigned,
3686      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3687
3688  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3689       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3690    Entries.push_back(std::make_pair(I->second.second, &*I));
3691
3692  array_pod_sort(Entries.begin(), Entries.end());
3693
3694  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3695    // Emit a label for reference from debug information entries.
3696    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3697
3698    // Emit the string itself.
3699    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3700  }
3701}
3702
3703/// emitDebugLoc - Emit visible names into a debug loc section.
3704///
3705void DwarfDebug::emitDebugLoc() {
3706  if (DotDebugLocEntries.empty())
3707    return;
3708
3709  // Start the dwarf loc section.
3710  Asm->OutStreamer.SwitchSection(
3711    Asm->getObjFileLowering().getDwarfLocSection());
3712  unsigned char Size = Asm->getTargetData().getPointerSize();
3713  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
3714  unsigned index = 1;
3715  for (SmallVector<DotDebugLocEntry, 4>::iterator
3716         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
3717       I != E; ++I, ++index) {
3718    DotDebugLocEntry Entry = *I;
3719    if (Entry.isEmpty()) {
3720      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3721      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3722      Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
3723    } else {
3724      Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
3725      Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
3726      const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3727      unsigned Reg = RI->getDwarfRegNum(Entry.Loc.getReg(), false);
3728      if (int Offset =  Entry.Loc.getOffset()) {
3729        // If the value is at a certain offset from frame register then
3730        // use DW_OP_fbreg.
3731        unsigned OffsetSize = Offset ? MCAsmInfo::getSLEB128Size(Offset) : 1;
3732        Asm->OutStreamer.AddComment("Loc expr size");
3733        Asm->EmitInt16(1 + OffsetSize);
3734        Asm->OutStreamer.AddComment(
3735          dwarf::OperationEncodingString(dwarf::DW_OP_fbreg));
3736        Asm->EmitInt8(dwarf::DW_OP_fbreg);
3737        Asm->OutStreamer.AddComment("Offset");
3738        Asm->EmitSLEB128(Offset);
3739      } else {
3740        if (Reg < 32) {
3741          Asm->OutStreamer.AddComment("Loc expr size");
3742          Asm->EmitInt16(1);
3743          Asm->OutStreamer.AddComment(
3744            dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
3745          Asm->EmitInt8(dwarf::DW_OP_reg0 + Reg);
3746        } else {
3747          Asm->OutStreamer.AddComment("Loc expr size");
3748          Asm->EmitInt16(1 + MCAsmInfo::getULEB128Size(Reg));
3749          Asm->EmitInt8(dwarf::DW_OP_regx);
3750          Asm->EmitULEB128(Reg);
3751        }
3752      }
3753    }
3754  }
3755}
3756
3757/// EmitDebugARanges - Emit visible names into a debug aranges section.
3758///
3759void DwarfDebug::EmitDebugARanges() {
3760  // Start the dwarf aranges section.
3761  Asm->OutStreamer.SwitchSection(
3762                          Asm->getObjFileLowering().getDwarfARangesSection());
3763}
3764
3765/// emitDebugRanges - Emit visible names into a debug ranges section.
3766///
3767void DwarfDebug::emitDebugRanges() {
3768  // Start the dwarf ranges section.
3769  Asm->OutStreamer.SwitchSection(
3770    Asm->getObjFileLowering().getDwarfRangesSection());
3771  unsigned char Size = Asm->getTargetData().getPointerSize();
3772  for (SmallVector<const MCSymbol *, 8>::iterator
3773         I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3774       I != E; ++I) {
3775    if (*I)
3776      Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3777    else
3778      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3779  }
3780}
3781
3782/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3783///
3784void DwarfDebug::emitDebugMacInfo() {
3785  if (const MCSection *LineInfo =
3786      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3787    // Start the dwarf macinfo section.
3788    Asm->OutStreamer.SwitchSection(LineInfo);
3789  }
3790}
3791
3792/// emitDebugInlineInfo - Emit inline info using following format.
3793/// Section Header:
3794/// 1. length of section
3795/// 2. Dwarf version number
3796/// 3. address size.
3797///
3798/// Entries (one "entry" for each function that was inlined):
3799///
3800/// 1. offset into __debug_str section for MIPS linkage name, if exists;
3801///   otherwise offset into __debug_str for regular function name.
3802/// 2. offset into __debug_str section for regular function name.
3803/// 3. an unsigned LEB128 number indicating the number of distinct inlining
3804/// instances for the function.
3805///
3806/// The rest of the entry consists of a {die_offset, low_pc} pair for each
3807/// inlined instance; the die_offset points to the inlined_subroutine die in the
3808/// __debug_info section, and the low_pc is the starting address for the
3809/// inlining instance.
3810void DwarfDebug::emitDebugInlineInfo() {
3811  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3812    return;
3813
3814  if (!FirstCU)
3815    return;
3816
3817  Asm->OutStreamer.SwitchSection(
3818                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
3819
3820  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3821  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3822                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3823
3824  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3825
3826  Asm->OutStreamer.AddComment("Dwarf Version");
3827  Asm->EmitInt16(dwarf::DWARF_VERSION);
3828  Asm->OutStreamer.AddComment("Address Size (in bytes)");
3829  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3830
3831  for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3832         E = InlinedSPNodes.end(); I != E; ++I) {
3833
3834    const MDNode *Node = *I;
3835    DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3836      = InlineInfo.find(Node);
3837    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3838    DISubprogram SP(Node);
3839    StringRef LName = SP.getLinkageName();
3840    StringRef Name = SP.getName();
3841
3842    Asm->OutStreamer.AddComment("MIPS linkage name");
3843    if (LName.empty()) {
3844      Asm->OutStreamer.EmitBytes(Name, 0);
3845      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3846    } else
3847      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3848                             DwarfStrSectionSym);
3849
3850    Asm->OutStreamer.AddComment("Function name");
3851    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3852    Asm->EmitULEB128(Labels.size(), "Inline count");
3853
3854    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3855           LE = Labels.end(); LI != LE; ++LI) {
3856      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3857      Asm->EmitInt32(LI->second->getOffset());
3858
3859      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3860      Asm->OutStreamer.EmitSymbolValue(LI->first,
3861                                       Asm->getTargetData().getPointerSize(),0);
3862    }
3863  }
3864
3865  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
3866}
3867