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