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