DwarfDebug.cpp revision c26f5447e39b43a6dd9c1a9d88227f4adf3b5600
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 "DwarfCompileUnit.h"
18#include "llvm/Constants.h"
19#include "llvm/Module.h"
20#include "llvm/Instructions.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineModuleInfo.h"
23#include "llvm/MC/MCAsmInfo.h"
24#include "llvm/MC/MCSection.h"
25#include "llvm/MC/MCStreamer.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/Target/Mangler.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetFrameLowering.h"
30#include "llvm/Target/TargetLoweringObjectFile.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetRegisterInfo.h"
33#include "llvm/Target/TargetOptions.h"
34#include "llvm/Analysis/DebugInfo.h"
35#include "llvm/Analysis/DIBuilder.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/ValueHandle.h"
43#include "llvm/Support/FormattedStream.h"
44#include "llvm/Support/Timer.h"
45#include "llvm/Support/Path.h"
46using namespace llvm;
47
48static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
49     cl::desc("Print DbgScope information for each machine instruction"));
50
51static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
52                                              cl::Hidden,
53     cl::desc("Disable debug info printing"));
54
55static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
56     cl::desc("Make an absence of debug location information explicit."),
57     cl::init(false));
58
59#ifndef NDEBUG
60STATISTIC(BlocksWithoutLineNo, "Number of blocks without any line number");
61#endif
62
63namespace {
64  const char *DWARFGroupName = "DWARF Emission";
65  const char *DbgTimerName = "DWARF Debug Writer";
66} // end anonymous namespace
67
68//===----------------------------------------------------------------------===//
69
70/// Configuration values for initial hash set sizes (log2).
71///
72static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
73
74namespace llvm {
75
76DIType DbgVariable::getType()               const {
77  DIType Ty = Var.getType();
78  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
79  // addresses instead.
80  if (Var.isBlockByrefVariable()) {
81    /* Byref variables, in Blocks, are declared by the programmer as
82       "SomeType VarName;", but the compiler creates a
83       __Block_byref_x_VarName struct, and gives the variable VarName
84       either the struct, or a pointer to the struct, as its type.  This
85       is necessary for various behind-the-scenes things the compiler
86       needs to do with by-reference variables in blocks.
87
88       However, as far as the original *programmer* is concerned, the
89       variable should still have type 'SomeType', as originally declared.
90
91       The following function dives into the __Block_byref_x_VarName
92       struct to find the original type of the variable.  This will be
93       passed back to the code generating the type for the Debug
94       Information Entry for the variable 'VarName'.  'VarName' will then
95       have the original type 'SomeType' in its debug information.
96
97       The original type 'SomeType' will be the type of the field named
98       'VarName' inside the __Block_byref_x_VarName struct.
99
100       NOTE: In order for this to not completely fail on the debugger
101       side, the Debug Information Entry for the variable VarName needs to
102       have a DW_AT_location that tells the debugger how to unwind through
103       the pointers and __Block_byref_x_VarName struct to find the actual
104       value of the variable.  The function addBlockByrefType does this.  */
105    DIType subType = Ty;
106    unsigned tag = Ty.getTag();
107
108    if (tag == dwarf::DW_TAG_pointer_type) {
109      DIDerivedType DTy = DIDerivedType(Ty);
110      subType = DTy.getTypeDerivedFrom();
111    }
112
113    DICompositeType blockStruct = DICompositeType(subType);
114    DIArray Elements = blockStruct.getTypeArray();
115
116    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
117      DIDescriptor Element = Elements.getElement(i);
118      DIDerivedType DT = DIDerivedType(Element);
119      if (getName() == DT.getName())
120        return (DT.getTypeDerivedFrom());
121    }
122    return Ty;
123  }
124  return Ty;
125}
126
127//===----------------------------------------------------------------------===//
128/// DbgRange - This is used to track range of instructions with identical
129/// debug info scope.
130///
131typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
132
133//===----------------------------------------------------------------------===//
134/// DbgScope - This class is used to track scope information.
135///
136class DbgScope {
137  DbgScope *Parent;                   // Parent to this scope.
138  DIDescriptor Desc;                  // Debug info descriptor for scope.
139  // Location at which this scope is inlined.
140  AssertingVH<const MDNode> InlinedAtLocation;
141  bool AbstractScope;                 // Abstract Scope
142  const MachineInstr *LastInsn;       // Last instruction of this scope.
143  const MachineInstr *FirstInsn;      // First instruction of this scope.
144  unsigned DFSIn, DFSOut;
145  // Scopes defined in scope.  Contents not owned.
146  SmallVector<DbgScope *, 4> Scopes;
147  // Variables declared in scope.  Contents owned.
148  SmallVector<DbgVariable *, 8> Variables;
149  SmallVector<DbgRange, 4> Ranges;
150  // Private state for dump()
151  mutable unsigned IndentLevel;
152public:
153  DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
154    : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
155      LastInsn(0), FirstInsn(0),
156      DFSIn(0), DFSOut(0), IndentLevel(0) {}
157  virtual ~DbgScope();
158
159  // Accessors.
160  DbgScope *getParent()          const { return Parent; }
161  void setParent(DbgScope *P)          { Parent = P; }
162  DIDescriptor getDesc()         const { return Desc; }
163  const MDNode *getInlinedAt()         const { return InlinedAtLocation; }
164  const MDNode *getScopeNode()         const { return Desc; }
165  const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
166  const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
167  const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
168
169  /// openInsnRange - This scope covers instruction range starting from MI.
170  void openInsnRange(const MachineInstr *MI) {
171    if (!FirstInsn)
172      FirstInsn = MI;
173
174    if (Parent)
175      Parent->openInsnRange(MI);
176  }
177
178  /// extendInsnRange - Extend the current instruction range covered by
179  /// this scope.
180  void extendInsnRange(const MachineInstr *MI) {
181    assert (FirstInsn && "MI Range is not open!");
182    LastInsn = MI;
183    if (Parent)
184      Parent->extendInsnRange(MI);
185  }
186
187  /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
188  /// until now. This is used when a new scope is encountered while walking
189  /// machine instructions.
190  void closeInsnRange(DbgScope *NewScope = NULL) {
191    assert (LastInsn && "Last insn missing!");
192    Ranges.push_back(DbgRange(FirstInsn, LastInsn));
193    FirstInsn = NULL;
194    LastInsn = NULL;
195    // If Parent dominates NewScope then do not close Parent's instruction
196    // range.
197    if (Parent && (!NewScope || !Parent->dominates(NewScope)))
198      Parent->closeInsnRange(NewScope);
199  }
200
201  void setAbstractScope() { AbstractScope = true; }
202  bool isAbstractScope() const { return AbstractScope; }
203
204  // Depth First Search support to walk and mainpluate DbgScope hierarchy.
205  unsigned getDFSOut() const { return DFSOut; }
206  void setDFSOut(unsigned O) { DFSOut = O; }
207  unsigned getDFSIn() const  { return DFSIn; }
208  void setDFSIn(unsigned I)  { DFSIn = I; }
209  bool dominates(const DbgScope *S) {
210    if (S == this)
211      return true;
212    if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
213      return true;
214    return false;
215  }
216
217  /// addScope - Add a scope to the scope.
218  ///
219  void addScope(DbgScope *S) { Scopes.push_back(S); }
220
221  /// addVariable - Add a variable to the scope.
222  ///
223  void addVariable(DbgVariable *V) { Variables.push_back(V); }
224
225#ifndef NDEBUG
226  void dump() const;
227#endif
228};
229
230} // end llvm namespace
231
232#ifndef NDEBUG
233void DbgScope::dump() const {
234  raw_ostream &err = dbgs();
235  err.indent(IndentLevel);
236  const MDNode *N = Desc;
237  N->dump();
238  if (AbstractScope)
239    err << "Abstract Scope\n";
240
241  IndentLevel += 2;
242  if (!Scopes.empty())
243    err << "Children ...\n";
244  for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
245    if (Scopes[i] != this)
246      Scopes[i]->dump();
247
248  IndentLevel -= 2;
249}
250#endif
251
252DbgScope::~DbgScope() {
253  for (unsigned j = 0, M = Variables.size(); j < M; ++j)
254    delete Variables[j];
255}
256
257DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
258  : Asm(A), MMI(Asm->MMI), FirstCU(0),
259    AbbreviationsSet(InitAbbreviationsSetSize),
260    CurrentFnDbgScope(0), PrevLabel(NULL) {
261  NextStringPoolNumber = 0;
262
263  DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
264  DwarfStrSectionSym = TextSectionSym = 0;
265  DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
266  FunctionBeginSym = FunctionEndSym = 0;
267  {
268    NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
269    beginModule(M);
270  }
271}
272DwarfDebug::~DwarfDebug() {
273}
274
275MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
276  std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
277  if (Entry.first) return Entry.first;
278
279  Entry.second = NextStringPoolNumber++;
280  return Entry.first = Asm->GetTempSymbol("string", Entry.second);
281}
282
283
284/// assignAbbrevNumber - Define a unique number for the abbreviation.
285///
286void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
287  // Profile the node so that we can make it unique.
288  FoldingSetNodeID ID;
289  Abbrev.Profile(ID);
290
291  // Check the set for priors.
292  DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
293
294  // If it's newly added.
295  if (InSet == &Abbrev) {
296    // Add to abbreviation list.
297    Abbreviations.push_back(&Abbrev);
298
299    // Assign the vector position + 1 as its number.
300    Abbrev.setNumber(Abbreviations.size());
301  } else {
302    // Assign existing abbreviation number.
303    Abbrev.setNumber(InSet->getNumber());
304  }
305}
306
307/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
308/// printer to not emit usual symbol prefix before the symbol name is used then
309/// return linkage name after skipping this special LLVM prefix.
310static StringRef getRealLinkageName(StringRef LinkageName) {
311  char One = '\1';
312  if (LinkageName.startswith(StringRef(&One, 1)))
313    return LinkageName.substr(1);
314  return LinkageName;
315}
316
317/// createSubprogramDIE - Create new DIE using SP.
318DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
319  CompileUnit *SPCU = getCompileUnit(SP);
320  DIE *SPDie = SPCU->getDIE(SP);
321  if (SPDie)
322    return SPDie;
323
324  SPDie = new DIE(dwarf::DW_TAG_subprogram);
325
326  // DW_TAG_inlined_subroutine may refer to this DIE.
327  SPCU->insertDIE(SP, SPDie);
328
329  // Add to context owner.
330  SPCU->addToContextOwner(SPDie, SP.getContext());
331
332  // Add function template parameters.
333  SPCU->addTemplateParams(*SPDie, SP.getTemplateParams());
334
335  // If this DIE is going to refer declaration info using AT_specification
336  // then there is no need to add other attributes.
337  if (SP.getFunctionDeclaration().isSubprogram())
338    return SPDie;
339
340  // Constructors and operators for anonymous aggregates do not have names.
341  if (!SP.getName().empty())
342    SPCU->addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
343                    SP.getName());
344
345  StringRef LinkageName = SP.getLinkageName();
346  if (!LinkageName.empty())
347    SPCU->addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
348                    getRealLinkageName(LinkageName));
349
350  SPCU->addSourceLine(SPDie, SP);
351
352  if (SP.isPrototyped())
353    SPCU->addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
354
355  // Add Return Type.
356  DICompositeType SPTy = SP.getType();
357  DIArray Args = SPTy.getTypeArray();
358  unsigned SPTag = SPTy.getTag();
359
360  if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
361    SPCU->addType(SPDie, SPTy);
362  else
363    SPCU->addType(SPDie, DIType(Args.getElement(0)));
364
365  unsigned VK = SP.getVirtuality();
366  if (VK) {
367    SPCU->addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
368    DIEBlock *Block = SPCU->getDIEBlock();
369    SPCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
370    SPCU->addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
371    SPCU->addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
372    ContainingTypeMap.insert(std::make_pair(SPDie,
373                                            SP.getContainingType()));
374  }
375
376  if (!SP.isDefinition()) {
377    SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
378
379    // Add arguments. Do not add arguments for subprogram definition. They will
380    // be handled while processing variables.
381    DICompositeType SPTy = SP.getType();
382    DIArray Args = SPTy.getTypeArray();
383    unsigned SPTag = SPTy.getTag();
384
385    if (SPTag == dwarf::DW_TAG_subroutine_type)
386      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
387        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
388        DIType ATy = DIType(DIType(Args.getElement(i)));
389        SPCU->addType(Arg, ATy);
390        if (ATy.isArtificial())
391          SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
392        SPDie->addChild(Arg);
393      }
394  }
395
396  if (SP.isArtificial())
397    SPCU->addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
398
399  if (!SP.isLocalToUnit())
400    SPCU->addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
401
402  if (SP.isOptimized())
403    SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
404
405  if (unsigned isa = Asm->getISAEncoding()) {
406    SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
407  }
408
409  return SPDie;
410}
411
412DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
413  assert(N && "Invalid Scope encoding!");
414
415  DbgScope *AScope = AbstractScopes.lookup(N);
416  if (AScope)
417    return AScope;
418
419  DbgScope *Parent = NULL;
420
421  DIDescriptor Scope(N);
422  if (Scope.isLexicalBlock()) {
423    DILexicalBlock DB(N);
424    DIDescriptor ParentDesc = DB.getContext();
425    Parent = getOrCreateAbstractScope(ParentDesc);
426  }
427
428  AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
429
430  if (Parent)
431    Parent->addScope(AScope);
432  AScope->setAbstractScope();
433  AbstractScopes[N] = AScope;
434  if (DIDescriptor(N).isSubprogram())
435    AbstractScopesList.push_back(AScope);
436  return AScope;
437}
438
439/// isSubprogramContext - Return true if Context is either a subprogram
440/// or another context nested inside a subprogram.
441static bool isSubprogramContext(const MDNode *Context) {
442  if (!Context)
443    return false;
444  DIDescriptor D(Context);
445  if (D.isSubprogram())
446    return true;
447  if (D.isType())
448    return isSubprogramContext(DIType(Context).getContext());
449  return false;
450}
451
452/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
453/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
454/// If there are global variables in this scope then create and insert
455/// DIEs for these variables.
456DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
457  CompileUnit *SPCU = getCompileUnit(SPNode);
458  DIE *SPDie = SPCU->getDIE(SPNode);
459
460  assert(SPDie && "Unable to find subprogram DIE!");
461  DISubprogram SP(SPNode);
462
463  DISubprogram SPDecl = SP.getFunctionDeclaration();
464  if (SPDecl.isSubprogram())
465    // Refer function declaration directly.
466    SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
467                      createSubprogramDIE(SPDecl));
468  else {
469    // There is not any need to generate specification DIE for a function
470    // defined at compile unit level. If a function is defined inside another
471    // function then gdb prefers the definition at top level and but does not
472    // expect specification DIE in parent function. So avoid creating
473    // specification DIE for a function defined inside a function.
474    if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
475        !SP.getContext().isFile() &&
476        !isSubprogramContext(SP.getContext())) {
477      SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
478
479      // Add arguments.
480      DICompositeType SPTy = SP.getType();
481      DIArray Args = SPTy.getTypeArray();
482      unsigned SPTag = SPTy.getTag();
483      if (SPTag == dwarf::DW_TAG_subroutine_type)
484        for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
485          DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
486          DIType ATy = DIType(DIType(Args.getElement(i)));
487          SPCU->addType(Arg, ATy);
488          if (ATy.isArtificial())
489            SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
490          SPDie->addChild(Arg);
491        }
492      DIE *SPDeclDie = SPDie;
493      SPDie = new DIE(dwarf::DW_TAG_subprogram);
494      SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
495                        SPDeclDie);
496      SPCU->addDie(SPDie);
497    }
498  }
499  // Pick up abstract subprogram DIE.
500  if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
501    SPDie = new DIE(dwarf::DW_TAG_subprogram);
502    SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
503                      dwarf::DW_FORM_ref4, AbsSPDIE);
504    SPCU->addDie(SPDie);
505  }
506
507  SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
508                 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
509  SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
510                 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
511  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
512  MachineLocation Location(RI->getFrameRegister(*Asm->MF));
513  SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
514
515  return SPDie;
516}
517
518/// constructLexicalScope - Construct new DW_TAG_lexical_block
519/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
520DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
521
522  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
523  if (Scope->isAbstractScope())
524    return ScopeDIE;
525
526  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
527  if (Ranges.empty())
528    return 0;
529
530  CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode());
531  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
532  if (Ranges.size() > 1) {
533    // .debug_range section has not been laid out yet. Emit offset in
534    // .debug_range as a uint, size 4, for now. emitDIE will handle
535    // DW_AT_ranges appropriately.
536    TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
537                   DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
538    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
539         RE = Ranges.end(); RI != RE; ++RI) {
540      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
541      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
542    }
543    DebugRangeSymbols.push_back(NULL);
544    DebugRangeSymbols.push_back(NULL);
545    return ScopeDIE;
546  }
547
548  const MCSymbol *Start = getLabelBeforeInsn(RI->first);
549  const MCSymbol *End = getLabelAfterInsn(RI->second);
550
551  if (End == 0) return 0;
552
553  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
554  assert(End->isDefined() && "Invalid end label for an inlined scope!");
555
556  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
557  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
558
559  return ScopeDIE;
560}
561
562/// constructInlinedScopeDIE - This scope represents inlined body of
563/// a function. Construct DIE to represent this concrete inlined copy
564/// of the function.
565DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
566
567  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
568  assert (Ranges.empty() == false
569          && "DbgScope does not have instruction markers!");
570
571  // FIXME : .debug_inlined section specification does not clearly state how
572  // to emit inlined scope that is split into multiple instruction ranges.
573  // For now, use first instruction range and emit low_pc/high_pc pair and
574  // corresponding .debug_inlined section entry for this pair.
575  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
576  const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
577  const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
578
579  if (StartLabel == 0 || EndLabel == 0) {
580    assert (0 && "Unexpected Start and End  labels for a inlined scope!");
581    return 0;
582  }
583  assert(StartLabel->isDefined() &&
584         "Invalid starting label for an inlined scope!");
585  assert(EndLabel->isDefined() &&
586         "Invalid end label for an inlined scope!");
587
588  if (!Scope->getScopeNode())
589    return NULL;
590  DIScope DS(Scope->getScopeNode());
591  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
592
593  DISubprogram InlinedSP = getDISubprogram(DS);
594  CompileUnit *TheCU = getCompileUnit(InlinedSP);
595  DIE *OriginDIE = TheCU->getDIE(InlinedSP);
596  assert(OriginDIE && "Unable to find Origin DIE!");
597  TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
598                     dwarf::DW_FORM_ref4, OriginDIE);
599
600  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
601  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
602
603  InlinedSubprogramDIEs.insert(OriginDIE);
604
605  // Track the start label for this inlined function.
606  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
607    I = InlineInfo.find(InlinedSP);
608
609  if (I == InlineInfo.end()) {
610    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
611                                                             ScopeDIE));
612    InlinedSPNodes.push_back(InlinedSP);
613  } else
614    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
615
616  DILocation DL(Scope->getInlinedAt());
617  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
618  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
619
620  return ScopeDIE;
621}
622
623
624/// constructVariableDIE - Construct a DIE for the given DbgVariable.
625DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
626  StringRef Name = DV->getName();
627  if (Name.empty())
628    return NULL;
629
630  // Translate tag to proper Dwarf tag.  The result variable is dropped for
631  // now.
632  unsigned Tag;
633  switch (DV->getTag()) {
634  case dwarf::DW_TAG_return_variable:
635    return NULL;
636  case dwarf::DW_TAG_arg_variable:
637    Tag = dwarf::DW_TAG_formal_parameter;
638    break;
639  case dwarf::DW_TAG_auto_variable:    // fall thru
640  default:
641    Tag = dwarf::DW_TAG_variable;
642    break;
643  }
644
645  // Define variable debug information entry.
646  DIE *VariableDie = new DIE(Tag);
647  CompileUnit *VariableCU = getCompileUnit(DV->getVariable());
648  DIE *AbsDIE = NULL;
649  DenseMap<const DbgVariable *, const DbgVariable *>::iterator
650    V2AVI = VarToAbstractVarMap.find(DV);
651  if (V2AVI != VarToAbstractVarMap.end())
652    AbsDIE = V2AVI->second->getDIE();
653
654  if (AbsDIE)
655    VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
656                       dwarf::DW_FORM_ref4, AbsDIE);
657  else {
658    VariableCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
659                          Name);
660    VariableCU->addSourceLine(VariableDie, DV->getVariable());
661
662    // Add variable type.
663    VariableCU->addType(VariableDie, DV->getType());
664  }
665
666  if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
667    VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
668                        dwarf::DW_FORM_flag, 1);
669  else if (DIVariable(DV->getVariable()).isArtificial())
670    VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
671                        dwarf::DW_FORM_flag, 1);
672
673  if (Scope->isAbstractScope()) {
674    DV->setDIE(VariableDie);
675    return VariableDie;
676  }
677
678  // Add variable address.
679
680  unsigned Offset = DV->getDotDebugLocOffset();
681  if (Offset != ~0U) {
682    VariableCU->addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
683             Asm->GetTempSymbol("debug_loc", Offset));
684    DV->setDIE(VariableDie);
685    UseDotDebugLocEntry.insert(VariableDie);
686    return VariableDie;
687  }
688
689  // Check if variable is described by a  DBG_VALUE instruction.
690  DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
691    DbgVariableToDbgInstMap.find(DV);
692  if (DVI != DbgVariableToDbgInstMap.end()) {
693    const MachineInstr *DVInsn = DVI->second;
694    bool updated = false;
695    // FIXME : Handle getNumOperands != 3
696    if (DVInsn->getNumOperands() == 3) {
697      if (DVInsn->getOperand(0).isReg()) {
698        const MachineOperand RegOp = DVInsn->getOperand(0);
699        const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
700        if (DVInsn->getOperand(1).isImm() &&
701            TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
702          unsigned FrameReg = 0;
703          const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
704          int Offset =
705            TFI->getFrameIndexReference(*Asm->MF,
706                                        DVInsn->getOperand(1).getImm(),
707                                        FrameReg);
708          MachineLocation Location(FrameReg, Offset);
709          VariableCU->addVariableAddress(DV, VariableDie, Location);
710
711        } else if (RegOp.getReg())
712          VariableCU->addVariableAddress(DV, VariableDie,
713                                         MachineLocation(RegOp.getReg()));
714        updated = true;
715      }
716      else if (DVInsn->getOperand(0).isImm())
717        updated = VariableCU->addConstantValue(VariableDie,
718                                               DVInsn->getOperand(0));
719      else if (DVInsn->getOperand(0).isFPImm())
720        updated =
721          VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
722    } else {
723      VariableCU->addVariableAddress(DV, VariableDie,
724                                     Asm->getDebugValueLocation(DVInsn));
725      updated = true;
726    }
727    if (!updated) {
728      // If variableDie is not updated then DBG_VALUE instruction does not
729      // have valid variable info.
730      delete VariableDie;
731      return NULL;
732    }
733    DV->setDIE(VariableDie);
734    return VariableDie;
735  }
736
737  // .. else use frame index, if available.
738  int FI = 0;
739  if (findVariableFrameIndex(DV, &FI)) {
740    unsigned FrameReg = 0;
741    const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
742    int Offset =
743      TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
744    MachineLocation Location(FrameReg, Offset);
745    VariableCU->addVariableAddress(DV, VariableDie, Location);
746  }
747
748  DV->setDIE(VariableDie);
749  return VariableDie;
750
751}
752
753void CompileUnit::addPubTypes(DISubprogram SP) {
754  DICompositeType SPTy = SP.getType();
755  unsigned SPTag = SPTy.getTag();
756  if (SPTag != dwarf::DW_TAG_subroutine_type)
757    return;
758
759  DIArray Args = SPTy.getTypeArray();
760  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
761    DIType ATy(Args.getElement(i));
762    if (!ATy.Verify())
763      continue;
764    DICompositeType CATy = getDICompositeType(ATy);
765    if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
766        && !CATy.isForwardDecl()) {
767      if (DIEEntry *Entry = getDIEEntry(CATy))
768        addGlobalType(CATy.getName(), Entry->getEntry());
769    }
770  }
771}
772
773/// constructScopeDIE - Construct a DIE for this scope.
774DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
775  if (!Scope || !Scope->getScopeNode())
776    return NULL;
777
778  SmallVector <DIE *, 8> Children;
779
780  // Collect arguments for current function.
781  if (Scope == CurrentFnDbgScope)
782    for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
783      if (DbgVariable *ArgDV = CurrentFnArguments[i])
784        if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
785          Children.push_back(Arg);
786
787  // Collect lexical scope childrens first.
788  const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
789  for (unsigned i = 0, N = Variables.size(); i < N; ++i)
790    if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
791      Children.push_back(Variable);
792  const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
793  for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
794    if (DIE *Nested = constructScopeDIE(Scopes[j]))
795      Children.push_back(Nested);
796  DIScope DS(Scope->getScopeNode());
797  DIE *ScopeDIE = NULL;
798  if (Scope->getInlinedAt())
799    ScopeDIE = constructInlinedScopeDIE(Scope);
800  else if (DS.isSubprogram()) {
801    ProcessedSPNodes.insert(DS);
802    if (Scope->isAbstractScope()) {
803      ScopeDIE = getCompileUnit(DS)->getDIE(DS);
804      // Note down abstract DIE.
805      if (ScopeDIE)
806        AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
807    }
808    else
809      ScopeDIE = updateSubprogramScopeDIE(DS);
810  }
811  else {
812    // There is no need to emit empty lexical block DIE.
813    if (Children.empty())
814      return NULL;
815    ScopeDIE = constructLexicalScopeDIE(Scope);
816  }
817
818  if (!ScopeDIE) return NULL;
819
820  // Add children
821  for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
822         E = Children.end(); I != E; ++I)
823    ScopeDIE->addChild(*I);
824
825  if (DS.isSubprogram())
826    getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
827
828 return ScopeDIE;
829}
830
831/// GetOrCreateSourceID - Look up the source id with the given directory and
832/// source file names. If none currently exists, create a new id and insert it
833/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
834/// maps as well.
835
836unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
837                                         StringRef DirName) {
838  // If FE did not provide a file name, then assume stdin.
839  if (FileName.empty())
840    return GetOrCreateSourceID("<stdin>", StringRef());
841
842  // MCStream expects full path name as filename.
843  if (!DirName.empty() && !FileName.startswith("/")) {
844    std::string FullPathName(DirName.data());
845    if (!DirName.endswith("/"))
846      FullPathName += "/";
847    FullPathName += FileName.data();
848    // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
849    return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
850  }
851
852  StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
853  if (Entry.getValue())
854    return Entry.getValue();
855
856  unsigned SrcId = SourceIdMap.size();
857  Entry.setValue(SrcId);
858
859  // Print out a .file directive to specify files for .loc directives.
860  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
861
862  return SrcId;
863}
864
865/// getOrCreateNameSpace - Create a DIE for DINameSpace.
866DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
867  DIE *NDie = getDIE(NS);
868  if (NDie)
869    return NDie;
870  NDie = new DIE(dwarf::DW_TAG_namespace);
871  insertDIE(NS, NDie);
872  if (!NS.getName().empty())
873    addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
874  addSourceLine(NDie, NS);
875  addToContextOwner(NDie, NS.getContext());
876  return NDie;
877}
878
879/// constructCompileUnit - Create new CompileUnit for the given
880/// metadata node with tag DW_TAG_compile_unit.
881void DwarfDebug::constructCompileUnit(const MDNode *N) {
882  DICompileUnit DIUnit(N);
883  StringRef FN = DIUnit.getFilename();
884  StringRef Dir = DIUnit.getDirectory();
885  unsigned ID = GetOrCreateSourceID(FN, Dir);
886
887  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
888  CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
889  NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
890                   DIUnit.getProducer());
891  NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
892                 DIUnit.getLanguage());
893  NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
894  // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
895  // simplifies debug range entries.
896  NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
897  // DW_AT_stmt_list is a offset of line number information for this
898  // compile unit in debug_line section.
899  if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
900    NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
901                    Asm->GetTempSymbol("section_line"));
902  else
903    NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
904
905  if (!Dir.empty())
906    NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
907  if (DIUnit.isOptimized())
908    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
909
910  StringRef Flags = DIUnit.getFlags();
911  if (!Flags.empty())
912    NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
913
914  unsigned RVer = DIUnit.getRunTimeVersion();
915  if (RVer)
916    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
917            dwarf::DW_FORM_data1, RVer);
918
919  if (!FirstCU)
920    FirstCU = NewCU;
921  CUMap.insert(std::make_pair(N, NewCU));
922}
923
924/// getCompielUnit - Get CompileUnit DIE.
925CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
926  assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
927  DIDescriptor D(N);
928  const MDNode *CUNode = NULL;
929  if (D.isCompileUnit())
930    CUNode = N;
931  else if (D.isSubprogram())
932    CUNode = DISubprogram(N).getCompileUnit();
933  else if (D.isType())
934    CUNode = DIType(N).getCompileUnit();
935  else if (D.isGlobalVariable())
936    CUNode = DIGlobalVariable(N).getCompileUnit();
937  else if (D.isVariable())
938    CUNode = DIVariable(N).getCompileUnit();
939  else if (D.isNameSpace())
940    CUNode = DINameSpace(N).getCompileUnit();
941  else if (D.isFile())
942    CUNode = DIFile(N).getCompileUnit();
943  else
944    return FirstCU;
945
946  DenseMap<const MDNode *, CompileUnit *>::const_iterator I
947    = CUMap.find(CUNode);
948  if (I == CUMap.end())
949    return FirstCU;
950  return I->second;
951}
952
953/// isUnsignedDIType - Return true if type encoding is unsigned.
954static bool isUnsignedDIType(DIType Ty) {
955  DIDerivedType DTy(Ty);
956  if (DTy.Verify())
957    return isUnsignedDIType(DTy.getTypeDerivedFrom());
958
959  DIBasicType BTy(Ty);
960  if (BTy.Verify()) {
961    unsigned Encoding = BTy.getEncoding();
962    if (Encoding == dwarf::DW_ATE_unsigned ||
963        Encoding == dwarf::DW_ATE_unsigned_char)
964      return true;
965  }
966  return false;
967}
968
969// Return const exprssion if value is a GEP to access merged global
970// constant. e.g.
971// i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
972static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
973  const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
974  if (!CE || CE->getNumOperands() != 3 ||
975      CE->getOpcode() != Instruction::GetElementPtr)
976    return NULL;
977
978  // First operand points to a global value.
979  if (!isa<GlobalValue>(CE->getOperand(0)))
980    return NULL;
981
982  // Second operand is zero.
983  const ConstantInt *CI =
984    dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
985  if (!CI || !CI->isZero())
986    return NULL;
987
988  // Third operand is offset.
989  if (!isa<ConstantInt>(CE->getOperand(2)))
990    return NULL;
991
992  return CE;
993}
994
995/// constructGlobalVariableDIE - Construct global variable DIE.
996void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
997  DIGlobalVariable GV(N);
998
999  // If debug information is malformed then ignore it.
1000  if (GV.Verify() == false)
1001    return;
1002
1003  // Check for pre-existence.
1004  CompileUnit *TheCU = getCompileUnit(N);
1005  if (TheCU->getDIE(GV))
1006    return;
1007
1008  DIType GTy = GV.getType();
1009  DIE *VariableDIE = new DIE(GV.getTag());
1010
1011  bool isGlobalVariable = GV.getGlobal() != NULL;
1012
1013  // Add name.
1014  TheCU->addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1015                   GV.getDisplayName());
1016  StringRef LinkageName = GV.getLinkageName();
1017  if (!LinkageName.empty() && isGlobalVariable)
1018    TheCU->addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1019                     dwarf::DW_FORM_string,
1020                     getRealLinkageName(LinkageName));
1021  // Add type.
1022  TheCU->addType(VariableDIE, GTy);
1023  if (GTy.isCompositeType() && !GTy.getName().empty()
1024      && !GTy.isForwardDecl()) {
1025    DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1026    assert(Entry && "Missing global type!");
1027    TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1028  }
1029  // Add scoping info.
1030  if (!GV.isLocalToUnit()) {
1031    TheCU->addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1032    // Expose as global.
1033    TheCU->addGlobal(GV.getName(), VariableDIE);
1034  }
1035  // Add line number info.
1036  TheCU->addSourceLine(VariableDIE, GV);
1037  // Add to map.
1038  TheCU->insertDIE(N, VariableDIE);
1039  // Add to context owner.
1040  DIDescriptor GVContext = GV.getContext();
1041  TheCU->addToContextOwner(VariableDIE, GVContext);
1042  // Add location.
1043  if (isGlobalVariable) {
1044    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1045    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1046    TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1047             Asm->Mang->getSymbol(GV.getGlobal()));
1048    // Do not create specification DIE if context is either compile unit
1049    // or a subprogram.
1050    if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1051        !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1052      // Create specification DIE.
1053      DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1054      TheCU->addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1055                  dwarf::DW_FORM_ref4, VariableDIE);
1056      TheCU->addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1057      TheCU->addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1058      TheCU->addDie(VariableSpecDIE);
1059    } else {
1060      TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1061    }
1062  } else if (ConstantInt *CI =
1063             dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1064    TheCU->addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy));
1065  else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1066    // GV is a merged global.
1067    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1068    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1069    TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1070                    Asm->Mang->getSymbol(cast<GlobalValue>(CE->getOperand(0))));
1071    ConstantInt *CII = cast<ConstantInt>(CE->getOperand(2));
1072    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1073    TheCU->addUInt(Block, 0, dwarf::DW_FORM_udata, CII->getZExtValue());
1074    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1075    TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1076  }
1077
1078  return;
1079}
1080
1081/// construct SubprogramDIE - Construct subprogram DIE.
1082void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1083  DISubprogram SP(N);
1084
1085  // Check for pre-existence.
1086  CompileUnit *TheCU = getCompileUnit(N);
1087  if (TheCU->getDIE(N))
1088    return;
1089
1090  if (!SP.isDefinition())
1091    // This is a method declaration which will be handled while constructing
1092    // class type.
1093    return;
1094
1095  DIE *SubprogramDie = createSubprogramDIE(SP);
1096
1097  // Add to map.
1098  TheCU->insertDIE(N, SubprogramDie);
1099
1100  // Add to context owner.
1101  TheCU->addToContextOwner(SubprogramDie, SP.getContext());
1102
1103  // Expose as global.
1104  TheCU->addGlobal(SP.getName(), SubprogramDie);
1105
1106  return;
1107}
1108
1109/// beginModule - Emit all Dwarf sections that should come prior to the
1110/// content. Create global DIEs and emit initial debug info sections.
1111/// This is inovked by the target AsmPrinter.
1112void DwarfDebug::beginModule(Module *M) {
1113  if (DisableDebugInfoPrinting)
1114    return;
1115
1116  DebugInfoFinder DbgFinder;
1117  DbgFinder.processModule(*M);
1118
1119  bool HasDebugInfo = false;
1120
1121  // Scan all the compile-units to see if there are any marked as the main unit.
1122  // if not, we do not generate debug info.
1123  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1124       E = DbgFinder.compile_unit_end(); I != E; ++I) {
1125    if (DICompileUnit(*I).isMain()) {
1126      HasDebugInfo = true;
1127      break;
1128    }
1129  }
1130
1131  if (!HasDebugInfo) return;
1132
1133  // Tell MMI that we have debug info.
1134  MMI->setDebugInfoAvailability(true);
1135
1136  // Emit initial sections.
1137  EmitSectionLabels();
1138
1139  // Create all the compile unit DIEs.
1140  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1141         E = DbgFinder.compile_unit_end(); I != E; ++I)
1142    constructCompileUnit(*I);
1143
1144  // Create DIEs for each subprogram.
1145  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1146         E = DbgFinder.subprogram_end(); I != E; ++I)
1147    constructSubprogramDIE(*I);
1148
1149  // Create DIEs for each global variable.
1150  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1151         E = DbgFinder.global_variable_end(); I != E; ++I)
1152    constructGlobalVariableDIE(*I);
1153
1154  //getOrCreateTypeDIE
1155  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
1156    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1157      DIType Ty(NMD->getOperand(i));
1158      getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1159    }
1160
1161  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
1162    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1163      DIType Ty(NMD->getOperand(i));
1164      getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1165    }
1166
1167  // Prime section data.
1168  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1169}
1170
1171/// endModule - Emit all Dwarf sections that should come after the content.
1172///
1173void DwarfDebug::endModule() {
1174  if (!FirstCU) return;
1175  const Module *M = MMI->getModule();
1176  DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
1177  if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
1178    for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
1179      if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
1180      DISubprogram SP(AllSPs->getOperand(SI));
1181      if (!SP.Verify()) continue;
1182
1183      // Collect info for variables that were optimized out.
1184      if (!SP.isDefinition()) continue;
1185      StringRef FName = SP.getLinkageName();
1186      if (FName.empty())
1187        FName = SP.getName();
1188      NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
1189      if (!NMD) continue;
1190      unsigned E = NMD->getNumOperands();
1191      if (!E) continue;
1192      DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
1193      DeadFnScopeMap[SP] = Scope;
1194      for (unsigned I = 0; I != E; ++I) {
1195        DIVariable DV(NMD->getOperand(I));
1196        if (!DV.Verify()) continue;
1197        Scope->addVariable(new DbgVariable(DV));
1198      }
1199
1200      // Construct subprogram DIE and add variables DIEs.
1201      constructSubprogramDIE(SP);
1202      DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
1203      const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1204      for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1205        DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1206        if (VariableDIE)
1207          ScopeDIE->addChild(VariableDIE);
1208      }
1209    }
1210  }
1211
1212  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1213  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1214         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1215    DIE *ISP = *AI;
1216    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1217  }
1218
1219  for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1220         CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1221    DIE *SPDie = CI->first;
1222    const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1223    if (!N) continue;
1224    DIE *NDie = getCompileUnit(N)->getDIE(N);
1225    if (!NDie) continue;
1226    getCompileUnit(N)->addDIEEntry(SPDie, dwarf::DW_AT_containing_type,
1227                                   dwarf::DW_FORM_ref4, NDie);
1228  }
1229
1230  // Standard sections final addresses.
1231  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1232  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1233  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1234  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1235
1236  // End text sections.
1237  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1238    Asm->OutStreamer.SwitchSection(SectionMap[i]);
1239    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1240  }
1241
1242  // Emit common frame information.
1243  emitCommonDebugFrame();
1244
1245  // Emit function debug frame information
1246  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1247         E = DebugFrames.end(); I != E; ++I)
1248    emitFunctionDebugFrame(*I);
1249
1250  // Compute DIE offsets and sizes.
1251  computeSizeAndOffsets();
1252
1253  // Emit all the DIEs into a debug info section
1254  emitDebugInfo();
1255
1256  // Corresponding abbreviations into a abbrev section.
1257  emitAbbreviations();
1258
1259  // Emit info into a debug pubnames section.
1260  emitDebugPubNames();
1261
1262  // Emit info into a debug pubtypes section.
1263  emitDebugPubTypes();
1264
1265  // Emit info into a debug loc section.
1266  emitDebugLoc();
1267
1268  // Emit info into a debug aranges section.
1269  EmitDebugARanges();
1270
1271  // Emit info into a debug ranges section.
1272  emitDebugRanges();
1273
1274  // Emit info into a debug macinfo section.
1275  emitDebugMacInfo();
1276
1277  // Emit inline info.
1278  emitDebugInlineInfo();
1279
1280  // Emit info into a debug str section.
1281  emitDebugStr();
1282
1283  // clean up.
1284  DeleteContainerSeconds(DeadFnScopeMap);
1285  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1286         E = CUMap.end(); I != E; ++I)
1287    delete I->second;
1288  FirstCU = NULL;  // Reset for the next Module, if any.
1289}
1290
1291/// findAbstractVariable - Find abstract variable, if any, associated with Var.
1292DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1293                                              DebugLoc ScopeLoc) {
1294
1295  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1296  if (AbsDbgVariable)
1297    return AbsDbgVariable;
1298
1299  LLVMContext &Ctx = Var->getContext();
1300  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
1301  if (!Scope)
1302    return NULL;
1303
1304  AbsDbgVariable = new DbgVariable(Var);
1305  Scope->addVariable(AbsDbgVariable);
1306  AbstractVariables[Var] = AbsDbgVariable;
1307  return AbsDbgVariable;
1308}
1309
1310/// addCurrentFnArgument - If Var is an current function argument that add
1311/// it in CurrentFnArguments list.
1312bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1313                                      DbgVariable *Var, DbgScope *Scope) {
1314  if (Scope != CurrentFnDbgScope)
1315    return false;
1316  DIVariable DV = Var->getVariable();
1317  if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1318    return false;
1319  unsigned ArgNo = DV.getArgNumber();
1320  if (ArgNo == 0)
1321    return false;
1322
1323  size_t Size = CurrentFnArguments.size();
1324  if (Size == 0)
1325    CurrentFnArguments.resize(MF->getFunction()->arg_size());
1326  // llvm::Function argument size is not good indicator of how many
1327  // arguments does the function have at source level.
1328  if (ArgNo > Size)
1329    CurrentFnArguments.resize(ArgNo * 2);
1330  CurrentFnArguments[ArgNo - 1] = Var;
1331  return true;
1332}
1333
1334/// collectVariableInfoFromMMITable - Collect variable information from
1335/// side table maintained by MMI.
1336void
1337DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
1338                                   SmallPtrSet<const MDNode *, 16> &Processed) {
1339  const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1340  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1341  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1342         VE = VMap.end(); VI != VE; ++VI) {
1343    const MDNode *Var = VI->first;
1344    if (!Var) continue;
1345    Processed.insert(Var);
1346    DIVariable DV(Var);
1347    const std::pair<unsigned, DebugLoc> &VP = VI->second;
1348
1349    DbgScope *Scope = 0;
1350    if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
1351      Scope = ConcreteScopes.lookup(IA);
1352    if (Scope == 0)
1353      Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
1354
1355    // If variable scope is not found then skip this variable.
1356    if (Scope == 0)
1357      continue;
1358
1359    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1360    DbgVariable *RegVar = new DbgVariable(DV);
1361    recordVariableFrameIndex(RegVar, VP.first);
1362    if (!addCurrentFnArgument(MF, RegVar, Scope))
1363      Scope->addVariable(RegVar);
1364    if (AbsDbgVariable) {
1365      recordVariableFrameIndex(AbsDbgVariable, VP.first);
1366      VarToAbstractVarMap[RegVar] = AbsDbgVariable;
1367    }
1368  }
1369}
1370
1371/// isDbgValueInDefinedReg - Return true if debug value, encoded by
1372/// DBG_VALUE instruction, is in a defined reg.
1373static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1374  assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1375  return MI->getNumOperands() == 3 &&
1376         MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1377         MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1378}
1379
1380/// collectVariableInfo - Populate DbgScope entries with variables' info.
1381void
1382DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1383                                SmallPtrSet<const MDNode *, 16> &Processed) {
1384
1385  /// collection info from MMI table.
1386  collectVariableInfoFromMMITable(MF, Processed);
1387
1388  for (SmallVectorImpl<const MDNode*>::const_iterator
1389         UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1390         ++UVI) {
1391    const MDNode *Var = *UVI;
1392    if (Processed.count(Var))
1393      continue;
1394
1395    // History contains relevant DBG_VALUE instructions for Var and instructions
1396    // clobbering it.
1397    SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1398    if (History.empty())
1399      continue;
1400    const MachineInstr *MInsn = History.front();
1401
1402    DIVariable DV(Var);
1403    DbgScope *Scope = NULL;
1404    if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1405        DISubprogram(DV.getContext()).describes(MF->getFunction()))
1406      Scope = CurrentFnDbgScope;
1407    else
1408      Scope = findDbgScope(MInsn);
1409    // If variable scope is not found then skip this variable.
1410    if (!Scope)
1411      continue;
1412
1413    Processed.insert(DV);
1414    assert(MInsn->isDebugValue() && "History must begin with debug value");
1415    DbgVariable *RegVar = new DbgVariable(DV);
1416    if (!addCurrentFnArgument(MF, RegVar, Scope))
1417      Scope->addVariable(RegVar);
1418    if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1419      DbgVariableToDbgInstMap[AbsVar] = MInsn;
1420      VarToAbstractVarMap[RegVar] = AbsVar;
1421    }
1422
1423    // Simple ranges that are fully coalesced.
1424    if (History.size() <= 1 || (History.size() == 2 &&
1425                                MInsn->isIdenticalTo(History.back()))) {
1426      DbgVariableToDbgInstMap[RegVar] = MInsn;
1427      continue;
1428    }
1429
1430    // handle multiple DBG_VALUE instructions describing one variable.
1431    RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1432
1433    for (SmallVectorImpl<const MachineInstr*>::const_iterator
1434           HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1435      const MachineInstr *Begin = *HI;
1436      assert(Begin->isDebugValue() && "Invalid History entry");
1437      MachineLocation MLoc;
1438      if (Begin->getNumOperands() == 3) {
1439        if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
1440          MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
1441      } else
1442        MLoc = Asm->getDebugValueLocation(Begin);
1443
1444      // FIXME: emitDebugLoc only understands registers.
1445      if (!MLoc.getReg())
1446        continue;
1447
1448      // Compute the range for a register location.
1449      const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1450      const MCSymbol *SLabel = 0;
1451
1452      if (HI + 1 == HE)
1453        // If Begin is the last instruction in History then its value is valid
1454        // until the end of the function.
1455        SLabel = FunctionEndSym;
1456      else {
1457        const MachineInstr *End = HI[1];
1458        if (End->isDebugValue())
1459          SLabel = getLabelBeforeInsn(End);
1460        else {
1461          // End is a normal instruction clobbering the range.
1462          SLabel = getLabelAfterInsn(End);
1463          assert(SLabel && "Forgot label after clobber instruction");
1464          ++HI;
1465        }
1466      }
1467
1468      // The value is valid until the next DBG_VALUE or clobber.
1469      DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc, Var));
1470    }
1471    DotDebugLocEntries.push_back(DotDebugLocEntry());
1472  }
1473
1474  // Collect info for variables that were optimized out.
1475  const Function *F = MF->getFunction();
1476  if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1477    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1478      DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1479      if (!DV || !Processed.insert(DV))
1480        continue;
1481      DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
1482      if (Scope)
1483        Scope->addVariable(new DbgVariable(DV));
1484    }
1485  }
1486}
1487
1488/// getLabelBeforeInsn - Return Label preceding the instruction.
1489const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1490  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1491  assert(Label && "Didn't insert label before instruction");
1492  return Label;
1493}
1494
1495/// getLabelAfterInsn - Return Label immediately following the instruction.
1496const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1497  return LabelsAfterInsn.lookup(MI);
1498}
1499
1500/// beginInstruction - Process beginning of an instruction.
1501void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1502  // Check if source location changes, but ignore DBG_VALUE locations.
1503  if (!MI->isDebugValue()) {
1504    DebugLoc DL = MI->getDebugLoc();
1505    if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1506      PrevInstLoc = DL;
1507      if (!DL.isUnknown()) {
1508        const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1509        recordSourceLine(DL.getLine(), DL.getCol(), Scope);
1510      } else
1511        recordSourceLine(0, 0, 0);
1512    }
1513  }
1514
1515  // Insert labels where requested.
1516  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1517    LabelsBeforeInsn.find(MI);
1518
1519  // No label needed.
1520  if (I == LabelsBeforeInsn.end())
1521    return;
1522
1523  // Label already assigned.
1524  if (I->second)
1525    return;
1526
1527  if (!PrevLabel) {
1528    PrevLabel = MMI->getContext().CreateTempSymbol();
1529    Asm->OutStreamer.EmitLabel(PrevLabel);
1530  }
1531  I->second = PrevLabel;
1532}
1533
1534/// endInstruction - Process end of an instruction.
1535void DwarfDebug::endInstruction(const MachineInstr *MI) {
1536  // Don't create a new label after DBG_VALUE instructions.
1537  // They don't generate code.
1538  if (!MI->isDebugValue())
1539    PrevLabel = 0;
1540
1541  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1542    LabelsAfterInsn.find(MI);
1543
1544  // No label needed.
1545  if (I == LabelsAfterInsn.end())
1546    return;
1547
1548  // Label already assigned.
1549  if (I->second)
1550    return;
1551
1552  // We need a label after this instruction.
1553  if (!PrevLabel) {
1554    PrevLabel = MMI->getContext().CreateTempSymbol();
1555    Asm->OutStreamer.EmitLabel(PrevLabel);
1556  }
1557  I->second = PrevLabel;
1558}
1559
1560/// getOrCreateDbgScope - Create DbgScope for the scope.
1561DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
1562                                          const MDNode *InlinedAt) {
1563  if (!InlinedAt) {
1564    DbgScope *WScope = DbgScopeMap.lookup(Scope);
1565    if (WScope)
1566      return WScope;
1567    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1568    DbgScopeMap.insert(std::make_pair(Scope, WScope));
1569    if (DIDescriptor(Scope).isLexicalBlock()) {
1570      DbgScope *Parent =
1571        getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
1572      WScope->setParent(Parent);
1573      Parent->addScope(WScope);
1574    }
1575
1576    if (!WScope->getParent()) {
1577      StringRef SPName = DISubprogram(Scope).getLinkageName();
1578      // We used to check only for a linkage name, but that fails
1579      // since we began omitting the linkage name for private
1580      // functions.  The new way is to check for the name in metadata,
1581      // but that's not supported in old .ll test cases.  Ergo, we
1582      // check both.
1583      if (SPName == Asm->MF->getFunction()->getName() ||
1584          DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
1585        CurrentFnDbgScope = WScope;
1586    }
1587
1588    return WScope;
1589  }
1590
1591  getOrCreateAbstractScope(Scope);
1592  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1593  if (WScope)
1594    return WScope;
1595
1596  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1597  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1598  DILocation DL(InlinedAt);
1599  DbgScope *Parent =
1600    getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
1601  WScope->setParent(Parent);
1602  Parent->addScope(WScope);
1603
1604  ConcreteScopes[InlinedAt] = WScope;
1605
1606  return WScope;
1607}
1608
1609/// hasValidLocation - Return true if debug location entry attached with
1610/// machine instruction encodes valid location info.
1611static bool hasValidLocation(LLVMContext &Ctx,
1612                             const MachineInstr *MInsn,
1613                             const MDNode *&Scope, const MDNode *&InlinedAt) {
1614  DebugLoc DL = MInsn->getDebugLoc();
1615  if (DL.isUnknown()) return false;
1616
1617  const MDNode *S = DL.getScope(Ctx);
1618
1619  // There is no need to create another DIE for compile unit. For all
1620  // other scopes, create one DbgScope now. This will be translated
1621  // into a scope DIE at the end.
1622  if (DIScope(S).isCompileUnit()) return false;
1623
1624  Scope = S;
1625  InlinedAt = DL.getInlinedAt(Ctx);
1626  return true;
1627}
1628
1629/// calculateDominanceGraph - Calculate dominance graph for DbgScope
1630/// hierarchy.
1631static void calculateDominanceGraph(DbgScope *Scope) {
1632  assert (Scope && "Unable to calculate scop edominance graph!");
1633  SmallVector<DbgScope *, 4> WorkStack;
1634  WorkStack.push_back(Scope);
1635  unsigned Counter = 0;
1636  while (!WorkStack.empty()) {
1637    DbgScope *WS = WorkStack.back();
1638    const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
1639    bool visitedChildren = false;
1640    for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1641           SE = Children.end(); SI != SE; ++SI) {
1642      DbgScope *ChildScope = *SI;
1643      if (!ChildScope->getDFSOut()) {
1644        WorkStack.push_back(ChildScope);
1645        visitedChildren = true;
1646        ChildScope->setDFSIn(++Counter);
1647        break;
1648      }
1649    }
1650    if (!visitedChildren) {
1651      WorkStack.pop_back();
1652      WS->setDFSOut(++Counter);
1653    }
1654  }
1655}
1656
1657/// printDbgScopeInfo - Print DbgScope info for each machine instruction.
1658static
1659void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
1660                       DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
1661{
1662#ifndef NDEBUG
1663  unsigned PrevDFSIn = 0;
1664  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1665       I != E; ++I) {
1666    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1667         II != IE; ++II) {
1668      const MachineInstr *MInsn = II;
1669      const MDNode *Scope = NULL;
1670      const MDNode *InlinedAt = NULL;
1671
1672      // Check if instruction has valid location information.
1673      if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1674        dbgs() << " [ ";
1675        if (InlinedAt)
1676          dbgs() << "*";
1677        DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
1678          MI2ScopeMap.find(MInsn);
1679        if (DI != MI2ScopeMap.end()) {
1680          DbgScope *S = DI->second;
1681          dbgs() << S->getDFSIn();
1682          PrevDFSIn = S->getDFSIn();
1683        } else
1684          dbgs() << PrevDFSIn;
1685      } else
1686        dbgs() << " [ x" << PrevDFSIn;
1687      dbgs() << " ]";
1688      MInsn->dump();
1689    }
1690    dbgs() << "\n";
1691  }
1692#endif
1693}
1694/// extractScopeInformation - Scan machine instructions in this function
1695/// and collect DbgScopes. Return true, if at least one scope was found.
1696bool DwarfDebug::extractScopeInformation() {
1697  // If scope information was extracted using .dbg intrinsics then there is not
1698  // any need to extract these information by scanning each instruction.
1699  if (!DbgScopeMap.empty())
1700    return false;
1701
1702  // Scan each instruction and create scopes. First build working set of scopes.
1703  LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1704  SmallVector<DbgRange, 4> MIRanges;
1705  DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
1706  const MDNode *PrevScope = NULL;
1707  const MDNode *PrevInlinedAt = NULL;
1708  const MachineInstr *RangeBeginMI = NULL;
1709  const MachineInstr *PrevMI = NULL;
1710  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
1711       I != E; ++I) {
1712    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1713         II != IE; ++II) {
1714      const MachineInstr *MInsn = II;
1715      const MDNode *Scope = NULL;
1716      const MDNode *InlinedAt = NULL;
1717
1718      // Check if instruction has valid location information.
1719      if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1720        PrevMI = MInsn;
1721        continue;
1722      }
1723
1724      // If scope has not changed then skip this instruction.
1725      if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
1726        PrevMI = MInsn;
1727        continue;
1728      }
1729
1730      // Ignore DBG_VALUE. It does not contribute any instruction in output.
1731      if (MInsn->isDebugValue())
1732        continue;
1733
1734      if (RangeBeginMI) {
1735        // If we have alread seen a beginning of a instruction range and
1736        // current instruction scope does not match scope of first instruction
1737        // in this range then create a new instruction range.
1738        DbgRange R(RangeBeginMI, PrevMI);
1739        MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
1740                                                        PrevInlinedAt);
1741        MIRanges.push_back(R);
1742      }
1743
1744      // This is a beginning of a new instruction range.
1745      RangeBeginMI = MInsn;
1746
1747      // Reset previous markers.
1748      PrevMI = MInsn;
1749      PrevScope = Scope;
1750      PrevInlinedAt = InlinedAt;
1751    }
1752  }
1753
1754  // Create last instruction range.
1755  if (RangeBeginMI && PrevMI && PrevScope) {
1756    DbgRange R(RangeBeginMI, PrevMI);
1757    MIRanges.push_back(R);
1758    MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
1759  }
1760
1761  if (!CurrentFnDbgScope)
1762    return false;
1763
1764  calculateDominanceGraph(CurrentFnDbgScope);
1765  if (PrintDbgScope)
1766    printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
1767
1768  // Find ranges of instructions covered by each DbgScope;
1769  DbgScope *PrevDbgScope = NULL;
1770  for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
1771         RE = MIRanges.end(); RI != RE; ++RI) {
1772    const DbgRange &R = *RI;
1773    DbgScope *S = MI2ScopeMap.lookup(R.first);
1774    assert (S && "Lost DbgScope for a machine instruction!");
1775    if (PrevDbgScope && !PrevDbgScope->dominates(S))
1776      PrevDbgScope->closeInsnRange(S);
1777    S->openInsnRange(R.first);
1778    S->extendInsnRange(R.second);
1779    PrevDbgScope = S;
1780  }
1781
1782  if (PrevDbgScope)
1783    PrevDbgScope->closeInsnRange();
1784
1785  identifyScopeMarkers();
1786
1787  return !DbgScopeMap.empty();
1788}
1789
1790/// identifyScopeMarkers() -
1791/// Each DbgScope has first instruction and last instruction to mark beginning
1792/// and end of a scope respectively. Create an inverse map that list scopes
1793/// starts (and ends) with an instruction. One instruction may start (or end)
1794/// multiple scopes. Ignore scopes that are not reachable.
1795void DwarfDebug::identifyScopeMarkers() {
1796  SmallVector<DbgScope *, 4> WorkList;
1797  WorkList.push_back(CurrentFnDbgScope);
1798  while (!WorkList.empty()) {
1799    DbgScope *S = WorkList.pop_back_val();
1800
1801    const SmallVector<DbgScope *, 4> &Children = S->getScopes();
1802    if (!Children.empty())
1803      for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1804             SE = Children.end(); SI != SE; ++SI)
1805        WorkList.push_back(*SI);
1806
1807    if (S->isAbstractScope())
1808      continue;
1809
1810    const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
1811    if (Ranges.empty())
1812      continue;
1813    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1814           RE = Ranges.end(); RI != RE; ++RI) {
1815      assert(RI->first && "DbgRange does not have first instruction!");
1816      assert(RI->second && "DbgRange does not have second instruction!");
1817      requestLabelBeforeInsn(RI->first);
1818      requestLabelAfterInsn(RI->second);
1819    }
1820  }
1821}
1822
1823/// FindFirstDebugLoc - Find the first debug location in the function. This
1824/// is intended to be an approximation for the source position of the
1825/// beginning of the function.
1826static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
1827  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1828       I != E; ++I)
1829    for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
1830         MBBI != MBBE; ++MBBI) {
1831      DebugLoc DL = MBBI->getDebugLoc();
1832      if (!DL.isUnknown())
1833        return DL;
1834    }
1835  return DebugLoc();
1836}
1837
1838#ifndef NDEBUG
1839/// CheckLineNumbers - Count basicblocks whose instructions do not have any
1840/// line number information.
1841static void CheckLineNumbers(const MachineFunction *MF) {
1842  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1843       I != E; ++I) {
1844    bool FoundLineNo = false;
1845    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1846         II != IE; ++II) {
1847      const MachineInstr *MI = II;
1848      if (!MI->getDebugLoc().isUnknown()) {
1849        FoundLineNo = true;
1850        break;
1851      }
1852    }
1853    if (!FoundLineNo && I->size())
1854      ++BlocksWithoutLineNo;
1855  }
1856}
1857#endif
1858
1859/// beginFunction - Gather pre-function debug information.  Assumes being
1860/// emitted immediately after the function entry point.
1861void DwarfDebug::beginFunction(const MachineFunction *MF) {
1862  if (!MMI->hasDebugInfo()) return;
1863  if (!extractScopeInformation()) return;
1864
1865#ifndef NDEBUG
1866  CheckLineNumbers(MF);
1867#endif
1868
1869  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1870                                        Asm->getFunctionNumber());
1871  // Assumes in correct section after the entry point.
1872  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1873
1874  // Emit label for the implicitly defined dbg.stoppoint at the start of the
1875  // function.
1876  DebugLoc FDL = FindFirstDebugLoc(MF);
1877  if (FDL.isUnknown()) return;
1878
1879  const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
1880  const MDNode *TheScope = 0;
1881
1882  DISubprogram SP = getDISubprogram(Scope);
1883  unsigned Line, Col;
1884  if (SP.Verify()) {
1885    Line = SP.getLineNumber();
1886    Col = 0;
1887    TheScope = SP;
1888  } else {
1889    Line = FDL.getLine();
1890    Col = FDL.getCol();
1891    TheScope = Scope;
1892  }
1893
1894  recordSourceLine(Line, Col, TheScope);
1895
1896  assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1897
1898  /// ProcessedArgs - Collection of arguments already processed.
1899  SmallPtrSet<const MDNode *, 8> ProcessedArgs;
1900
1901  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1902
1903  /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1904  std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1905
1906  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1907       I != E; ++I) {
1908    bool AtBlockEntry = true;
1909    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1910         II != IE; ++II) {
1911      const MachineInstr *MI = II;
1912
1913      if (MI->isDebugValue()) {
1914        assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1915
1916        // Keep track of user variables.
1917        const MDNode *Var =
1918          MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1919
1920        // Variable is in a register, we need to check for clobbers.
1921        if (isDbgValueInDefinedReg(MI))
1922          LiveUserVar[MI->getOperand(0).getReg()] = Var;
1923
1924        // Check the history of this variable.
1925        SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1926        if (History.empty()) {
1927          UserVariables.push_back(Var);
1928          // The first mention of a function argument gets the FunctionBeginSym
1929          // label, so arguments are visible when breaking at function entry.
1930          DIVariable DV(Var);
1931          if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1932              DISubprogram(getDISubprogram(DV.getContext()))
1933                .describes(MF->getFunction()))
1934            LabelsBeforeInsn[MI] = FunctionBeginSym;
1935        } else {
1936          // We have seen this variable before. Try to coalesce DBG_VALUEs.
1937          const MachineInstr *Prev = History.back();
1938          if (Prev->isDebugValue()) {
1939            // Coalesce identical entries at the end of History.
1940            if (History.size() >= 2 &&
1941                Prev->isIdenticalTo(History[History.size() - 2]))
1942              History.pop_back();
1943
1944            // Terminate old register assignments that don't reach MI;
1945            MachineFunction::const_iterator PrevMBB = Prev->getParent();
1946            if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1947                isDbgValueInDefinedReg(Prev)) {
1948              // Previous register assignment needs to terminate at the end of
1949              // its basic block.
1950              MachineBasicBlock::const_iterator LastMI =
1951                PrevMBB->getLastNonDebugInstr();
1952              if (LastMI == PrevMBB->end())
1953                // Drop DBG_VALUE for empty range.
1954                History.pop_back();
1955              else {
1956                // Terminate after LastMI.
1957                History.push_back(LastMI);
1958              }
1959            }
1960          }
1961        }
1962        History.push_back(MI);
1963      } else {
1964        // Not a DBG_VALUE instruction.
1965        if (!MI->isLabel())
1966          AtBlockEntry = false;
1967
1968        // Check if the instruction clobbers any registers with debug vars.
1969        for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1970               MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1971          if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1972            continue;
1973          for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1974               unsigned Reg = *AI; ++AI) {
1975            const MDNode *Var = LiveUserVar[Reg];
1976            if (!Var)
1977              continue;
1978            // Reg is now clobbered.
1979            LiveUserVar[Reg] = 0;
1980
1981            // Was MD last defined by a DBG_VALUE referring to Reg?
1982            DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1983            if (HistI == DbgValues.end())
1984              continue;
1985            SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1986            if (History.empty())
1987              continue;
1988            const MachineInstr *Prev = History.back();
1989            // Sanity-check: Register assignments are terminated at the end of
1990            // their block.
1991            if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1992              continue;
1993            // Is the variable still in Reg?
1994            if (!isDbgValueInDefinedReg(Prev) ||
1995                Prev->getOperand(0).getReg() != Reg)
1996              continue;
1997            // Var is clobbered. Make sure the next instruction gets a label.
1998            History.push_back(MI);
1999          }
2000        }
2001      }
2002    }
2003  }
2004
2005  for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
2006       I != E; ++I) {
2007    SmallVectorImpl<const MachineInstr*> &History = I->second;
2008    if (History.empty())
2009      continue;
2010
2011    // Make sure the final register assignments are terminated.
2012    const MachineInstr *Prev = History.back();
2013    if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
2014      const MachineBasicBlock *PrevMBB = Prev->getParent();
2015      MachineBasicBlock::const_iterator LastMI = PrevMBB->getLastNonDebugInstr();
2016      if (LastMI == PrevMBB->end())
2017        // Drop DBG_VALUE for empty range.
2018        History.pop_back();
2019      else {
2020        // Terminate after LastMI.
2021        History.push_back(LastMI);
2022      }
2023    }
2024    // Request labels for the full history.
2025    for (unsigned i = 0, e = History.size(); i != e; ++i) {
2026      const MachineInstr *MI = History[i];
2027      if (MI->isDebugValue())
2028        requestLabelBeforeInsn(MI);
2029      else
2030        requestLabelAfterInsn(MI);
2031    }
2032  }
2033
2034  PrevInstLoc = DebugLoc();
2035  PrevLabel = FunctionBeginSym;
2036}
2037
2038/// endFunction - Gather and emit post-function debug information.
2039///
2040void DwarfDebug::endFunction(const MachineFunction *MF) {
2041  if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2042
2043  if (CurrentFnDbgScope) {
2044
2045    // Define end label for subprogram.
2046    FunctionEndSym = Asm->GetTempSymbol("func_end",
2047                                        Asm->getFunctionNumber());
2048    // Assumes in correct section after the entry point.
2049    Asm->OutStreamer.EmitLabel(FunctionEndSym);
2050
2051    SmallPtrSet<const MDNode *, 16> ProcessedVars;
2052    collectVariableInfo(MF, ProcessedVars);
2053
2054    // Construct abstract scopes.
2055    for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2056           AE = AbstractScopesList.end(); AI != AE; ++AI) {
2057      DISubprogram SP((*AI)->getScopeNode());
2058      if (SP.Verify()) {
2059        // Collect info for variables that were optimized out.
2060        StringRef FName = SP.getLinkageName();
2061        if (FName.empty())
2062          FName = SP.getName();
2063        if (NamedMDNode *NMD =
2064            getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
2065          for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2066          DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2067          if (!DV || !ProcessedVars.insert(DV))
2068            continue;
2069          DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2070          if (Scope)
2071            Scope->addVariable(new DbgVariable(DV));
2072          }
2073        }
2074      }
2075      if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2076        constructScopeDIE(*AI);
2077    }
2078
2079    DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2080
2081    if (!DisableFramePointerElim(*MF))
2082      getCompileUnit(CurrentFnDbgScope->getScopeNode())->addUInt(CurFnDIE,
2083                                                                 dwarf::DW_AT_APPLE_omit_frame_ptr,
2084                                                                 dwarf::DW_FORM_flag, 1);
2085
2086
2087    DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2088                                                 MMI->getFrameMoves()));
2089  }
2090
2091  // Clear debug info
2092  CurrentFnDbgScope = NULL;
2093  DeleteContainerPointers(CurrentFnArguments);
2094  DbgVariableToFrameIndexMap.clear();
2095  VarToAbstractVarMap.clear();
2096  DbgVariableToDbgInstMap.clear();
2097  DeleteContainerSeconds(DbgScopeMap);
2098  UserVariables.clear();
2099  DbgValues.clear();
2100  ConcreteScopes.clear();
2101  DeleteContainerSeconds(AbstractScopes);
2102  AbstractScopesList.clear();
2103  AbstractVariables.clear();
2104  LabelsBeforeInsn.clear();
2105  LabelsAfterInsn.clear();
2106  PrevLabel = NULL;
2107}
2108
2109/// recordVariableFrameIndex - Record a variable's index.
2110void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2111  assert (V && "Invalid DbgVariable!");
2112  DbgVariableToFrameIndexMap[V] = Index;
2113}
2114
2115/// findVariableFrameIndex - Return true if frame index for the variable
2116/// is found. Update FI to hold value of the index.
2117bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2118  assert (V && "Invalid DbgVariable!");
2119  DenseMap<const DbgVariable *, int>::iterator I =
2120    DbgVariableToFrameIndexMap.find(V);
2121  if (I == DbgVariableToFrameIndexMap.end())
2122    return false;
2123  *FI = I->second;
2124  return true;
2125}
2126
2127/// findDbgScope - Find DbgScope for the debug loc attached with an
2128/// instruction.
2129DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2130  DbgScope *Scope = NULL;
2131  LLVMContext &Ctx =
2132    MInsn->getParent()->getParent()->getFunction()->getContext();
2133  DebugLoc DL = MInsn->getDebugLoc();
2134
2135  if (DL.isUnknown())
2136    return Scope;
2137
2138  if (const MDNode *IA = DL.getInlinedAt(Ctx))
2139    Scope = ConcreteScopes.lookup(IA);
2140  if (Scope == 0)
2141    Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2142
2143  return Scope;
2144}
2145
2146
2147/// recordSourceLine - Register a source line with debug info. Returns the
2148/// unique label that was emitted and which provides correspondence to
2149/// the source line list.
2150void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S){
2151  StringRef Fn;
2152  StringRef Dir;
2153  unsigned Src = 1;
2154  if (S) {
2155    DIDescriptor Scope(S);
2156
2157    if (Scope.isCompileUnit()) {
2158      DICompileUnit CU(S);
2159      Fn = CU.getFilename();
2160      Dir = CU.getDirectory();
2161    } else if (Scope.isFile()) {
2162      DIFile F(S);
2163      Fn = F.getFilename();
2164      Dir = F.getDirectory();
2165    } else if (Scope.isSubprogram()) {
2166      DISubprogram SP(S);
2167      Fn = SP.getFilename();
2168      Dir = SP.getDirectory();
2169    } else if (Scope.isLexicalBlock()) {
2170      DILexicalBlock DB(S);
2171      Fn = DB.getFilename();
2172      Dir = DB.getDirectory();
2173    } else
2174      assert(0 && "Unexpected scope info");
2175
2176    Src = GetOrCreateSourceID(Fn, Dir);
2177  }
2178  Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, DWARF2_FLAG_IS_STMT,
2179                                         0, 0, Fn);
2180}
2181
2182//===----------------------------------------------------------------------===//
2183// Emit Methods
2184//===----------------------------------------------------------------------===//
2185
2186/// computeSizeAndOffset - Compute the size and offset of a DIE.
2187///
2188unsigned
2189DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2190  // Get the children.
2191  const std::vector<DIE *> &Children = Die->getChildren();
2192
2193  // If not last sibling and has children then add sibling offset attribute.
2194  if (!Last && !Children.empty())
2195    Die->addSiblingOffset(DIEValueAllocator);
2196
2197  // Record the abbreviation.
2198  assignAbbrevNumber(Die->getAbbrev());
2199
2200  // Get the abbreviation for this DIE.
2201  unsigned AbbrevNumber = Die->getAbbrevNumber();
2202  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2203
2204  // Set DIE offset
2205  Die->setOffset(Offset);
2206
2207  // Start the size with the size of abbreviation code.
2208  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2209
2210  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2211  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2212
2213  // Size the DIE attribute values.
2214  for (unsigned i = 0, N = Values.size(); i < N; ++i)
2215    // Size attribute value.
2216    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2217
2218  // Size the DIE children if any.
2219  if (!Children.empty()) {
2220    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2221           "Children flag not set");
2222
2223    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2224      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2225
2226    // End of children marker.
2227    Offset += sizeof(int8_t);
2228  }
2229
2230  Die->setSize(Offset - Die->getOffset());
2231  return Offset;
2232}
2233
2234/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2235///
2236void DwarfDebug::computeSizeAndOffsets() {
2237  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2238         E = CUMap.end(); I != E; ++I) {
2239    // Compute size of compile unit header.
2240    unsigned Offset =
2241      sizeof(int32_t) + // Length of Compilation Unit Info
2242      sizeof(int16_t) + // DWARF version number
2243      sizeof(int32_t) + // Offset Into Abbrev. Section
2244      sizeof(int8_t);   // Pointer Size (in bytes)
2245    computeSizeAndOffset(I->second->getCUDie(), Offset, true);
2246  }
2247}
2248
2249/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2250/// temporary label to it if SymbolStem is specified.
2251static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2252                                const char *SymbolStem = 0) {
2253  Asm->OutStreamer.SwitchSection(Section);
2254  if (!SymbolStem) return 0;
2255
2256  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2257  Asm->OutStreamer.EmitLabel(TmpSym);
2258  return TmpSym;
2259}
2260
2261/// EmitSectionLabels - Emit initial Dwarf sections with a label at
2262/// the start of each one.
2263void DwarfDebug::EmitSectionLabels() {
2264  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2265
2266  // Dwarf sections base addresses.
2267  if (Asm->MAI->doesDwarfRequireFrameSection()) {
2268    DwarfFrameSectionSym =
2269      EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2270   }
2271
2272  DwarfInfoSectionSym =
2273    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2274  DwarfAbbrevSectionSym =
2275    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2276  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2277
2278  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2279    EmitSectionSym(Asm, MacroInfo);
2280
2281  EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2282  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2283  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2284  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2285  DwarfStrSectionSym =
2286    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2287  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2288                                             "debug_range");
2289
2290  DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
2291                                           "section_debug_loc");
2292
2293  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2294  EmitSectionSym(Asm, TLOF.getDataSection());
2295}
2296
2297/// emitDIE - Recusively Emits a debug information entry.
2298///
2299void DwarfDebug::emitDIE(DIE *Die) {
2300  // Get the abbreviation for this DIE.
2301  unsigned AbbrevNumber = Die->getAbbrevNumber();
2302  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2303
2304  // Emit the code (index) for the abbreviation.
2305  if (Asm->isVerbose())
2306    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2307                                Twine::utohexstr(Die->getOffset()) + ":0x" +
2308                                Twine::utohexstr(Die->getSize()) + " " +
2309                                dwarf::TagString(Abbrev->getTag()));
2310  Asm->EmitULEB128(AbbrevNumber);
2311
2312  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2313  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2314
2315  // Emit the DIE attribute values.
2316  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2317    unsigned Attr = AbbrevData[i].getAttribute();
2318    unsigned Form = AbbrevData[i].getForm();
2319    assert(Form && "Too many attributes for DIE (check abbreviation)");
2320
2321    if (Asm->isVerbose())
2322      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2323
2324    switch (Attr) {
2325    case dwarf::DW_AT_sibling:
2326      Asm->EmitInt32(Die->getSiblingOffset());
2327      break;
2328    case dwarf::DW_AT_abstract_origin: {
2329      DIEEntry *E = cast<DIEEntry>(Values[i]);
2330      DIE *Origin = E->getEntry();
2331      unsigned Addr = Origin->getOffset();
2332      Asm->EmitInt32(Addr);
2333      break;
2334    }
2335    case dwarf::DW_AT_ranges: {
2336      // DW_AT_range Value encodes offset in debug_range section.
2337      DIEInteger *V = cast<DIEInteger>(Values[i]);
2338
2339      if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
2340        Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2341                                 V->getValue(),
2342                                 4);
2343      } else {
2344        Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2345                                       V->getValue(),
2346                                       DwarfDebugRangeSectionSym,
2347                                       4);
2348      }
2349      break;
2350    }
2351    case dwarf::DW_AT_location: {
2352      if (UseDotDebugLocEntry.count(Die) != 0) {
2353        DIELabel *L = cast<DIELabel>(Values[i]);
2354        Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2355      } else
2356        Values[i]->EmitValue(Asm, Form);
2357      break;
2358    }
2359    case dwarf::DW_AT_accessibility: {
2360      if (Asm->isVerbose()) {
2361        DIEInteger *V = cast<DIEInteger>(Values[i]);
2362        Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2363      }
2364      Values[i]->EmitValue(Asm, Form);
2365      break;
2366    }
2367    default:
2368      // Emit an attribute using the defined form.
2369      Values[i]->EmitValue(Asm, Form);
2370      break;
2371    }
2372  }
2373
2374  // Emit the DIE children if any.
2375  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2376    const std::vector<DIE *> &Children = Die->getChildren();
2377
2378    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2379      emitDIE(Children[j]);
2380
2381    if (Asm->isVerbose())
2382      Asm->OutStreamer.AddComment("End Of Children Mark");
2383    Asm->EmitInt8(0);
2384  }
2385}
2386
2387/// emitDebugInfo - Emit the debug info section.
2388///
2389void DwarfDebug::emitDebugInfo() {
2390  // Start debug info section.
2391  Asm->OutStreamer.SwitchSection(
2392                            Asm->getObjFileLowering().getDwarfInfoSection());
2393  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2394         E = CUMap.end(); I != E; ++I) {
2395    CompileUnit *TheCU = I->second;
2396    DIE *Die = TheCU->getCUDie();
2397
2398    // Emit the compile units header.
2399    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2400                                                  TheCU->getID()));
2401
2402    // Emit size of content not including length itself
2403    unsigned ContentSize = Die->getSize() +
2404      sizeof(int16_t) + // DWARF version number
2405      sizeof(int32_t) + // Offset Into Abbrev. Section
2406      sizeof(int8_t);   // Pointer Size (in bytes)
2407
2408    Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2409    Asm->EmitInt32(ContentSize);
2410    Asm->OutStreamer.AddComment("DWARF version number");
2411    Asm->EmitInt16(dwarf::DWARF_VERSION);
2412    Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2413    Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2414                           DwarfAbbrevSectionSym);
2415    Asm->OutStreamer.AddComment("Address Size (in bytes)");
2416    Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2417
2418    emitDIE(Die);
2419    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
2420  }
2421}
2422
2423/// emitAbbreviations - Emit the abbreviation section.
2424///
2425void DwarfDebug::emitAbbreviations() const {
2426  // Check to see if it is worth the effort.
2427  if (!Abbreviations.empty()) {
2428    // Start the debug abbrev section.
2429    Asm->OutStreamer.SwitchSection(
2430                            Asm->getObjFileLowering().getDwarfAbbrevSection());
2431
2432    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2433
2434    // For each abbrevation.
2435    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2436      // Get abbreviation data
2437      const DIEAbbrev *Abbrev = Abbreviations[i];
2438
2439      // Emit the abbrevations code (base 1 index.)
2440      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2441
2442      // Emit the abbreviations data.
2443      Abbrev->Emit(Asm);
2444    }
2445
2446    // Mark end of abbreviations.
2447    Asm->EmitULEB128(0, "EOM(3)");
2448
2449    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2450  }
2451}
2452
2453/// emitEndOfLineMatrix - Emit the last address of the section and the end of
2454/// the line matrix.
2455///
2456void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2457  // Define last address of section.
2458  Asm->OutStreamer.AddComment("Extended Op");
2459  Asm->EmitInt8(0);
2460
2461  Asm->OutStreamer.AddComment("Op size");
2462  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2463  Asm->OutStreamer.AddComment("DW_LNE_set_address");
2464  Asm->EmitInt8(dwarf::DW_LNE_set_address);
2465
2466  Asm->OutStreamer.AddComment("Section end label");
2467
2468  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2469                                   Asm->getTargetData().getPointerSize(),
2470                                   0/*AddrSpace*/);
2471
2472  // Mark end of matrix.
2473  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2474  Asm->EmitInt8(0);
2475  Asm->EmitInt8(1);
2476  Asm->EmitInt8(1);
2477}
2478
2479/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2480///
2481void DwarfDebug::emitCommonDebugFrame() {
2482  if (!Asm->MAI->doesDwarfRequireFrameSection())
2483    return;
2484
2485  int stackGrowth = Asm->getTargetData().getPointerSize();
2486  if (Asm->TM.getFrameLowering()->getStackGrowthDirection() ==
2487      TargetFrameLowering::StackGrowsDown)
2488    stackGrowth *= -1;
2489
2490  // Start the dwarf frame section.
2491  Asm->OutStreamer.SwitchSection(
2492                              Asm->getObjFileLowering().getDwarfFrameSection());
2493
2494  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
2495  Asm->OutStreamer.AddComment("Length of Common Information Entry");
2496  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
2497                           Asm->GetTempSymbol("debug_frame_common_begin"), 4);
2498
2499  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
2500  Asm->OutStreamer.AddComment("CIE Identifier Tag");
2501  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2502  Asm->OutStreamer.AddComment("CIE Version");
2503  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2504  Asm->OutStreamer.AddComment("CIE Augmentation");
2505  Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
2506  Asm->EmitULEB128(1, "CIE Code Alignment Factor");
2507  Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
2508  Asm->OutStreamer.AddComment("CIE RA Column");
2509  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
2510  const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
2511  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2512
2513  std::vector<MachineMove> Moves;
2514  TFI->getInitialFrameState(Moves);
2515
2516  Asm->EmitFrameMoves(Moves, 0, false);
2517
2518  Asm->EmitAlignment(2);
2519  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
2520}
2521
2522/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2523/// section.
2524void DwarfDebug::
2525emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2526  if (!Asm->MAI->doesDwarfRequireFrameSection())
2527    return;
2528
2529  // Start the dwarf frame section.
2530  Asm->OutStreamer.SwitchSection(
2531                              Asm->getObjFileLowering().getDwarfFrameSection());
2532
2533  Asm->OutStreamer.AddComment("Length of Frame Information Entry");
2534  MCSymbol *DebugFrameBegin =
2535    Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
2536  MCSymbol *DebugFrameEnd =
2537    Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
2538  Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
2539
2540  Asm->OutStreamer.EmitLabel(DebugFrameBegin);
2541
2542  Asm->OutStreamer.AddComment("FDE CIE offset");
2543  Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
2544                         DwarfFrameSectionSym);
2545
2546  Asm->OutStreamer.AddComment("FDE initial location");
2547  MCSymbol *FuncBeginSym =
2548    Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
2549  Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
2550                                   Asm->getTargetData().getPointerSize(),
2551                                   0/*AddrSpace*/);
2552
2553
2554  Asm->OutStreamer.AddComment("FDE address range");
2555  Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
2556                           FuncBeginSym, Asm->getTargetData().getPointerSize());
2557
2558  Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
2559
2560  Asm->EmitAlignment(2);
2561  Asm->OutStreamer.EmitLabel(DebugFrameEnd);
2562}
2563
2564/// emitDebugPubNames - Emit visible names into a debug pubnames section.
2565///
2566void DwarfDebug::emitDebugPubNames() {
2567  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2568         E = CUMap.end(); I != E; ++I) {
2569    CompileUnit *TheCU = I->second;
2570    // Start the dwarf pubnames section.
2571    Asm->OutStreamer.SwitchSection(
2572      Asm->getObjFileLowering().getDwarfPubNamesSection());
2573
2574    Asm->OutStreamer.AddComment("Length of Public Names Info");
2575    Asm->EmitLabelDifference(
2576      Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
2577      Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
2578
2579    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
2580                                                  TheCU->getID()));
2581
2582    Asm->OutStreamer.AddComment("DWARF Version");
2583    Asm->EmitInt16(dwarf::DWARF_VERSION);
2584
2585    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2586    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2587                           DwarfInfoSectionSym);
2588
2589    Asm->OutStreamer.AddComment("Compilation Unit Length");
2590    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2591                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
2592                             4);
2593
2594    const StringMap<DIE*> &Globals = TheCU->getGlobals();
2595    for (StringMap<DIE*>::const_iterator
2596           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2597      const char *Name = GI->getKeyData();
2598      DIE *Entity = GI->second;
2599
2600      Asm->OutStreamer.AddComment("DIE offset");
2601      Asm->EmitInt32(Entity->getOffset());
2602
2603      if (Asm->isVerbose())
2604        Asm->OutStreamer.AddComment("External Name");
2605      Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2606    }
2607
2608    Asm->OutStreamer.AddComment("End Mark");
2609    Asm->EmitInt32(0);
2610    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
2611                                                TheCU->getID()));
2612  }
2613}
2614
2615void DwarfDebug::emitDebugPubTypes() {
2616  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2617         E = CUMap.end(); I != E; ++I) {
2618    CompileUnit *TheCU = I->second;
2619    // Start the dwarf pubnames section.
2620    Asm->OutStreamer.SwitchSection(
2621      Asm->getObjFileLowering().getDwarfPubTypesSection());
2622    Asm->OutStreamer.AddComment("Length of Public Types Info");
2623    Asm->EmitLabelDifference(
2624      Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
2625      Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
2626
2627    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2628                                                  TheCU->getID()));
2629
2630    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2631    Asm->EmitInt16(dwarf::DWARF_VERSION);
2632
2633    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2634    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2635                           DwarfInfoSectionSym);
2636
2637    Asm->OutStreamer.AddComment("Compilation Unit Length");
2638    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2639                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
2640                             4);
2641
2642    const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2643    for (StringMap<DIE*>::const_iterator
2644           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2645      const char *Name = GI->getKeyData();
2646      DIE * Entity = GI->second;
2647
2648      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2649      Asm->EmitInt32(Entity->getOffset());
2650
2651      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2652      Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2653    }
2654
2655    Asm->OutStreamer.AddComment("End Mark");
2656    Asm->EmitInt32(0);
2657    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2658                                                  TheCU->getID()));
2659  }
2660}
2661
2662/// emitDebugStr - Emit visible names into a debug str section.
2663///
2664void DwarfDebug::emitDebugStr() {
2665  // Check to see if it is worth the effort.
2666  if (StringPool.empty()) return;
2667
2668  // Start the dwarf str section.
2669  Asm->OutStreamer.SwitchSection(
2670                                Asm->getObjFileLowering().getDwarfStrSection());
2671
2672  // Get all of the string pool entries and put them in an array by their ID so
2673  // we can sort them.
2674  SmallVector<std::pair<unsigned,
2675      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2676
2677  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2678       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2679    Entries.push_back(std::make_pair(I->second.second, &*I));
2680
2681  array_pod_sort(Entries.begin(), Entries.end());
2682
2683  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2684    // Emit a label for reference from debug information entries.
2685    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2686
2687    // Emit the string itself.
2688    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
2689  }
2690}
2691
2692/// emitDebugLoc - Emit visible names into a debug loc section.
2693///
2694void DwarfDebug::emitDebugLoc() {
2695  if (DotDebugLocEntries.empty())
2696    return;
2697
2698  for (SmallVector<DotDebugLocEntry, 4>::iterator
2699         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2700       I != E; ++I) {
2701    DotDebugLocEntry &Entry = *I;
2702    if (I + 1 != DotDebugLocEntries.end())
2703      Entry.Merge(I+1);
2704  }
2705
2706  // Start the dwarf loc section.
2707  Asm->OutStreamer.SwitchSection(
2708    Asm->getObjFileLowering().getDwarfLocSection());
2709  unsigned char Size = Asm->getTargetData().getPointerSize();
2710  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2711  unsigned index = 1;
2712  for (SmallVector<DotDebugLocEntry, 4>::iterator
2713         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2714       I != E; ++I, ++index) {
2715    DotDebugLocEntry &Entry = *I;
2716    if (Entry.isMerged()) continue;
2717    if (Entry.isEmpty()) {
2718      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2719      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2720      Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2721    } else {
2722      Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2723      Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2724      DIVariable DV(Entry.Variable);
2725      if (DV.hasComplexAddress()) {
2726        unsigned N = DV.getNumAddrElements();
2727        unsigned i = 0;
2728        Asm->OutStreamer.AddComment("Loc expr size");
2729        if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2730          // If first address element is OpPlus then emit
2731          // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2732          MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2733          Asm->EmitInt16(Asm->getDwarfRegOpSize(Loc) + N - 2);
2734          Asm->EmitDwarfRegOp(Loc);
2735//          Asm->EmitULEB128(DV.getAddrElement(1));
2736          i = 2;
2737        } else {
2738          Asm->EmitInt16(Asm->getDwarfRegOpSize(Entry.Loc) + N);
2739          Asm->EmitDwarfRegOp(Entry.Loc);
2740        }
2741
2742        // Emit remaining complex address elements.
2743        for (; i < N; ++i) {
2744          uint64_t Element = DV.getAddrElement(i);
2745          if (Element == DIBuilder::OpPlus) {
2746            Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2747            Asm->EmitULEB128(DV.getAddrElement(++i));
2748          } else if (Element == DIBuilder::OpDeref)
2749            Asm->EmitInt8(dwarf::DW_OP_deref);
2750          else llvm_unreachable("unknown Opcode found in complex address");
2751        }
2752      } else {
2753        Asm->OutStreamer.AddComment("Loc expr size");
2754        Asm->EmitInt16(Asm->getDwarfRegOpSize(Entry.Loc));
2755        Asm->EmitDwarfRegOp(Entry.Loc);
2756      }
2757    }
2758  }
2759}
2760
2761/// EmitDebugARanges - Emit visible names into a debug aranges section.
2762///
2763void DwarfDebug::EmitDebugARanges() {
2764  // Start the dwarf aranges section.
2765  Asm->OutStreamer.SwitchSection(
2766                          Asm->getObjFileLowering().getDwarfARangesSection());
2767}
2768
2769/// emitDebugRanges - Emit visible names into a debug ranges section.
2770///
2771void DwarfDebug::emitDebugRanges() {
2772  // Start the dwarf ranges section.
2773  Asm->OutStreamer.SwitchSection(
2774    Asm->getObjFileLowering().getDwarfRangesSection());
2775  unsigned char Size = Asm->getTargetData().getPointerSize();
2776  for (SmallVector<const MCSymbol *, 8>::iterator
2777         I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2778       I != E; ++I) {
2779    if (*I)
2780      Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2781    else
2782      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2783  }
2784}
2785
2786/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2787///
2788void DwarfDebug::emitDebugMacInfo() {
2789  if (const MCSection *LineInfo =
2790      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2791    // Start the dwarf macinfo section.
2792    Asm->OutStreamer.SwitchSection(LineInfo);
2793  }
2794}
2795
2796/// emitDebugInlineInfo - Emit inline info using following format.
2797/// Section Header:
2798/// 1. length of section
2799/// 2. Dwarf version number
2800/// 3. address size.
2801///
2802/// Entries (one "entry" for each function that was inlined):
2803///
2804/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2805///   otherwise offset into __debug_str for regular function name.
2806/// 2. offset into __debug_str section for regular function name.
2807/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2808/// instances for the function.
2809///
2810/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2811/// inlined instance; the die_offset points to the inlined_subroutine die in the
2812/// __debug_info section, and the low_pc is the starting address for the
2813/// inlining instance.
2814void DwarfDebug::emitDebugInlineInfo() {
2815  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2816    return;
2817
2818  if (!FirstCU)
2819    return;
2820
2821  Asm->OutStreamer.SwitchSection(
2822                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
2823
2824  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2825  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2826                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2827
2828  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2829
2830  Asm->OutStreamer.AddComment("Dwarf Version");
2831  Asm->EmitInt16(dwarf::DWARF_VERSION);
2832  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2833  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2834
2835  for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2836         E = InlinedSPNodes.end(); I != E; ++I) {
2837
2838    const MDNode *Node = *I;
2839    DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2840      = InlineInfo.find(Node);
2841    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2842    DISubprogram SP(Node);
2843    StringRef LName = SP.getLinkageName();
2844    StringRef Name = SP.getName();
2845
2846    Asm->OutStreamer.AddComment("MIPS linkage name");
2847    if (LName.empty()) {
2848      Asm->OutStreamer.EmitBytes(Name, 0);
2849      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2850    } else
2851      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2852                             DwarfStrSectionSym);
2853
2854    Asm->OutStreamer.AddComment("Function name");
2855    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2856    Asm->EmitULEB128(Labels.size(), "Inline count");
2857
2858    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2859           LE = Labels.end(); LI != LE; ++LI) {
2860      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2861      Asm->EmitInt32(LI->second->getOffset());
2862
2863      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2864      Asm->OutStreamer.EmitSymbolValue(LI->first,
2865                                       Asm->getTargetData().getPointerSize(),0);
2866    }
2867  }
2868
2869  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2870}
2871