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