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