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