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