DwarfDebug.cpp revision c23b933d5f8be9b51a1d22e717c0311f65f87dcd
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 "DwarfAccelTable.h"
18#include "DwarfCompileUnit.h"
19#include "llvm/Constants.h"
20#include "llvm/DebugInfo.h"
21#include "llvm/DIBuilder.h"
22#include "llvm/Module.h"
23#include "llvm/Instructions.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineModuleInfo.h"
26#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCSection.h"
28#include "llvm/MC/MCStreamer.h"
29#include "llvm/MC/MCSymbol.h"
30#include "llvm/Target/TargetData.h"
31#include "llvm/Target/TargetFrameLowering.h"
32#include "llvm/Target/TargetLoweringObjectFile.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetRegisterInfo.h"
35#include "llvm/Target/TargetOptions.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/ADT/Triple.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/ValueHandle.h"
44#include "llvm/Support/FormattedStream.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/Path.h"
47using namespace llvm;
48
49static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
50                                              cl::Hidden,
51     cl::desc("Disable debug info printing"));
52
53static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54     cl::desc("Make an absence of debug location information explicit."),
55     cl::init(false));
56
57static cl::opt<bool> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
58     cl::desc("Output prototype dwarf accelerator tables."),
59     cl::init(false));
60
61namespace {
62  const char *DWARFGroupName = "DWARF Emission";
63  const char *DbgTimerName = "DWARF Debug Writer";
64} // end anonymous namespace
65
66//===----------------------------------------------------------------------===//
67
68/// Configuration values for initial hash set sizes (log2).
69///
70static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
71
72namespace llvm {
73
74DIType DbgVariable::getType() const {
75  DIType Ty = Var.getType();
76  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
77  // addresses instead.
78  if (Var.isBlockByrefVariable()) {
79    /* Byref variables, in Blocks, are declared by the programmer as
80       "SomeType VarName;", but the compiler creates a
81       __Block_byref_x_VarName struct, and gives the variable VarName
82       either the struct, or a pointer to the struct, as its type.  This
83       is necessary for various behind-the-scenes things the compiler
84       needs to do with by-reference variables in blocks.
85
86       However, as far as the original *programmer* is concerned, the
87       variable should still have type 'SomeType', as originally declared.
88
89       The following function dives into the __Block_byref_x_VarName
90       struct to find the original type of the variable.  This will be
91       passed back to the code generating the type for the Debug
92       Information Entry for the variable 'VarName'.  'VarName' will then
93       have the original type 'SomeType' in its debug information.
94
95       The original type 'SomeType' will be the type of the field named
96       'VarName' inside the __Block_byref_x_VarName struct.
97
98       NOTE: In order for this to not completely fail on the debugger
99       side, the Debug Information Entry for the variable VarName needs to
100       have a DW_AT_location that tells the debugger how to unwind through
101       the pointers and __Block_byref_x_VarName struct to find the actual
102       value of the variable.  The function addBlockByrefType does this.  */
103    DIType subType = Ty;
104    unsigned tag = Ty.getTag();
105
106    if (tag == dwarf::DW_TAG_pointer_type) {
107      DIDerivedType DTy = DIDerivedType(Ty);
108      subType = DTy.getTypeDerivedFrom();
109    }
110
111    DICompositeType blockStruct = DICompositeType(subType);
112    DIArray Elements = blockStruct.getTypeArray();
113
114    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
115      DIDescriptor Element = Elements.getElement(i);
116      DIDerivedType DT = DIDerivedType(Element);
117      if (getName() == DT.getName())
118        return (DT.getTypeDerivedFrom());
119    }
120  }
121  return Ty;
122}
123
124} // end llvm namespace
125
126DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
127  : Asm(A), MMI(Asm->MMI), FirstCU(0),
128    AbbreviationsSet(InitAbbreviationsSetSize),
129    SourceIdMap(DIEValueAllocator), StringPool(DIEValueAllocator),
130    PrevLabel(NULL),
131    HasNonTextSection(false) {
132  NextStringPoolNumber = 0;
133
134  DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
135  DwarfStrSectionSym = TextSectionSym = 0;
136  DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
137  FunctionBeginSym = FunctionEndSym = 0;
138
139  // Turn on accelerator tables for Darwin.
140  if (Triple(M->getTargetTriple()).isOSDarwin())
141    DwarfAccelTables = true;
142
143  {
144    NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
145    beginModule(M);
146  }
147}
148DwarfDebug::~DwarfDebug() {
149}
150
151/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
152/// temporary label to it if SymbolStem is specified.
153static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
154                                const char *SymbolStem = 0) {
155  Asm->OutStreamer.SwitchSection(Section);
156  if (!SymbolStem) return 0;
157
158  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
159  Asm->OutStreamer.EmitLabel(TmpSym);
160  return TmpSym;
161}
162
163MCSymbol *DwarfDebug::getStringPool() {
164  return Asm->GetTempSymbol("section_str");
165}
166
167MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
168  std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
169  if (Entry.first) return Entry.first;
170
171  Entry.second = NextStringPoolNumber++;
172  return Entry.first = Asm->GetTempSymbol("string", Entry.second);
173}
174
175/// assignAbbrevNumber - Define a unique number for the abbreviation.
176///
177void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
178  // Profile the node so that we can make it unique.
179  FoldingSetNodeID ID;
180  Abbrev.Profile(ID);
181
182  // Check the set for priors.
183  DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
184
185  // If it's newly added.
186  if (InSet == &Abbrev) {
187    // Add to abbreviation list.
188    Abbreviations.push_back(&Abbrev);
189
190    // Assign the vector position + 1 as its number.
191    Abbrev.setNumber(Abbreviations.size());
192  } else {
193    // Assign existing abbreviation number.
194    Abbrev.setNumber(InSet->getNumber());
195  }
196}
197
198/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
199/// printer to not emit usual symbol prefix before the symbol name is used then
200/// return linkage name after skipping this special LLVM prefix.
201static StringRef getRealLinkageName(StringRef LinkageName) {
202  char One = '\1';
203  if (LinkageName.startswith(StringRef(&One, 1)))
204    return LinkageName.substr(1);
205  return LinkageName;
206}
207
208static bool isObjCClass(StringRef Name) {
209  return Name.startswith("+") || Name.startswith("-");
210}
211
212static bool hasObjCCategory(StringRef Name) {
213  if (!isObjCClass(Name)) return false;
214
215  size_t pos = Name.find(')');
216  if (pos != std::string::npos) {
217    if (Name[pos+1] != ' ') return false;
218    return true;
219  }
220  return false;
221}
222
223static void getObjCClassCategory(StringRef In, StringRef &Class,
224                                 StringRef &Category) {
225  if (!hasObjCCategory(In)) {
226    Class = In.slice(In.find('[') + 1, In.find(' '));
227    Category = "";
228    return;
229  }
230
231  Class = In.slice(In.find('[') + 1, In.find('('));
232  Category = In.slice(In.find('[') + 1, In.find(' '));
233  return;
234}
235
236static StringRef getObjCMethodName(StringRef In) {
237  return In.slice(In.find(' ') + 1, In.find(']'));
238}
239
240// Add the various names to the Dwarf accelerator table names.
241static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
242                               DIE* Die) {
243  if (!SP.isDefinition()) return;
244
245  TheCU->addAccelName(SP.getName(), Die);
246
247  // If the linkage name is different than the name, go ahead and output
248  // that as well into the name table.
249  if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
250    TheCU->addAccelName(SP.getLinkageName(), Die);
251
252  // If this is an Objective-C selector name add it to the ObjC accelerator
253  // too.
254  if (isObjCClass(SP.getName())) {
255    StringRef Class, Category;
256    getObjCClassCategory(SP.getName(), Class, Category);
257    TheCU->addAccelObjC(Class, Die);
258    if (Category != "")
259      TheCU->addAccelObjC(Category, Die);
260    // Also add the base method name to the name table.
261    TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
262  }
263}
264
265/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
266/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
267/// If there are global variables in this scope then create and insert
268/// DIEs for these variables.
269DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
270                                          const MDNode *SPNode) {
271  DIE *SPDie = SPCU->getDIE(SPNode);
272
273  assert(SPDie && "Unable to find subprogram DIE!");
274  DISubprogram SP(SPNode);
275
276  DISubprogram SPDecl = SP.getFunctionDeclaration();
277  if (!SPDecl.isSubprogram()) {
278    // There is not any need to generate specification DIE for a function
279    // defined at compile unit level. If a function is defined inside another
280    // function then gdb prefers the definition at top level and but does not
281    // expect specification DIE in parent function. So avoid creating
282    // specification DIE for a function defined inside a function.
283    if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
284        !SP.getContext().isFile() &&
285        !isSubprogramContext(SP.getContext())) {
286      SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
287
288      // Add arguments.
289      DICompositeType SPTy = SP.getType();
290      DIArray Args = SPTy.getTypeArray();
291      unsigned SPTag = SPTy.getTag();
292      if (SPTag == dwarf::DW_TAG_subroutine_type)
293        for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
294          DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
295          DIType ATy = DIType(DIType(Args.getElement(i)));
296          SPCU->addType(Arg, ATy);
297          if (ATy.isArtificial())
298            SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
299          SPDie->addChild(Arg);
300        }
301      DIE *SPDeclDie = SPDie;
302      SPDie = new DIE(dwarf::DW_TAG_subprogram);
303      SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
304                        SPDeclDie);
305      SPCU->addDie(SPDie);
306    }
307  }
308  // Pick up abstract subprogram DIE.
309  if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
310    SPDie = new DIE(dwarf::DW_TAG_subprogram);
311    SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
312                      dwarf::DW_FORM_ref4, AbsSPDIE);
313    SPCU->addDie(SPDie);
314  }
315
316  SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
317                 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
318  SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
319                 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
320  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
321  MachineLocation Location(RI->getFrameRegister(*Asm->MF));
322  SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
323
324  // Add name to the name table, we do this here because we're guaranteed
325  // to have concrete versions of our DW_TAG_subprogram nodes.
326  addSubprogramNames(SPCU, SP, SPDie);
327
328  return SPDie;
329}
330
331/// constructLexicalScope - Construct new DW_TAG_lexical_block
332/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
333DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
334                                          LexicalScope *Scope) {
335  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
336  if (Scope->isAbstractScope())
337    return ScopeDIE;
338
339  const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
340  if (Ranges.empty())
341    return 0;
342
343  SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
344  if (Ranges.size() > 1) {
345    // .debug_range section has not been laid out yet. Emit offset in
346    // .debug_range as a uint, size 4, for now. emitDIE will handle
347    // DW_AT_ranges appropriately.
348    TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
349                   DebugRangeSymbols.size()
350                   * Asm->getTargetData().getPointerSize());
351    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
352         RE = Ranges.end(); RI != RE; ++RI) {
353      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
354      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
355    }
356    DebugRangeSymbols.push_back(NULL);
357    DebugRangeSymbols.push_back(NULL);
358    return ScopeDIE;
359  }
360
361  const MCSymbol *Start = getLabelBeforeInsn(RI->first);
362  const MCSymbol *End = getLabelAfterInsn(RI->second);
363
364  if (End == 0) return 0;
365
366  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
367  assert(End->isDefined() && "Invalid end label for an inlined scope!");
368
369  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
370  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
371
372  return ScopeDIE;
373}
374
375/// constructInlinedScopeDIE - This scope represents inlined body of
376/// a function. Construct DIE to represent this concrete inlined copy
377/// of the function.
378DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
379                                          LexicalScope *Scope) {
380  const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
381  assert(Ranges.empty() == false &&
382         "LexicalScope does not have instruction markers!");
383
384  if (!Scope->getScopeNode())
385    return NULL;
386  DIScope DS(Scope->getScopeNode());
387  DISubprogram InlinedSP = getDISubprogram(DS);
388  DIE *OriginDIE = TheCU->getDIE(InlinedSP);
389  if (!OriginDIE) {
390    DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
391    return NULL;
392  }
393
394  SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
395  const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
396  const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
397
398  if (StartLabel == 0 || EndLabel == 0) {
399    llvm_unreachable("Unexpected Start and End labels for a inlined scope!");
400  }
401  assert(StartLabel->isDefined() &&
402         "Invalid starting label for an inlined scope!");
403  assert(EndLabel->isDefined() &&
404         "Invalid end label for an inlined scope!");
405
406  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
407  TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
408                     dwarf::DW_FORM_ref4, OriginDIE);
409
410  if (Ranges.size() > 1) {
411    // .debug_range section has not been laid out yet. Emit offset in
412    // .debug_range as a uint, size 4, for now. emitDIE will handle
413    // DW_AT_ranges appropriately.
414    TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
415                   DebugRangeSymbols.size()
416                   * Asm->getTargetData().getPointerSize());
417    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
418         RE = Ranges.end(); RI != RE; ++RI) {
419      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
420      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
421    }
422    DebugRangeSymbols.push_back(NULL);
423    DebugRangeSymbols.push_back(NULL);
424  } else {
425    TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
426                    StartLabel);
427    TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
428                    EndLabel);
429  }
430
431  InlinedSubprogramDIEs.insert(OriginDIE);
432
433  // Track the start label for this inlined function.
434  //.debug_inlined section specification does not clearly state how
435  // to emit inlined scope that is split into multiple instruction ranges.
436  // For now, use first instruction range and emit low_pc/high_pc pair and
437  // corresponding .debug_inlined section entry for this pair.
438  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
439    I = InlineInfo.find(InlinedSP);
440
441  if (I == InlineInfo.end()) {
442    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
443    InlinedSPNodes.push_back(InlinedSP);
444  } else
445    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
446
447  DILocation DL(Scope->getInlinedAt());
448  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
449                 GetOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
450  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
451
452  // Add name to the name table, we do this here because we're guaranteed
453  // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
454  addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
455
456  return ScopeDIE;
457}
458
459/// constructScopeDIE - Construct a DIE for this scope.
460DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
461  if (!Scope || !Scope->getScopeNode())
462    return NULL;
463
464  SmallVector<DIE *, 8> Children;
465
466  // Collect arguments for current function.
467  if (LScopes.isCurrentFunctionScope(Scope))
468    for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
469      if (DbgVariable *ArgDV = CurrentFnArguments[i])
470        if (DIE *Arg =
471            TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
472          Children.push_back(Arg);
473
474  // Collect lexical scope children first.
475  const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
476  for (unsigned i = 0, N = Variables.size(); i < N; ++i)
477    if (DIE *Variable =
478        TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
479      Children.push_back(Variable);
480  const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
481  for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
482    if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
483      Children.push_back(Nested);
484  DIScope DS(Scope->getScopeNode());
485  DIE *ScopeDIE = NULL;
486  if (Scope->getInlinedAt())
487    ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
488  else if (DS.isSubprogram()) {
489    ProcessedSPNodes.insert(DS);
490    if (Scope->isAbstractScope()) {
491      ScopeDIE = TheCU->getDIE(DS);
492      // Note down abstract DIE.
493      if (ScopeDIE)
494        AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
495    }
496    else
497      ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
498  }
499  else {
500    // There is no need to emit empty lexical block DIE.
501    if (Children.empty())
502      return NULL;
503    ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
504  }
505
506  if (!ScopeDIE) return NULL;
507
508  // Add children
509  for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
510         E = Children.end(); I != E; ++I)
511    ScopeDIE->addChild(*I);
512
513  if (DS.isSubprogram())
514    TheCU->addPubTypes(DISubprogram(DS));
515
516  return ScopeDIE;
517}
518
519/// GetOrCreateSourceID - Look up the source id with the given directory and
520/// source file names. If none currently exists, create a new id and insert it
521/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
522/// maps as well.
523unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
524                                         StringRef DirName) {
525  // If FE did not provide a file name, then assume stdin.
526  if (FileName.empty())
527    return GetOrCreateSourceID("<stdin>", StringRef());
528
529  // TODO: this might not belong here. See if we can factor this better.
530  if (DirName == CompilationDir)
531    DirName = "";
532
533  unsigned SrcId = SourceIdMap.size()+1;
534
535  // We look up the file/dir pair by concatenating them with a zero byte.
536  SmallString<128> NamePair;
537  NamePair += DirName;
538  NamePair += '\0'; // Zero bytes are not allowed in paths.
539  NamePair += FileName;
540
541  StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
542  if (Ent.getValue() != SrcId)
543    return Ent.getValue();
544
545  // Print out a .file directive to specify files for .loc directives.
546  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
547
548  return SrcId;
549}
550
551/// constructCompileUnit - Create new CompileUnit for the given
552/// metadata node with tag DW_TAG_compile_unit.
553CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
554  DICompileUnit DIUnit(N);
555  StringRef FN = DIUnit.getFilename();
556  CompilationDir = DIUnit.getDirectory();
557  unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
558
559  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
560  CompileUnit *NewCU = new CompileUnit(ID, DIUnit.getLanguage(), Die, Asm, this);
561  NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
562  NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
563                 DIUnit.getLanguage());
564  NewCU->addString(Die, dwarf::DW_AT_name, FN);
565  // DW_AT_stmt_list is a offset of line number information for this
566  // compile unit in debug_line section.
567  if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
568    NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
569                    Asm->GetTempSymbol("section_line"));
570  else
571    NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
572
573  if (!CompilationDir.empty())
574    NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
575  if (DIUnit.isOptimized())
576    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
577
578  StringRef Flags = DIUnit.getFlags();
579  if (!Flags.empty())
580    NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
581
582  if (unsigned RVer = DIUnit.getRunTimeVersion())
583    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
584            dwarf::DW_FORM_data1, RVer);
585
586  if (!FirstCU)
587    FirstCU = NewCU;
588  CUMap.insert(std::make_pair(N, NewCU));
589  return NewCU;
590}
591
592/// construct SubprogramDIE - Construct subprogram DIE.
593void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
594                                        const MDNode *N) {
595  CompileUnit *&CURef = SPMap[N];
596  if (CURef)
597    return;
598  CURef = TheCU;
599
600  DISubprogram SP(N);
601  if (!SP.isDefinition())
602    // This is a method declaration which will be handled while constructing
603    // class type.
604    return;
605
606  DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
607
608  // Add to map.
609  TheCU->insertDIE(N, SubprogramDie);
610
611  // Add to context owner.
612  TheCU->addToContextOwner(SubprogramDie, SP.getContext());
613
614  return;
615}
616
617/// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
618/// as llvm.dbg.enum and llvm.dbg.ty
619void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
620  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
621    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
622      const MDNode *N = NMD->getOperand(i);
623      if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
624        constructSubprogramDIE(CU, N);
625    }
626
627  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
628    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
629      const MDNode *N = NMD->getOperand(i);
630      if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
631        CU->createGlobalVariableDIE(N);
632    }
633
634  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
635    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
636      DIType Ty(NMD->getOperand(i));
637      if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
638        CU->getOrCreateTypeDIE(Ty);
639    }
640
641  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
642    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
643      DIType Ty(NMD->getOperand(i));
644      if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
645        CU->getOrCreateTypeDIE(Ty);
646    }
647}
648
649/// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
650/// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
651bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
652  DebugInfoFinder DbgFinder;
653  DbgFinder.processModule(*M);
654
655  bool HasDebugInfo = false;
656  // Scan all the compile-units to see if there are any marked as the main
657  // unit. If not, we do not generate debug info.
658  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
659         E = DbgFinder.compile_unit_end(); I != E; ++I) {
660    if (DICompileUnit(*I).isMain()) {
661      HasDebugInfo = true;
662      break;
663    }
664  }
665  if (!HasDebugInfo) return false;
666
667  // Create all the compile unit DIEs.
668  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
669         E = DbgFinder.compile_unit_end(); I != E; ++I)
670    constructCompileUnit(*I);
671
672  // Create DIEs for each global variable.
673  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
674         E = DbgFinder.global_variable_end(); I != E; ++I) {
675    const MDNode *N = *I;
676    if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
677      CU->createGlobalVariableDIE(N);
678  }
679
680  // Create DIEs for each subprogram.
681  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
682         E = DbgFinder.subprogram_end(); I != E; ++I) {
683    const MDNode *N = *I;
684    if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
685      constructSubprogramDIE(CU, N);
686  }
687
688  return HasDebugInfo;
689}
690
691/// beginModule - Emit all Dwarf sections that should come prior to the
692/// content. Create global DIEs and emit initial debug info sections.
693/// This is invoked by the target AsmPrinter.
694void DwarfDebug::beginModule(Module *M) {
695  if (DisableDebugInfoPrinting)
696    return;
697
698  // If module has named metadata anchors then use them, otherwise scan the
699  // module using debug info finder to collect debug info.
700  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
701  if (CU_Nodes) {
702    for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
703      DICompileUnit CUNode(CU_Nodes->getOperand(i));
704      CompileUnit *CU = constructCompileUnit(CUNode);
705      DIArray GVs = CUNode.getGlobalVariables();
706      for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
707        CU->createGlobalVariableDIE(GVs.getElement(i));
708      DIArray SPs = CUNode.getSubprograms();
709      for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
710        constructSubprogramDIE(CU, SPs.getElement(i));
711      DIArray EnumTypes = CUNode.getEnumTypes();
712      for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
713        CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
714      DIArray RetainedTypes = CUNode.getRetainedTypes();
715      for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
716        CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
717    }
718  } else if (!collectLegacyDebugInfo(M))
719    return;
720
721  collectInfoFromNamedMDNodes(M);
722
723  // Tell MMI that we have debug info.
724  MMI->setDebugInfoAvailability(true);
725
726  // Emit initial sections.
727  EmitSectionLabels();
728
729  // Prime section data.
730  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
731}
732
733/// endModule - Emit all Dwarf sections that should come after the content.
734///
735void DwarfDebug::endModule() {
736  if (!FirstCU) return;
737  const Module *M = MMI->getModule();
738  DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
739
740  // Collect info for variables that were optimized out.
741  if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
742    for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
743      DICompileUnit TheCU(CU_Nodes->getOperand(i));
744      DIArray Subprograms = TheCU.getSubprograms();
745      for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
746        DISubprogram SP(Subprograms.getElement(i));
747        if (ProcessedSPNodes.count(SP) != 0) continue;
748        if (!SP.Verify()) continue;
749        if (!SP.isDefinition()) continue;
750        DIArray Variables = SP.getVariables();
751        if (Variables.getNumElements() == 0) continue;
752
753        LexicalScope *Scope =
754          new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
755        DeadFnScopeMap[SP] = Scope;
756
757        // Construct subprogram DIE and add variables DIEs.
758        CompileUnit *SPCU = CUMap.lookup(TheCU);
759        assert(SPCU && "Unable to find Compile Unit!");
760        constructSubprogramDIE(SPCU, SP);
761        DIE *ScopeDIE = SPCU->getDIE(SP);
762        for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
763          DIVariable DV(Variables.getElement(vi));
764          if (!DV.Verify()) continue;
765          DbgVariable *NewVar = new DbgVariable(DV, NULL);
766          if (DIE *VariableDIE =
767              SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
768            ScopeDIE->addChild(VariableDIE);
769        }
770      }
771    }
772  }
773
774  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
775  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
776         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
777    DIE *ISP = *AI;
778    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
779  }
780  for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
781         AE = AbstractSPDies.end(); AI != AE; ++AI) {
782    DIE *ISP = AI->second;
783    if (InlinedSubprogramDIEs.count(ISP))
784      continue;
785    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
786  }
787
788  for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
789         CUE = CUMap.end(); CUI != CUE; ++CUI) {
790    // Emit DW_AT_containing_type attribute to connect types with their
791    // vtable holding type.
792    CompileUnit *TheCU = CUI->second;
793    TheCU->constructContainingTypeDIEs();
794
795    // Emit low_pc and high_pc for CU.
796    DIE *Die = TheCU->getCUDie();
797    if (HasNonTextSection) {
798      // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
799      // into an entity.
800      TheCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
801    } else {
802      TheCU->addLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
803                      Asm->GetTempSymbol("text_begin"));
804      TheCU->addLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
805                      Asm->GetTempSymbol("text_end"));
806    }
807  }
808
809  // Standard sections final addresses.
810  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
811  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
812  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
813  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
814
815  // End text sections.
816  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
817    Asm->OutStreamer.SwitchSection(SectionMap[i]);
818    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
819  }
820
821  // Compute DIE offsets and sizes.
822  computeSizeAndOffsets();
823
824  // Emit all the DIEs into a debug info section
825  emitDebugInfo();
826
827  // Corresponding abbreviations into a abbrev section.
828  emitAbbreviations();
829
830  // Emit info into a dwarf accelerator table sections.
831  if (DwarfAccelTables) {
832    emitAccelNames();
833    emitAccelObjC();
834    emitAccelNamespaces();
835    emitAccelTypes();
836  }
837
838  // Emit info into a debug pubtypes section.
839  emitDebugPubTypes();
840
841  // Emit info into a debug loc section.
842  emitDebugLoc();
843
844  // Emit info into a debug aranges section.
845  EmitDebugARanges();
846
847  // Emit info into a debug ranges section.
848  emitDebugRanges();
849
850  // Emit info into a debug macinfo section.
851  emitDebugMacInfo();
852
853  // Emit inline info.
854  emitDebugInlineInfo();
855
856  // Emit info into a debug str section.
857  emitDebugStr();
858
859  // clean up.
860  DeleteContainerSeconds(DeadFnScopeMap);
861  SPMap.clear();
862  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
863         E = CUMap.end(); I != E; ++I)
864    delete I->second;
865  FirstCU = NULL;  // Reset for the next Module, if any.
866  HasNonTextSection = false;
867}
868
869/// findAbstractVariable - Find abstract variable, if any, associated with Var.
870DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
871                                              DebugLoc ScopeLoc) {
872  LLVMContext &Ctx = DV->getContext();
873  // More then one inlined variable corresponds to one abstract variable.
874  DIVariable Var = cleanseInlinedVariable(DV, Ctx);
875  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
876  if (AbsDbgVariable)
877    return AbsDbgVariable;
878
879  LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
880  if (!Scope)
881    return NULL;
882
883  AbsDbgVariable = new DbgVariable(Var, NULL);
884  addScopeVariable(Scope, AbsDbgVariable);
885  AbstractVariables[Var] = AbsDbgVariable;
886  return AbsDbgVariable;
887}
888
889/// addCurrentFnArgument - If Var is a current function argument then add
890/// it to CurrentFnArguments list.
891bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
892                                      DbgVariable *Var, LexicalScope *Scope) {
893  if (!LScopes.isCurrentFunctionScope(Scope))
894    return false;
895  DIVariable DV = Var->getVariable();
896  if (DV.getTag() != dwarf::DW_TAG_arg_variable)
897    return false;
898  unsigned ArgNo = DV.getArgNumber();
899  if (ArgNo == 0)
900    return false;
901
902  size_t Size = CurrentFnArguments.size();
903  if (Size == 0)
904    CurrentFnArguments.resize(MF->getFunction()->arg_size());
905  // llvm::Function argument size is not good indicator of how many
906  // arguments does the function have at source level.
907  if (ArgNo > Size)
908    CurrentFnArguments.resize(ArgNo * 2);
909  CurrentFnArguments[ArgNo - 1] = Var;
910  return true;
911}
912
913/// collectVariableInfoFromMMITable - Collect variable information from
914/// side table maintained by MMI.
915void
916DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
917                                   SmallPtrSet<const MDNode *, 16> &Processed) {
918  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
919  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
920         VE = VMap.end(); VI != VE; ++VI) {
921    const MDNode *Var = VI->first;
922    if (!Var) continue;
923    Processed.insert(Var);
924    DIVariable DV(Var);
925    const std::pair<unsigned, DebugLoc> &VP = VI->second;
926
927    LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
928
929    // If variable scope is not found then skip this variable.
930    if (Scope == 0)
931      continue;
932
933    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
934    DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
935    RegVar->setFrameIndex(VP.first);
936    if (!addCurrentFnArgument(MF, RegVar, Scope))
937      addScopeVariable(Scope, RegVar);
938    if (AbsDbgVariable)
939      AbsDbgVariable->setFrameIndex(VP.first);
940  }
941}
942
943/// isDbgValueInDefinedReg - Return true if debug value, encoded by
944/// DBG_VALUE instruction, is in a defined reg.
945static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
946  assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
947  return MI->getNumOperands() == 3 &&
948         MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
949         MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
950}
951
952/// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
953/// at MI.
954static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
955                                         const MCSymbol *FLabel,
956                                         const MCSymbol *SLabel,
957                                         const MachineInstr *MI) {
958  const MDNode *Var =  MI->getOperand(MI->getNumOperands() - 1).getMetadata();
959
960  if (MI->getNumOperands() != 3) {
961    MachineLocation MLoc = Asm->getDebugValueLocation(MI);
962    return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
963  }
964  if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
965    MachineLocation MLoc;
966    MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
967    return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
968  }
969  if (MI->getOperand(0).isImm())
970    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
971  if (MI->getOperand(0).isFPImm())
972    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
973  if (MI->getOperand(0).isCImm())
974    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
975
976  llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
977}
978
979/// collectVariableInfo - Find variables for each lexical scope.
980void
981DwarfDebug::collectVariableInfo(const MachineFunction *MF,
982                                SmallPtrSet<const MDNode *, 16> &Processed) {
983
984  /// collection info from MMI table.
985  collectVariableInfoFromMMITable(MF, Processed);
986
987  for (SmallVectorImpl<const MDNode*>::const_iterator
988         UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
989         ++UVI) {
990    const MDNode *Var = *UVI;
991    if (Processed.count(Var))
992      continue;
993
994    // History contains relevant DBG_VALUE instructions for Var and instructions
995    // clobbering it.
996    SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
997    if (History.empty())
998      continue;
999    const MachineInstr *MInsn = History.front();
1000
1001    DIVariable DV(Var);
1002    LexicalScope *Scope = NULL;
1003    if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1004        DISubprogram(DV.getContext()).describes(MF->getFunction()))
1005      Scope = LScopes.getCurrentFunctionScope();
1006    else {
1007      if (DV.getVersion() <= LLVMDebugVersion9)
1008        Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1009      else {
1010        if (MDNode *IA = DV.getInlinedAt())
1011          Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1012        else
1013          Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1014      }
1015    }
1016    // If variable scope is not found then skip this variable.
1017    if (!Scope)
1018      continue;
1019
1020    Processed.insert(DV);
1021    assert(MInsn->isDebugValue() && "History must begin with debug value");
1022    DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1023    DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1024    if (!addCurrentFnArgument(MF, RegVar, Scope))
1025      addScopeVariable(Scope, RegVar);
1026    if (AbsVar)
1027      AbsVar->setMInsn(MInsn);
1028
1029    // Simple ranges that are fully coalesced.
1030    if (History.size() <= 1 || (History.size() == 2 &&
1031                                MInsn->isIdenticalTo(History.back()))) {
1032      RegVar->setMInsn(MInsn);
1033      continue;
1034    }
1035
1036    // handle multiple DBG_VALUE instructions describing one variable.
1037    RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1038
1039    for (SmallVectorImpl<const MachineInstr*>::const_iterator
1040           HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1041      const MachineInstr *Begin = *HI;
1042      assert(Begin->isDebugValue() && "Invalid History entry");
1043
1044      // Check if DBG_VALUE is truncating a range.
1045      if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1046          && !Begin->getOperand(0).getReg())
1047        continue;
1048
1049      // Compute the range for a register location.
1050      const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1051      const MCSymbol *SLabel = 0;
1052
1053      if (HI + 1 == HE)
1054        // If Begin is the last instruction in History then its value is valid
1055        // until the end of the function.
1056        SLabel = FunctionEndSym;
1057      else {
1058        const MachineInstr *End = HI[1];
1059        DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1060              << "\t" << *Begin << "\t" << *End << "\n");
1061        if (End->isDebugValue())
1062          SLabel = getLabelBeforeInsn(End);
1063        else {
1064          // End is a normal instruction clobbering the range.
1065          SLabel = getLabelAfterInsn(End);
1066          assert(SLabel && "Forgot label after clobber instruction");
1067          ++HI;
1068        }
1069      }
1070
1071      // The value is valid until the next DBG_VALUE or clobber.
1072      DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1073                                                    Begin));
1074    }
1075    DotDebugLocEntries.push_back(DotDebugLocEntry());
1076  }
1077
1078  // Collect info for variables that were optimized out.
1079  LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1080  DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1081  for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1082    DIVariable DV(Variables.getElement(i));
1083    if (!DV || !DV.Verify() || !Processed.insert(DV))
1084      continue;
1085    if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1086      addScopeVariable(Scope, new DbgVariable(DV, NULL));
1087  }
1088}
1089
1090/// getLabelBeforeInsn - Return Label preceding the instruction.
1091const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1092  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1093  assert(Label && "Didn't insert label before instruction");
1094  return Label;
1095}
1096
1097/// getLabelAfterInsn - Return Label immediately following the instruction.
1098const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1099  return LabelsAfterInsn.lookup(MI);
1100}
1101
1102/// beginInstruction - Process beginning of an instruction.
1103void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1104  // Check if source location changes, but ignore DBG_VALUE locations.
1105  if (!MI->isDebugValue()) {
1106    DebugLoc DL = MI->getDebugLoc();
1107    if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1108      unsigned Flags = 0;
1109      PrevInstLoc = DL;
1110      if (DL == PrologEndLoc) {
1111        Flags |= DWARF2_FLAG_PROLOGUE_END;
1112        PrologEndLoc = DebugLoc();
1113      }
1114      if (PrologEndLoc.isUnknown())
1115        Flags |= DWARF2_FLAG_IS_STMT;
1116
1117      if (!DL.isUnknown()) {
1118        const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1119        recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1120      } else
1121        recordSourceLine(0, 0, 0, 0);
1122    }
1123  }
1124
1125  // Insert labels where requested.
1126  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1127    LabelsBeforeInsn.find(MI);
1128
1129  // No label needed.
1130  if (I == LabelsBeforeInsn.end())
1131    return;
1132
1133  // Label already assigned.
1134  if (I->second)
1135    return;
1136
1137  if (!PrevLabel) {
1138    PrevLabel = MMI->getContext().CreateTempSymbol();
1139    Asm->OutStreamer.EmitLabel(PrevLabel);
1140  }
1141  I->second = PrevLabel;
1142}
1143
1144/// endInstruction - Process end of an instruction.
1145void DwarfDebug::endInstruction(const MachineInstr *MI) {
1146  // Don't create a new label after DBG_VALUE instructions.
1147  // They don't generate code.
1148  if (!MI->isDebugValue())
1149    PrevLabel = 0;
1150
1151  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1152    LabelsAfterInsn.find(MI);
1153
1154  // No label needed.
1155  if (I == LabelsAfterInsn.end())
1156    return;
1157
1158  // Label already assigned.
1159  if (I->second)
1160    return;
1161
1162  // We need a label after this instruction.
1163  if (!PrevLabel) {
1164    PrevLabel = MMI->getContext().CreateTempSymbol();
1165    Asm->OutStreamer.EmitLabel(PrevLabel);
1166  }
1167  I->second = PrevLabel;
1168}
1169
1170/// identifyScopeMarkers() -
1171/// Each LexicalScope has first instruction and last instruction to mark
1172/// beginning and end of a scope respectively. Create an inverse map that list
1173/// scopes starts (and ends) with an instruction. One instruction may start (or
1174/// end) multiple scopes. Ignore scopes that are not reachable.
1175void DwarfDebug::identifyScopeMarkers() {
1176  SmallVector<LexicalScope *, 4> WorkList;
1177  WorkList.push_back(LScopes.getCurrentFunctionScope());
1178  while (!WorkList.empty()) {
1179    LexicalScope *S = WorkList.pop_back_val();
1180
1181    const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1182    if (!Children.empty())
1183      for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1184             SE = Children.end(); SI != SE; ++SI)
1185        WorkList.push_back(*SI);
1186
1187    if (S->isAbstractScope())
1188      continue;
1189
1190    const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1191    if (Ranges.empty())
1192      continue;
1193    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1194           RE = Ranges.end(); RI != RE; ++RI) {
1195      assert(RI->first && "InsnRange does not have first instruction!");
1196      assert(RI->second && "InsnRange does not have second instruction!");
1197      requestLabelBeforeInsn(RI->first);
1198      requestLabelAfterInsn(RI->second);
1199    }
1200  }
1201}
1202
1203/// getScopeNode - Get MDNode for DebugLoc's scope.
1204static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1205  if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1206    return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1207  return DL.getScope(Ctx);
1208}
1209
1210/// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1211/// line number info for the function.
1212static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1213  const MDNode *Scope = getScopeNode(DL, Ctx);
1214  DISubprogram SP = getDISubprogram(Scope);
1215  if (SP.Verify()) {
1216    // Check for number of operands since the compatibility is
1217    // cheap here.
1218    if (SP->getNumOperands() > 19)
1219      return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1220    else
1221      return DebugLoc::get(SP.getLineNumber(), 0, SP);
1222  }
1223
1224  return DebugLoc();
1225}
1226
1227/// beginFunction - Gather pre-function debug information.  Assumes being
1228/// emitted immediately after the function entry point.
1229void DwarfDebug::beginFunction(const MachineFunction *MF) {
1230  if (!MMI->hasDebugInfo()) return;
1231  LScopes.initialize(*MF);
1232  if (LScopes.empty()) return;
1233  identifyScopeMarkers();
1234
1235  if (!Asm->getCurrentSection()->getKind().isText())
1236    HasNonTextSection = true;
1237
1238  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1239                                        Asm->getFunctionNumber());
1240  // Assumes in correct section after the entry point.
1241  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1242
1243  assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1244
1245  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1246  /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1247  std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1248
1249  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1250       I != E; ++I) {
1251    bool AtBlockEntry = true;
1252    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1253         II != IE; ++II) {
1254      const MachineInstr *MI = II;
1255
1256      if (MI->isDebugValue()) {
1257        assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1258
1259        // Keep track of user variables.
1260        const MDNode *Var =
1261          MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1262
1263        // Variable is in a register, we need to check for clobbers.
1264        if (isDbgValueInDefinedReg(MI))
1265          LiveUserVar[MI->getOperand(0).getReg()] = Var;
1266
1267        // Check the history of this variable.
1268        SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1269        if (History.empty()) {
1270          UserVariables.push_back(Var);
1271          // The first mention of a function argument gets the FunctionBeginSym
1272          // label, so arguments are visible when breaking at function entry.
1273          DIVariable DV(Var);
1274          if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1275              DISubprogram(getDISubprogram(DV.getContext()))
1276                .describes(MF->getFunction()))
1277            LabelsBeforeInsn[MI] = FunctionBeginSym;
1278        } else {
1279          // We have seen this variable before. Try to coalesce DBG_VALUEs.
1280          const MachineInstr *Prev = History.back();
1281          if (Prev->isDebugValue()) {
1282            // Coalesce identical entries at the end of History.
1283            if (History.size() >= 2 &&
1284                Prev->isIdenticalTo(History[History.size() - 2])) {
1285              DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1286                    << "\t" << *Prev
1287                    << "\t" << *History[History.size() - 2] << "\n");
1288              History.pop_back();
1289            }
1290
1291            // Terminate old register assignments that don't reach MI;
1292            MachineFunction::const_iterator PrevMBB = Prev->getParent();
1293            if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1294                isDbgValueInDefinedReg(Prev)) {
1295              // Previous register assignment needs to terminate at the end of
1296              // its basic block.
1297              MachineBasicBlock::const_iterator LastMI =
1298                PrevMBB->getLastNonDebugInstr();
1299              if (LastMI == PrevMBB->end()) {
1300                // Drop DBG_VALUE for empty range.
1301                DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1302                      << "\t" << *Prev << "\n");
1303                History.pop_back();
1304              }
1305              else {
1306                // Terminate after LastMI.
1307                History.push_back(LastMI);
1308              }
1309            }
1310          }
1311        }
1312        History.push_back(MI);
1313      } else {
1314        // Not a DBG_VALUE instruction.
1315        if (!MI->isLabel())
1316          AtBlockEntry = false;
1317
1318        // First known non DBG_VALUE location marks beginning of function
1319        // body.
1320        if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1321          PrologEndLoc = MI->getDebugLoc();
1322
1323        // Check if the instruction clobbers any registers with debug vars.
1324        for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1325               MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1326          if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1327            continue;
1328          for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1329               AI.isValid(); ++AI) {
1330            unsigned Reg = *AI;
1331            const MDNode *Var = LiveUserVar[Reg];
1332            if (!Var)
1333              continue;
1334            // Reg is now clobbered.
1335            LiveUserVar[Reg] = 0;
1336
1337            // Was MD last defined by a DBG_VALUE referring to Reg?
1338            DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1339            if (HistI == DbgValues.end())
1340              continue;
1341            SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1342            if (History.empty())
1343              continue;
1344            const MachineInstr *Prev = History.back();
1345            // Sanity-check: Register assignments are terminated at the end of
1346            // their block.
1347            if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1348              continue;
1349            // Is the variable still in Reg?
1350            if (!isDbgValueInDefinedReg(Prev) ||
1351                Prev->getOperand(0).getReg() != Reg)
1352              continue;
1353            // Var is clobbered. Make sure the next instruction gets a label.
1354            History.push_back(MI);
1355          }
1356        }
1357      }
1358    }
1359  }
1360
1361  for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1362       I != E; ++I) {
1363    SmallVectorImpl<const MachineInstr*> &History = I->second;
1364    if (History.empty())
1365      continue;
1366
1367    // Make sure the final register assignments are terminated.
1368    const MachineInstr *Prev = History.back();
1369    if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1370      const MachineBasicBlock *PrevMBB = Prev->getParent();
1371      MachineBasicBlock::const_iterator LastMI =
1372        PrevMBB->getLastNonDebugInstr();
1373      if (LastMI == PrevMBB->end())
1374        // Drop DBG_VALUE for empty range.
1375        History.pop_back();
1376      else {
1377        // Terminate after LastMI.
1378        History.push_back(LastMI);
1379      }
1380    }
1381    // Request labels for the full history.
1382    for (unsigned i = 0, e = History.size(); i != e; ++i) {
1383      const MachineInstr *MI = History[i];
1384      if (MI->isDebugValue())
1385        requestLabelBeforeInsn(MI);
1386      else
1387        requestLabelAfterInsn(MI);
1388    }
1389  }
1390
1391  PrevInstLoc = DebugLoc();
1392  PrevLabel = FunctionBeginSym;
1393
1394  // Record beginning of function.
1395  if (!PrologEndLoc.isUnknown()) {
1396    DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1397                                       MF->getFunction()->getContext());
1398    recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1399                     FnStartDL.getScope(MF->getFunction()->getContext()),
1400                     DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0);
1401  }
1402}
1403
1404void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1405//  SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1406  ScopeVariables[LS].push_back(Var);
1407//  Vars.push_back(Var);
1408}
1409
1410/// endFunction - Gather and emit post-function debug information.
1411///
1412void DwarfDebug::endFunction(const MachineFunction *MF) {
1413  if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1414
1415  // Define end label for subprogram.
1416  FunctionEndSym = Asm->GetTempSymbol("func_end",
1417                                      Asm->getFunctionNumber());
1418  // Assumes in correct section after the entry point.
1419  Asm->OutStreamer.EmitLabel(FunctionEndSym);
1420
1421  SmallPtrSet<const MDNode *, 16> ProcessedVars;
1422  collectVariableInfo(MF, ProcessedVars);
1423
1424  LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1425  CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1426  assert(TheCU && "Unable to find compile unit!");
1427
1428  // Construct abstract scopes.
1429  ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1430  for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1431    LexicalScope *AScope = AList[i];
1432    DISubprogram SP(AScope->getScopeNode());
1433    if (SP.Verify()) {
1434      // Collect info for variables that were optimized out.
1435      DIArray Variables = SP.getVariables();
1436      for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1437        DIVariable DV(Variables.getElement(i));
1438        if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1439          continue;
1440        // Check that DbgVariable for DV wasn't created earlier, when
1441        // findAbstractVariable() was called for inlined instance of DV.
1442        LLVMContext &Ctx = DV->getContext();
1443        DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1444        if (AbstractVariables.lookup(CleanDV))
1445          continue;
1446        if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1447          addScopeVariable(Scope, new DbgVariable(DV, NULL));
1448      }
1449    }
1450    if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1451      constructScopeDIE(TheCU, AScope);
1452  }
1453
1454  DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1455
1456  if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1457    TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1458                   dwarf::DW_FORM_flag, 1);
1459
1460  DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1461                                               MMI->getFrameMoves()));
1462
1463  // Clear debug info
1464  for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1465         I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1466    DeleteContainerPointers(I->second);
1467  ScopeVariables.clear();
1468  DeleteContainerPointers(CurrentFnArguments);
1469  UserVariables.clear();
1470  DbgValues.clear();
1471  AbstractVariables.clear();
1472  LabelsBeforeInsn.clear();
1473  LabelsAfterInsn.clear();
1474  PrevLabel = NULL;
1475}
1476
1477/// recordSourceLine - Register a source line with debug info. Returns the
1478/// unique label that was emitted and which provides correspondence to
1479/// the source line list.
1480void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1481                                  unsigned Flags) {
1482  StringRef Fn;
1483  StringRef Dir;
1484  unsigned Src = 1;
1485  if (S) {
1486    DIDescriptor Scope(S);
1487
1488    if (Scope.isCompileUnit()) {
1489      DICompileUnit CU(S);
1490      Fn = CU.getFilename();
1491      Dir = CU.getDirectory();
1492    } else if (Scope.isFile()) {
1493      DIFile F(S);
1494      Fn = F.getFilename();
1495      Dir = F.getDirectory();
1496    } else if (Scope.isSubprogram()) {
1497      DISubprogram SP(S);
1498      Fn = SP.getFilename();
1499      Dir = SP.getDirectory();
1500    } else if (Scope.isLexicalBlockFile()) {
1501      DILexicalBlockFile DBF(S);
1502      Fn = DBF.getFilename();
1503      Dir = DBF.getDirectory();
1504    } else if (Scope.isLexicalBlock()) {
1505      DILexicalBlock DB(S);
1506      Fn = DB.getFilename();
1507      Dir = DB.getDirectory();
1508    } else
1509      llvm_unreachable("Unexpected scope info");
1510
1511    Src = GetOrCreateSourceID(Fn, Dir);
1512  }
1513  Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1514}
1515
1516//===----------------------------------------------------------------------===//
1517// Emit Methods
1518//===----------------------------------------------------------------------===//
1519
1520/// computeSizeAndOffset - Compute the size and offset of a DIE.
1521///
1522unsigned
1523DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1524  // Get the children.
1525  const std::vector<DIE *> &Children = Die->getChildren();
1526
1527  // Record the abbreviation.
1528  assignAbbrevNumber(Die->getAbbrev());
1529
1530  // Get the abbreviation for this DIE.
1531  unsigned AbbrevNumber = Die->getAbbrevNumber();
1532  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1533
1534  // Set DIE offset
1535  Die->setOffset(Offset);
1536
1537  // Start the size with the size of abbreviation code.
1538  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1539
1540  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1541  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1542
1543  // Size the DIE attribute values.
1544  for (unsigned i = 0, N = Values.size(); i < N; ++i)
1545    // Size attribute value.
1546    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1547
1548  // Size the DIE children if any.
1549  if (!Children.empty()) {
1550    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1551           "Children flag not set");
1552
1553    for (unsigned j = 0, M = Children.size(); j < M; ++j)
1554      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1555
1556    // End of children marker.
1557    Offset += sizeof(int8_t);
1558  }
1559
1560  Die->setSize(Offset - Die->getOffset());
1561  return Offset;
1562}
1563
1564/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1565///
1566void DwarfDebug::computeSizeAndOffsets() {
1567  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1568         E = CUMap.end(); I != E; ++I) {
1569    // Compute size of compile unit header.
1570    unsigned Offset =
1571      sizeof(int32_t) + // Length of Compilation Unit Info
1572      sizeof(int16_t) + // DWARF version number
1573      sizeof(int32_t) + // Offset Into Abbrev. Section
1574      sizeof(int8_t);   // Pointer Size (in bytes)
1575    computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1576  }
1577}
1578
1579/// EmitSectionLabels - Emit initial Dwarf sections with a label at
1580/// the start of each one.
1581void DwarfDebug::EmitSectionLabels() {
1582  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1583
1584  // Dwarf sections base addresses.
1585  DwarfInfoSectionSym =
1586    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1587  DwarfAbbrevSectionSym =
1588    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1589  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1590
1591  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1592    EmitSectionSym(Asm, MacroInfo);
1593
1594  EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1595  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1596  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1597  DwarfStrSectionSym =
1598    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1599  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1600                                             "debug_range");
1601
1602  DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1603                                           "section_debug_loc");
1604
1605  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1606  EmitSectionSym(Asm, TLOF.getDataSection());
1607}
1608
1609/// emitDIE - Recursively emits a debug information entry.
1610///
1611void DwarfDebug::emitDIE(DIE *Die) {
1612  // Get the abbreviation for this DIE.
1613  unsigned AbbrevNumber = Die->getAbbrevNumber();
1614  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1615
1616  // Emit the code (index) for the abbreviation.
1617  if (Asm->isVerbose())
1618    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1619                                Twine::utohexstr(Die->getOffset()) + ":0x" +
1620                                Twine::utohexstr(Die->getSize()) + " " +
1621                                dwarf::TagString(Abbrev->getTag()));
1622  Asm->EmitULEB128(AbbrevNumber);
1623
1624  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1625  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1626
1627  // Emit the DIE attribute values.
1628  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1629    unsigned Attr = AbbrevData[i].getAttribute();
1630    unsigned Form = AbbrevData[i].getForm();
1631    assert(Form && "Too many attributes for DIE (check abbreviation)");
1632
1633    if (Asm->isVerbose())
1634      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1635
1636    switch (Attr) {
1637    case dwarf::DW_AT_abstract_origin: {
1638      DIEEntry *E = cast<DIEEntry>(Values[i]);
1639      DIE *Origin = E->getEntry();
1640      unsigned Addr = Origin->getOffset();
1641      Asm->EmitInt32(Addr);
1642      break;
1643    }
1644    case dwarf::DW_AT_ranges: {
1645      // DW_AT_range Value encodes offset in debug_range section.
1646      DIEInteger *V = cast<DIEInteger>(Values[i]);
1647
1648      if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1649        Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1650                                 V->getValue(),
1651                                 4);
1652      } else {
1653        Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1654                                       V->getValue(),
1655                                       DwarfDebugRangeSectionSym,
1656                                       4);
1657      }
1658      break;
1659    }
1660    case dwarf::DW_AT_location: {
1661      if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1662        if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1663          Asm->EmitLabelReference(L->getValue(), 4);
1664        else
1665          Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1666      } else {
1667        Values[i]->EmitValue(Asm, Form);
1668      }
1669      break;
1670    }
1671    case dwarf::DW_AT_accessibility: {
1672      if (Asm->isVerbose()) {
1673        DIEInteger *V = cast<DIEInteger>(Values[i]);
1674        Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1675      }
1676      Values[i]->EmitValue(Asm, Form);
1677      break;
1678    }
1679    default:
1680      // Emit an attribute using the defined form.
1681      Values[i]->EmitValue(Asm, Form);
1682      break;
1683    }
1684  }
1685
1686  // Emit the DIE children if any.
1687  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1688    const std::vector<DIE *> &Children = Die->getChildren();
1689
1690    for (unsigned j = 0, M = Children.size(); j < M; ++j)
1691      emitDIE(Children[j]);
1692
1693    if (Asm->isVerbose())
1694      Asm->OutStreamer.AddComment("End Of Children Mark");
1695    Asm->EmitInt8(0);
1696  }
1697}
1698
1699/// emitDebugInfo - Emit the debug info section.
1700///
1701void DwarfDebug::emitDebugInfo() {
1702  // Start debug info section.
1703  Asm->OutStreamer.SwitchSection(
1704                            Asm->getObjFileLowering().getDwarfInfoSection());
1705  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1706         E = CUMap.end(); I != E; ++I) {
1707    CompileUnit *TheCU = I->second;
1708    DIE *Die = TheCU->getCUDie();
1709
1710    // Emit the compile units header.
1711    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1712                                                  TheCU->getID()));
1713
1714    // Emit size of content not including length itself
1715    unsigned ContentSize = Die->getSize() +
1716      sizeof(int16_t) + // DWARF version number
1717      sizeof(int32_t) + // Offset Into Abbrev. Section
1718      sizeof(int8_t);   // Pointer Size (in bytes)
1719
1720    Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1721    Asm->EmitInt32(ContentSize);
1722    Asm->OutStreamer.AddComment("DWARF version number");
1723    Asm->EmitInt16(dwarf::DWARF_VERSION);
1724    Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1725    Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1726                           DwarfAbbrevSectionSym);
1727    Asm->OutStreamer.AddComment("Address Size (in bytes)");
1728    Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1729
1730    emitDIE(Die);
1731    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1732  }
1733}
1734
1735/// emitAbbreviations - Emit the abbreviation section.
1736///
1737void DwarfDebug::emitAbbreviations() const {
1738  // Check to see if it is worth the effort.
1739  if (!Abbreviations.empty()) {
1740    // Start the debug abbrev section.
1741    Asm->OutStreamer.SwitchSection(
1742                            Asm->getObjFileLowering().getDwarfAbbrevSection());
1743
1744    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1745
1746    // For each abbrevation.
1747    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1748      // Get abbreviation data
1749      const DIEAbbrev *Abbrev = Abbreviations[i];
1750
1751      // Emit the abbrevations code (base 1 index.)
1752      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1753
1754      // Emit the abbreviations data.
1755      Abbrev->Emit(Asm);
1756    }
1757
1758    // Mark end of abbreviations.
1759    Asm->EmitULEB128(0, "EOM(3)");
1760
1761    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1762  }
1763}
1764
1765/// emitEndOfLineMatrix - Emit the last address of the section and the end of
1766/// the line matrix.
1767///
1768void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1769  // Define last address of section.
1770  Asm->OutStreamer.AddComment("Extended Op");
1771  Asm->EmitInt8(0);
1772
1773  Asm->OutStreamer.AddComment("Op size");
1774  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1775  Asm->OutStreamer.AddComment("DW_LNE_set_address");
1776  Asm->EmitInt8(dwarf::DW_LNE_set_address);
1777
1778  Asm->OutStreamer.AddComment("Section end label");
1779
1780  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1781                                   Asm->getTargetData().getPointerSize(),
1782                                   0/*AddrSpace*/);
1783
1784  // Mark end of matrix.
1785  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1786  Asm->EmitInt8(0);
1787  Asm->EmitInt8(1);
1788  Asm->EmitInt8(1);
1789}
1790
1791/// emitAccelNames - Emit visible names into a hashed accelerator table
1792/// section.
1793void DwarfDebug::emitAccelNames() {
1794  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1795                                           dwarf::DW_FORM_data4));
1796  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1797         E = CUMap.end(); I != E; ++I) {
1798    CompileUnit *TheCU = I->second;
1799    const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1800    for (StringMap<std::vector<DIE*> >::const_iterator
1801           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1802      const char *Name = GI->getKeyData();
1803      const std::vector<DIE *> &Entities = GI->second;
1804      for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1805             DE = Entities.end(); DI != DE; ++DI)
1806        AT.AddName(Name, (*DI));
1807    }
1808  }
1809
1810  AT.FinalizeTable(Asm, "Names");
1811  Asm->OutStreamer.SwitchSection(
1812    Asm->getObjFileLowering().getDwarfAccelNamesSection());
1813  MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1814  Asm->OutStreamer.EmitLabel(SectionBegin);
1815
1816  // Emit the full data.
1817  AT.Emit(Asm, SectionBegin, this);
1818}
1819
1820/// emitAccelObjC - Emit objective C classes and categories into a hashed
1821/// accelerator table section.
1822void DwarfDebug::emitAccelObjC() {
1823  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1824                                           dwarf::DW_FORM_data4));
1825  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1826         E = CUMap.end(); I != E; ++I) {
1827    CompileUnit *TheCU = I->second;
1828    const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1829    for (StringMap<std::vector<DIE*> >::const_iterator
1830           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1831      const char *Name = GI->getKeyData();
1832      const std::vector<DIE *> &Entities = GI->second;
1833      for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1834             DE = Entities.end(); DI != DE; ++DI)
1835        AT.AddName(Name, (*DI));
1836    }
1837  }
1838
1839  AT.FinalizeTable(Asm, "ObjC");
1840  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1841                                 .getDwarfAccelObjCSection());
1842  MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1843  Asm->OutStreamer.EmitLabel(SectionBegin);
1844
1845  // Emit the full data.
1846  AT.Emit(Asm, SectionBegin, this);
1847}
1848
1849/// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1850/// table.
1851void DwarfDebug::emitAccelNamespaces() {
1852  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1853                                           dwarf::DW_FORM_data4));
1854  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1855         E = CUMap.end(); I != E; ++I) {
1856    CompileUnit *TheCU = I->second;
1857    const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
1858    for (StringMap<std::vector<DIE*> >::const_iterator
1859           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1860      const char *Name = GI->getKeyData();
1861      const std::vector<DIE *> &Entities = GI->second;
1862      for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1863             DE = Entities.end(); DI != DE; ++DI)
1864        AT.AddName(Name, (*DI));
1865    }
1866  }
1867
1868  AT.FinalizeTable(Asm, "namespac");
1869  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1870                                 .getDwarfAccelNamespaceSection());
1871  MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1872  Asm->OutStreamer.EmitLabel(SectionBegin);
1873
1874  // Emit the full data.
1875  AT.Emit(Asm, SectionBegin, this);
1876}
1877
1878/// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1879void DwarfDebug::emitAccelTypes() {
1880  std::vector<DwarfAccelTable::Atom> Atoms;
1881  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1882                                        dwarf::DW_FORM_data4));
1883  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
1884                                        dwarf::DW_FORM_data2));
1885  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
1886                                        dwarf::DW_FORM_data1));
1887  DwarfAccelTable AT(Atoms);
1888  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1889         E = CUMap.end(); I != E; ++I) {
1890    CompileUnit *TheCU = I->second;
1891    const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
1892      = TheCU->getAccelTypes();
1893    for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
1894           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1895      const char *Name = GI->getKeyData();
1896      const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
1897      for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
1898             = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
1899        AT.AddName(Name, (*DI).first, (*DI).second);
1900    }
1901  }
1902
1903  AT.FinalizeTable(Asm, "types");
1904  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1905                                 .getDwarfAccelTypesSection());
1906  MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1907  Asm->OutStreamer.EmitLabel(SectionBegin);
1908
1909  // Emit the full data.
1910  AT.Emit(Asm, SectionBegin, this);
1911}
1912
1913void DwarfDebug::emitDebugPubTypes() {
1914  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1915         E = CUMap.end(); I != E; ++I) {
1916    CompileUnit *TheCU = I->second;
1917    // Start the dwarf pubtypes section.
1918    Asm->OutStreamer.SwitchSection(
1919      Asm->getObjFileLowering().getDwarfPubTypesSection());
1920    Asm->OutStreamer.AddComment("Length of Public Types Info");
1921    Asm->EmitLabelDifference(
1922      Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1923      Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1924
1925    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1926                                                  TheCU->getID()));
1927
1928    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1929    Asm->EmitInt16(dwarf::DWARF_VERSION);
1930
1931    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1932    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1933                           DwarfInfoSectionSym);
1934
1935    Asm->OutStreamer.AddComment("Compilation Unit Length");
1936    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1937                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
1938                             4);
1939
1940    const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1941    for (StringMap<DIE*>::const_iterator
1942           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1943      const char *Name = GI->getKeyData();
1944      DIE *Entity = GI->second;
1945
1946      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1947      Asm->EmitInt32(Entity->getOffset());
1948
1949      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1950      // Emit the name with a terminating null byte.
1951      Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1952    }
1953
1954    Asm->OutStreamer.AddComment("End Mark");
1955    Asm->EmitInt32(0);
1956    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1957                                                  TheCU->getID()));
1958  }
1959}
1960
1961/// emitDebugStr - Emit visible names into a debug str section.
1962///
1963void DwarfDebug::emitDebugStr() {
1964  // Check to see if it is worth the effort.
1965  if (StringPool.empty()) return;
1966
1967  // Start the dwarf str section.
1968  Asm->OutStreamer.SwitchSection(
1969                                Asm->getObjFileLowering().getDwarfStrSection());
1970
1971  // Get all of the string pool entries and put them in an array by their ID so
1972  // we can sort them.
1973  SmallVector<std::pair<unsigned,
1974      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1975
1976  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1977       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1978    Entries.push_back(std::make_pair(I->second.second, &*I));
1979
1980  array_pod_sort(Entries.begin(), Entries.end());
1981
1982  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1983    // Emit a label for reference from debug information entries.
1984    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1985
1986    // Emit the string itself with a terminating null byte.
1987    Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
1988                                         Entries[i].second->getKeyLength()+1),
1989                               0/*addrspace*/);
1990  }
1991}
1992
1993/// emitDebugLoc - Emit visible names into a debug loc section.
1994///
1995void DwarfDebug::emitDebugLoc() {
1996  if (DotDebugLocEntries.empty())
1997    return;
1998
1999  for (SmallVector<DotDebugLocEntry, 4>::iterator
2000         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2001       I != E; ++I) {
2002    DotDebugLocEntry &Entry = *I;
2003    if (I + 1 != DotDebugLocEntries.end())
2004      Entry.Merge(I+1);
2005  }
2006
2007  // Start the dwarf loc section.
2008  Asm->OutStreamer.SwitchSection(
2009    Asm->getObjFileLowering().getDwarfLocSection());
2010  unsigned char Size = Asm->getTargetData().getPointerSize();
2011  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2012  unsigned index = 1;
2013  for (SmallVector<DotDebugLocEntry, 4>::iterator
2014         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2015       I != E; ++I, ++index) {
2016    DotDebugLocEntry &Entry = *I;
2017    if (Entry.isMerged()) continue;
2018    if (Entry.isEmpty()) {
2019      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2020      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2021      Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2022    } else {
2023      Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2024      Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2025      DIVariable DV(Entry.Variable);
2026      Asm->OutStreamer.AddComment("Loc expr size");
2027      MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2028      MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2029      Asm->EmitLabelDifference(end, begin, 2);
2030      Asm->OutStreamer.EmitLabel(begin);
2031      if (Entry.isInt()) {
2032        DIBasicType BTy(DV.getType());
2033        if (BTy.Verify() &&
2034            (BTy.getEncoding()  == dwarf::DW_ATE_signed
2035             || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2036          Asm->OutStreamer.AddComment("DW_OP_consts");
2037          Asm->EmitInt8(dwarf::DW_OP_consts);
2038          Asm->EmitSLEB128(Entry.getInt());
2039        } else {
2040          Asm->OutStreamer.AddComment("DW_OP_constu");
2041          Asm->EmitInt8(dwarf::DW_OP_constu);
2042          Asm->EmitULEB128(Entry.getInt());
2043        }
2044      } else if (Entry.isLocation()) {
2045        if (!DV.hasComplexAddress())
2046          // Regular entry.
2047          Asm->EmitDwarfRegOp(Entry.Loc);
2048        else {
2049          // Complex address entry.
2050          unsigned N = DV.getNumAddrElements();
2051          unsigned i = 0;
2052          if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2053            if (Entry.Loc.getOffset()) {
2054              i = 2;
2055              Asm->EmitDwarfRegOp(Entry.Loc);
2056              Asm->OutStreamer.AddComment("DW_OP_deref");
2057              Asm->EmitInt8(dwarf::DW_OP_deref);
2058              Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2059              Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2060              Asm->EmitSLEB128(DV.getAddrElement(1));
2061            } else {
2062              // If first address element is OpPlus then emit
2063              // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2064              MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2065              Asm->EmitDwarfRegOp(Loc);
2066              i = 2;
2067            }
2068          } else {
2069            Asm->EmitDwarfRegOp(Entry.Loc);
2070          }
2071
2072          // Emit remaining complex address elements.
2073          for (; i < N; ++i) {
2074            uint64_t Element = DV.getAddrElement(i);
2075            if (Element == DIBuilder::OpPlus) {
2076              Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2077              Asm->EmitULEB128(DV.getAddrElement(++i));
2078            } else if (Element == DIBuilder::OpDeref) {
2079              if (!Entry.Loc.isReg())
2080                Asm->EmitInt8(dwarf::DW_OP_deref);
2081            } else
2082              llvm_unreachable("unknown Opcode found in complex address");
2083          }
2084        }
2085      }
2086      // else ... ignore constant fp. There is not any good way to
2087      // to represent them here in dwarf.
2088      Asm->OutStreamer.EmitLabel(end);
2089    }
2090  }
2091}
2092
2093/// EmitDebugARanges - Emit visible names into a debug aranges section.
2094///
2095void DwarfDebug::EmitDebugARanges() {
2096  // Start the dwarf aranges section.
2097  Asm->OutStreamer.SwitchSection(
2098                          Asm->getObjFileLowering().getDwarfARangesSection());
2099}
2100
2101/// emitDebugRanges - Emit visible names into a debug ranges section.
2102///
2103void DwarfDebug::emitDebugRanges() {
2104  // Start the dwarf ranges section.
2105  Asm->OutStreamer.SwitchSection(
2106    Asm->getObjFileLowering().getDwarfRangesSection());
2107  unsigned char Size = Asm->getTargetData().getPointerSize();
2108  for (SmallVector<const MCSymbol *, 8>::iterator
2109         I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2110       I != E; ++I) {
2111    if (*I)
2112      Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2113    else
2114      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2115  }
2116}
2117
2118/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2119///
2120void DwarfDebug::emitDebugMacInfo() {
2121  if (const MCSection *LineInfo =
2122      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2123    // Start the dwarf macinfo section.
2124    Asm->OutStreamer.SwitchSection(LineInfo);
2125  }
2126}
2127
2128/// emitDebugInlineInfo - Emit inline info using following format.
2129/// Section Header:
2130/// 1. length of section
2131/// 2. Dwarf version number
2132/// 3. address size.
2133///
2134/// Entries (one "entry" for each function that was inlined):
2135///
2136/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2137///   otherwise offset into __debug_str for regular function name.
2138/// 2. offset into __debug_str section for regular function name.
2139/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2140/// instances for the function.
2141///
2142/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2143/// inlined instance; the die_offset points to the inlined_subroutine die in the
2144/// __debug_info section, and the low_pc is the starting address for the
2145/// inlining instance.
2146void DwarfDebug::emitDebugInlineInfo() {
2147  if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2148    return;
2149
2150  if (!FirstCU)
2151    return;
2152
2153  Asm->OutStreamer.SwitchSection(
2154                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
2155
2156  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2157  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2158                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2159
2160  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2161
2162  Asm->OutStreamer.AddComment("Dwarf Version");
2163  Asm->EmitInt16(dwarf::DWARF_VERSION);
2164  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2165  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2166
2167  for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2168         E = InlinedSPNodes.end(); I != E; ++I) {
2169
2170    const MDNode *Node = *I;
2171    DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2172      = InlineInfo.find(Node);
2173    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2174    DISubprogram SP(Node);
2175    StringRef LName = SP.getLinkageName();
2176    StringRef Name = SP.getName();
2177
2178    Asm->OutStreamer.AddComment("MIPS linkage name");
2179    if (LName.empty())
2180      Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2181    else
2182      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2183                             DwarfStrSectionSym);
2184
2185    Asm->OutStreamer.AddComment("Function name");
2186    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2187    Asm->EmitULEB128(Labels.size(), "Inline count");
2188
2189    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2190           LE = Labels.end(); LI != LE; ++LI) {
2191      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2192      Asm->EmitInt32(LI->second->getOffset());
2193
2194      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2195      Asm->OutStreamer.EmitSymbolValue(LI->first,
2196                                       Asm->getTargetData().getPointerSize(),0);
2197    }
2198  }
2199
2200  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2201}
2202