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