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