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