Split out the DwarfException class into its own file. No functionality change,
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfWriter.cpp
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf 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 info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/DwarfWriter.h"
15 #include "DIE.h"
16 #include "DwarfException.h"
17 #include "DwarfPrinter.h"
18 #include "llvm/Module.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Constants.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineLocation.h"
25 #include "llvm/Analysis/DebugInfo.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/DataTypes.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Support/Timer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/FoldingSet.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/ADT/StringMap.h"
45 #include <ostream>
46 #include <string>
47 using namespace llvm;
48 using namespace llvm::dwarf;
49
50 static RegisterPass<DwarfWriter>
51 X("dwarfwriter", "DWARF Information Writer");
52 char DwarfWriter::ID = 0;
53
54 static TimerGroup &getDwarfTimerGroup() {
55   static TimerGroup DwarfTimerGroup("Dwarf Exception and Debugging");
56   return DwarfTimerGroup;
57 }
58
59 namespace llvm {
60
61 //===----------------------------------------------------------------------===//
62
63 /// Configuration values for initial hash set sizes (log2).
64 ///
65 static const unsigned InitDiesSetSize          = 9; // log2(512)
66 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
67 static const unsigned InitValuesSetSize        = 9; // log2(512)
68
69 //===----------------------------------------------------------------------===//
70 /// CompileUnit - This dwarf writer support class manages information associate
71 /// with a source file.
72 class VISIBILITY_HIDDEN CompileUnit {
73   /// ID - File identifier for source.
74   ///
75   unsigned ID;
76
77   /// Die - Compile unit debug information entry.
78   ///
79   DIE *Die;
80
81   /// GVToDieMap - Tracks the mapping of unit level debug informaton
82   /// variables to debug information entries.
83   std::map<GlobalVariable *, DIE *> GVToDieMap;
84
85   /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
86   /// descriptors to debug information entries using a DIEEntry proxy.
87   std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
88
89   /// Globals - A map of globally visible named entities for this unit.
90   ///
91   StringMap<DIE*> Globals;
92
93   /// DiesSet - Used to uniquely define dies within the compile unit.
94   ///
95   FoldingSet<DIE> DiesSet;
96 public:
97   CompileUnit(unsigned I, DIE *D)
98     : ID(I), Die(D), GVToDieMap(),
99       GVToDIEEntryMap(), Globals(), DiesSet(InitDiesSetSize)
100   {}
101
102   ~CompileUnit() {
103     delete Die;
104   }
105
106   // Accessors.
107   unsigned getID()           const { return ID; }
108   DIE* getDie()              const { return Die; }
109   StringMap<DIE*> &getGlobals() { return Globals; }
110
111   /// hasContent - Return true if this compile unit has something to write out.
112   ///
113   bool hasContent() const {
114     return !Die->getChildren().empty();
115   }
116
117   /// AddGlobal - Add a new global entity to the compile unit.
118   ///
119   void AddGlobal(const std::string &Name, DIE *Die) {
120     Globals[Name] = Die;
121   }
122
123   /// getDieMapSlotFor - Returns the debug information entry map slot for the
124   /// specified debug variable.
125   DIE *&getDieMapSlotFor(GlobalVariable *GV) {
126     return GVToDieMap[GV];
127   }
128
129   /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for the
130   /// specified debug variable.
131   DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
132     return GVToDIEEntryMap[GV];
133   }
134
135   /// AddDie - Adds or interns the DIE to the compile unit.
136   ///
137   DIE *AddDie(DIE &Buffer) {
138     FoldingSetNodeID ID;
139     Buffer.Profile(ID);
140     void *Where;
141     DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
142
143     if (!Die) {
144       Die = new DIE(Buffer);
145       DiesSet.InsertNode(Die, Where);
146       this->Die->AddChild(Die);
147       Buffer.Detach();
148     }
149
150     return Die;
151   }
152 };
153
154 //===----------------------------------------------------------------------===//
155 /// SrcLineInfo - This class is used to record source line correspondence.
156 ///
157 class VISIBILITY_HIDDEN SrcLineInfo {
158   unsigned Line;                     // Source line number.
159   unsigned Column;                   // Source column.
160   unsigned SourceID;                 // Source ID number.
161   unsigned LabelID;                  // Label in code ID number.
162 public:
163   SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
164     : Line(L), Column(C), SourceID(S), LabelID(I) {}
165
166   // Accessors
167   unsigned getLine()     const { return Line; }
168   unsigned getColumn()   const { return Column; }
169   unsigned getSourceID() const { return SourceID; }
170   unsigned getLabelID()  const { return LabelID; }
171 };
172
173 //===----------------------------------------------------------------------===//
174 /// DbgVariable - This class is used to track local variable information.
175 ///
176 class VISIBILITY_HIDDEN DbgVariable {
177   DIVariable Var;                    // Variable Descriptor.
178   unsigned FrameIndex;               // Variable frame index.
179 public:
180   DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I)  {}
181   
182   // Accessors.
183   DIVariable getVariable()  const { return Var; }
184   unsigned getFrameIndex() const { return FrameIndex; }
185 };
186
187 //===----------------------------------------------------------------------===//
188 /// DbgScope - This class is used to track scope information.
189 ///
190 class DbgConcreteScope;
191 class VISIBILITY_HIDDEN DbgScope {
192   DbgScope *Parent;                   // Parent to this scope.
193   DIDescriptor Desc;                  // Debug info descriptor for scope.
194                                       // Either subprogram or block.
195   unsigned StartLabelID;              // Label ID of the beginning of scope.
196   unsigned EndLabelID;                // Label ID of the end of scope.
197   SmallVector<DbgScope *, 4> Scopes;  // Scopes defined in scope.
198   SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
199   SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
200 public:
201   DbgScope(DbgScope *P, DIDescriptor D)
202     : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0) {}
203   virtual ~DbgScope();
204   
205   // Accessors.
206   DbgScope *getParent()          const { return Parent; }
207   DIDescriptor getDesc()         const { return Desc; }
208   unsigned getStartLabelID()     const { return StartLabelID; }
209   unsigned getEndLabelID()       const { return EndLabelID; }
210   SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
211   SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
212   SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
213   void setStartLabelID(unsigned S) { StartLabelID = S; }
214   void setEndLabelID(unsigned E)   { EndLabelID = E; }
215   
216   /// AddScope - Add a scope to the scope.
217   ///
218   void AddScope(DbgScope *S) { Scopes.push_back(S); }
219   
220   /// AddVariable - Add a variable to the scope.
221   ///
222   void AddVariable(DbgVariable *V) { Variables.push_back(V); }
223
224   /// AddConcreteInst - Add a concrete instance to the scope.
225   ///
226   void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
227
228 #ifndef NDEBUG
229   void dump() const;
230 #endif
231 };
232
233 #ifndef NDEBUG
234 void DbgScope::dump() const {
235   static unsigned IndentLevel = 0;
236   std::string Indent(IndentLevel, ' ');
237
238   cerr << Indent; Desc.dump();
239   cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
240
241   IndentLevel += 2;
242
243   for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
244     if (Scopes[i] != this)
245       Scopes[i]->dump();
246
247   IndentLevel -= 2;
248 }
249 #endif
250
251 //===----------------------------------------------------------------------===//
252 /// DbgConcreteScope - This class is used to track a scope that holds concrete
253 /// instance information.
254 /// 
255 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
256   CompileUnit *Unit;
257   DIE *Die;                           // Debug info for this concrete scope.
258 public:
259   DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
260
261   // Accessors.
262   DIE *getDie() const { return Die; }
263   void setDie(DIE *D) { Die = D; }
264 };
265
266 DbgScope::~DbgScope() {
267   for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
268     delete Scopes[i];
269   for (unsigned j = 0, M = Variables.size(); j < M; ++j)
270     delete Variables[j];
271   for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
272     delete ConcreteInsts[k];
273 }
274
275 //===----------------------------------------------------------------------===//
276 /// DwarfDebug - Emits Dwarf debug directives.
277 ///
278 class VISIBILITY_HIDDEN DwarfDebug : public Dwarf {
279   //===--------------------------------------------------------------------===//
280   // Attributes used to construct specific Dwarf sections.
281   //
282
283   /// CompileUnitMap - A map of global variables representing compile units to
284   /// compile units.
285   DenseMap<Value *, CompileUnit *> CompileUnitMap;
286
287   /// CompileUnits - All the compile units in this module.
288   ///
289   SmallVector<CompileUnit *, 8> CompileUnits;
290
291   /// MainCU - Some platform prefers one compile unit per .o file. In such
292   /// cases, all dies are inserted in MainCU.
293   CompileUnit *MainCU;
294
295   /// AbbreviationsSet - Used to uniquely define abbreviations.
296   ///
297   FoldingSet<DIEAbbrev> AbbreviationsSet;
298
299   /// Abbreviations - A list of all the unique abbreviations in use.
300   ///
301   std::vector<DIEAbbrev *> Abbreviations;
302
303   /// DirectoryIdMap - Directory name to directory id map.
304   ///
305   StringMap<unsigned> DirectoryIdMap;
306
307   /// DirectoryNames - A list of directory names.
308   SmallVector<std::string, 8> DirectoryNames;
309
310   /// SourceFileIdMap - Source file name to source file id map.
311   ///
312   StringMap<unsigned> SourceFileIdMap;
313
314   /// SourceFileNames - A list of source file names.
315   SmallVector<std::string, 8> SourceFileNames;
316
317   /// SourceIdMap - Source id map, i.e. pair of directory id and source file
318   /// id mapped to a unique id.
319   DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
320
321   /// SourceIds - Reverse map from source id to directory id + file id pair.
322   ///
323   SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
324
325   /// Lines - List of of source line correspondence.
326   std::vector<SrcLineInfo> Lines;
327
328   /// ValuesSet - Used to uniquely define values.
329   ///
330   FoldingSet<DIEValue> ValuesSet;
331
332   /// Values - A list of all the unique values in use.
333   ///
334   std::vector<DIEValue *> Values;
335
336   /// StringPool - A UniqueVector of strings used by indirect references.
337   ///
338   UniqueVector<std::string> StringPool;
339
340   /// SectionMap - Provides a unique id per text section.
341   ///
342   UniqueVector<const Section*> SectionMap;
343
344   /// SectionSourceLines - Tracks line numbers per text section.
345   ///
346   std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
347
348   /// didInitial - Flag to indicate if initial emission has been done.
349   ///
350   bool didInitial;
351
352   /// shouldEmit - Flag to indicate if debug information should be emitted.
353   ///
354   bool shouldEmit;
355
356   // FunctionDbgScope - Top level scope for the current function.
357   //
358   DbgScope *FunctionDbgScope;
359   
360   /// DbgScopeMap - Tracks the scopes in the current function.
361   DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
362
363   /// DbgAbstractScopeMap - Tracks abstract instance scopes in the current
364   /// function.
365   DenseMap<GlobalVariable *, DbgScope *> DbgAbstractScopeMap;
366
367   /// DbgConcreteScopeMap - Tracks concrete instance scopes in the current
368   /// function.
369   DenseMap<GlobalVariable *,
370            SmallVector<DbgScope *, 8> > DbgConcreteScopeMap;
371
372   /// InlineInfo - Keep track of inlined functions and their location.  This
373   /// information is used to populate debug_inlined section.
374   DenseMap<GlobalVariable *, SmallVector<unsigned, 4> > InlineInfo;
375
376   /// InlinedVariableScopes - Scopes information for the inlined subroutine
377   /// variables.
378   DenseMap<const MachineInstr *, DbgScope *> InlinedVariableScopes;
379
380   /// AbstractInstanceRootMap - Map of abstract instance roots of inlined
381   /// functions. These are subroutine entries that contain a DW_AT_inline
382   /// attribute.
383   DenseMap<const GlobalVariable *, DbgScope *> AbstractInstanceRootMap;
384
385   /// AbstractInstanceRootList - List of abstract instance roots of inlined
386   /// functions. These are subroutine entries that contain a DW_AT_inline
387   /// attribute.
388   SmallVector<DbgScope *, 32> AbstractInstanceRootList;
389
390   /// LexicalScopeStack - A stack of lexical scopes. The top one is the current
391   /// scope.
392   SmallVector<DbgScope *, 16> LexicalScopeStack;
393
394   /// CompileUnitOffsets - A vector of the offsets of the compile units. This is
395   /// used when calculating the "origin" of a concrete instance of an inlined
396   /// function.
397   DenseMap<CompileUnit *, unsigned> CompileUnitOffsets;
398
399   /// DebugTimer - Timer for the Dwarf debug writer.
400   Timer *DebugTimer;
401   
402   struct FunctionDebugFrameInfo {
403     unsigned Number;
404     std::vector<MachineMove> Moves;
405
406     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
407       Number(Num), Moves(M) { }
408   };
409
410   std::vector<FunctionDebugFrameInfo> DebugFrames;
411
412 private:
413   /// getSourceDirectoryAndFileIds - Return the directory and file ids that
414   /// maps to the source id. Source id starts at 1.
415   std::pair<unsigned, unsigned>
416   getSourceDirectoryAndFileIds(unsigned SId) const {
417     return SourceIds[SId-1];
418   }
419
420   /// getNumSourceDirectories - Return the number of source directories in the
421   /// debug info.
422   unsigned getNumSourceDirectories() const {
423     return DirectoryNames.size();
424   }
425
426   /// getSourceDirectoryName - Return the name of the directory corresponding
427   /// to the id.
428   const std::string &getSourceDirectoryName(unsigned Id) const {
429     return DirectoryNames[Id - 1];
430   }
431
432   /// getSourceFileName - Return the name of the source file corresponding
433   /// to the id.
434   const std::string &getSourceFileName(unsigned Id) const {
435     return SourceFileNames[Id - 1];
436   }
437
438   /// getNumSourceIds - Return the number of unique source ids.
439   unsigned getNumSourceIds() const {
440     return SourceIds.size();
441   }
442
443   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
444   ///
445   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
446     // Profile the node so that we can make it unique.
447     FoldingSetNodeID ID;
448     Abbrev.Profile(ID);
449
450     // Check the set for priors.
451     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
452
453     // If it's newly added.
454     if (InSet == &Abbrev) {
455       // Add to abbreviation list.
456       Abbreviations.push_back(&Abbrev);
457       // Assign the vector position + 1 as its number.
458       Abbrev.setNumber(Abbreviations.size());
459     } else {
460       // Assign existing abbreviation number.
461       Abbrev.setNumber(InSet->getNumber());
462     }
463   }
464
465   /// NewString - Add a string to the constant pool and returns a label.
466   ///
467   DWLabel NewString(const std::string &String) {
468     unsigned StringID = StringPool.insert(String);
469     return DWLabel("string", StringID);
470   }
471
472   /// NewDIEEntry - Creates a new DIEEntry to be a proxy for a debug information
473   /// entry.
474   DIEEntry *NewDIEEntry(DIE *Entry = NULL) {
475     DIEEntry *Value;
476
477     if (Entry) {
478       FoldingSetNodeID ID;
479       DIEEntry::Profile(ID, Entry);
480       void *Where;
481       Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
482
483       if (Value) return Value;
484
485       Value = new DIEEntry(Entry);
486       ValuesSet.InsertNode(Value, Where);
487     } else {
488       Value = new DIEEntry(Entry);
489     }
490
491     Values.push_back(Value);
492     return Value;
493   }
494
495   /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
496   ///
497   void SetDIEEntry(DIEEntry *Value, DIE *Entry) {
498     Value->setEntry(Entry);
499     // Add to values set if not already there.  If it is, we merely have a
500     // duplicate in the values list (no harm.)
501     ValuesSet.GetOrInsertNode(Value);
502   }
503
504   /// AddUInt - Add an unsigned integer attribute data and value.
505   ///
506   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
507     if (!Form) Form = DIEInteger::BestForm(false, Integer);
508
509     FoldingSetNodeID ID;
510     DIEInteger::Profile(ID, Integer);
511     void *Where;
512     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
513     if (!Value) {
514       Value = new DIEInteger(Integer);
515       ValuesSet.InsertNode(Value, Where);
516       Values.push_back(Value);
517     }
518
519     Die->AddValue(Attribute, Form, Value);
520   }
521
522   /// AddSInt - Add an signed integer attribute data and value.
523   ///
524   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
525     if (!Form) Form = DIEInteger::BestForm(true, Integer);
526
527     FoldingSetNodeID ID;
528     DIEInteger::Profile(ID, (uint64_t)Integer);
529     void *Where;
530     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
531     if (!Value) {
532       Value = new DIEInteger(Integer);
533       ValuesSet.InsertNode(Value, Where);
534       Values.push_back(Value);
535     }
536
537     Die->AddValue(Attribute, Form, Value);
538   }
539
540   /// AddString - Add a string attribute data and value.
541   ///
542   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
543                  const std::string &String) {
544     FoldingSetNodeID ID;
545     DIEString::Profile(ID, String);
546     void *Where;
547     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
548     if (!Value) {
549       Value = new DIEString(String);
550       ValuesSet.InsertNode(Value, Where);
551       Values.push_back(Value);
552     }
553
554     Die->AddValue(Attribute, Form, Value);
555   }
556
557   /// AddLabel - Add a Dwarf label attribute data and value.
558   ///
559   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
560                 const DWLabel &Label) {
561     FoldingSetNodeID ID;
562     DIEDwarfLabel::Profile(ID, Label);
563     void *Where;
564     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
565     if (!Value) {
566       Value = new DIEDwarfLabel(Label);
567       ValuesSet.InsertNode(Value, Where);
568       Values.push_back(Value);
569     }
570
571     Die->AddValue(Attribute, Form, Value);
572   }
573
574   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
575   ///
576   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
577                       const std::string &Label) {
578     FoldingSetNodeID ID;
579     DIEObjectLabel::Profile(ID, Label);
580     void *Where;
581     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
582     if (!Value) {
583       Value = new DIEObjectLabel(Label);
584       ValuesSet.InsertNode(Value, Where);
585       Values.push_back(Value);
586     }
587
588     Die->AddValue(Attribute, Form, Value);
589   }
590
591   /// AddSectionOffset - Add a section offset label attribute data and value.
592   ///
593   void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
594                         const DWLabel &Label, const DWLabel &Section,
595                         bool isEH = false, bool useSet = true) {
596     FoldingSetNodeID ID;
597     DIESectionOffset::Profile(ID, Label, Section);
598     void *Where;
599     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
600     if (!Value) {
601       Value = new DIESectionOffset(Label, Section, isEH, useSet);
602       ValuesSet.InsertNode(Value, Where);
603       Values.push_back(Value);
604     }
605
606     Die->AddValue(Attribute, Form, Value);
607   }
608
609   /// AddDelta - Add a label delta attribute data and value.
610   ///
611   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
612                 const DWLabel &Hi, const DWLabel &Lo) {
613     FoldingSetNodeID ID;
614     DIEDelta::Profile(ID, Hi, Lo);
615     void *Where;
616     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
617     if (!Value) {
618       Value = new DIEDelta(Hi, Lo);
619       ValuesSet.InsertNode(Value, Where);
620       Values.push_back(Value);
621     }
622
623     Die->AddValue(Attribute, Form, Value);
624   }
625
626   /// AddDIEEntry - Add a DIE attribute data and value.
627   ///
628   void AddDIEEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
629     Die->AddValue(Attribute, Form, NewDIEEntry(Entry));
630   }
631
632   /// AddBlock - Add block data.
633   ///
634   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
635     Block->ComputeSize(TD);
636     FoldingSetNodeID ID;
637     Block->Profile(ID);
638     void *Where;
639     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
640     if (!Value) {
641       Value = Block;
642       ValuesSet.InsertNode(Value, Where);
643       Values.push_back(Value);
644     } else {
645       // Already exists, reuse the previous one.
646       delete Block;
647       Block = cast<DIEBlock>(Value);
648     }
649
650     Die->AddValue(Attribute, Block->BestForm(), Value);
651   }
652
653   /// AddSourceLine - Add location information to specified debug information
654   /// entry.
655   void AddSourceLine(DIE *Die, const DIVariable *V) {
656     // If there is no compile unit specified, don't add a line #.
657     if (V->getCompileUnit().isNull())
658       return;
659
660     unsigned Line = V->getLineNumber();
661     unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
662     assert(FileID && "Invalid file id");
663     AddUInt(Die, DW_AT_decl_file, 0, FileID);
664     AddUInt(Die, DW_AT_decl_line, 0, Line);
665   }
666
667   /// AddSourceLine - Add location information to specified debug information
668   /// entry.
669   void AddSourceLine(DIE *Die, const DIGlobal *G) {
670     // If there is no compile unit specified, don't add a line #.
671     if (G->getCompileUnit().isNull())
672       return;
673     unsigned Line = G->getLineNumber();
674     unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
675     assert(FileID && "Invalid file id");
676     AddUInt(Die, DW_AT_decl_file, 0, FileID);
677     AddUInt(Die, DW_AT_decl_line, 0, Line);
678   }
679
680   void AddSourceLine(DIE *Die, const DIType *Ty) {
681     // If there is no compile unit specified, don't add a line #.
682     DICompileUnit CU = Ty->getCompileUnit();
683     if (CU.isNull())
684       return;
685     
686     unsigned Line = Ty->getLineNumber();
687     unsigned FileID = FindCompileUnit(CU).getID();
688     assert(FileID && "Invalid file id");
689     AddUInt(Die, DW_AT_decl_file, 0, FileID);
690     AddUInt(Die, DW_AT_decl_line, 0, Line);
691   }
692
693   /// AddAddress - Add an address attribute to a die based on the location
694   /// provided.
695   void AddAddress(DIE *Die, unsigned Attribute,
696                   const MachineLocation &Location) {
697     unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
698     DIEBlock *Block = new DIEBlock();
699
700     if (Location.isReg()) {
701       if (Reg < 32) {
702         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
703       } else {
704         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
705         AddUInt(Block, 0, DW_FORM_udata, Reg);
706       }
707     } else {
708       if (Reg < 32) {
709         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
710       } else {
711         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
712         AddUInt(Block, 0, DW_FORM_udata, Reg);
713       }
714       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
715     }
716
717     AddBlock(Die, Attribute, 0, Block);
718   }
719
720   /// AddType - Add a new type attribute to the specified entity.
721   void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
722     if (Ty.isNull())
723       return;
724
725     // Check for pre-existence.
726     DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
727     // If it exists then use the existing value.
728     if (Slot) {
729       Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
730       return;
731     }
732
733     // Set up proxy. 
734     Slot = NewDIEEntry();
735
736     // Construct type.
737     DIE Buffer(DW_TAG_base_type);
738     if (Ty.isBasicType(Ty.getTag()))
739       ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
740     else if (Ty.isDerivedType(Ty.getTag()))
741       ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
742     else {
743       assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
744       ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
745     }
746     
747     // Add debug information entry to entity and appropriate context.
748     DIE *Die = NULL;
749     DIDescriptor Context = Ty.getContext();
750     if (!Context.isNull())
751       Die = DW_Unit->getDieMapSlotFor(Context.getGV());
752
753     if (Die) {
754       DIE *Child = new DIE(Buffer);
755       Die->AddChild(Child);
756       Buffer.Detach();
757       SetDIEEntry(Slot, Child);
758     } else {
759       Die = DW_Unit->AddDie(Buffer);
760       SetDIEEntry(Slot, Die);
761     }
762
763     Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
764   }
765
766   /// ConstructTypeDIE - Construct basic type die from DIBasicType.
767   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
768                         DIBasicType BTy) {
769     
770     // Get core information.
771     std::string Name;
772     BTy.getName(Name);
773     Buffer.setTag(DW_TAG_base_type);
774     AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BTy.getEncoding());
775     // Add name if not anonymous or intermediate type.
776     if (!Name.empty())
777       AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
778     uint64_t Size = BTy.getSizeInBits() >> 3;
779     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
780   }
781
782   /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
783   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
784                         DIDerivedType DTy) {
785
786     // Get core information.
787     std::string Name;
788     DTy.getName(Name);
789     uint64_t Size = DTy.getSizeInBits() >> 3;
790     unsigned Tag = DTy.getTag();
791
792     // FIXME - Workaround for templates.
793     if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
794
795     Buffer.setTag(Tag);
796
797     // Map to main type, void will not have a type.
798     DIType FromTy = DTy.getTypeDerivedFrom();
799     AddType(DW_Unit, &Buffer, FromTy);
800
801     // Add name if not anonymous or intermediate type.
802     if (!Name.empty())
803       AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
804
805     // Add size if non-zero (derived types might be zero-sized.)
806     if (Size)
807       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
808
809     // Add source line info if available and TyDesc is not a forward
810     // declaration.
811     if (!DTy.isForwardDecl())
812       AddSourceLine(&Buffer, &DTy);
813   }
814
815   /// ConstructTypeDIE - Construct type DIE from DICompositeType.
816   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
817                         DICompositeType CTy) {
818     // Get core information.
819     std::string Name;
820     CTy.getName(Name);
821
822     uint64_t Size = CTy.getSizeInBits() >> 3;
823     unsigned Tag = CTy.getTag();
824     Buffer.setTag(Tag);
825
826     switch (Tag) {
827     case DW_TAG_vector_type:
828     case DW_TAG_array_type:
829       ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
830       break;
831     case DW_TAG_enumeration_type:
832       {
833         DIArray Elements = CTy.getTypeArray();
834         // Add enumerators to enumeration type.
835         for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
836           DIE *ElemDie = NULL;
837           DIEnumerator Enum(Elements.getElement(i).getGV());
838           ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
839           Buffer.AddChild(ElemDie);
840         }
841       }
842       break;
843     case DW_TAG_subroutine_type: 
844       {
845         // Add return type.
846         DIArray Elements = CTy.getTypeArray();
847         DIDescriptor RTy = Elements.getElement(0);
848         AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
849
850         // Add prototype flag.
851         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
852
853         // Add arguments.
854         for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
855           DIE *Arg = new DIE(DW_TAG_formal_parameter);
856           DIDescriptor Ty = Elements.getElement(i);
857           AddType(DW_Unit, Arg, DIType(Ty.getGV()));
858           Buffer.AddChild(Arg);
859         }
860       }
861       break;
862     case DW_TAG_structure_type:
863     case DW_TAG_union_type: 
864     case DW_TAG_class_type:
865       {
866         // Add elements to structure type.
867         DIArray Elements = CTy.getTypeArray();
868
869         // A forward struct declared type may not have elements available.
870         if (Elements.isNull())
871           break;
872
873         // Add elements to structure type.
874         for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
875           DIDescriptor Element = Elements.getElement(i);
876           DIE *ElemDie = NULL;
877           if (Element.getTag() == dwarf::DW_TAG_subprogram)
878             ElemDie = CreateSubprogramDIE(DW_Unit, 
879                                           DISubprogram(Element.getGV()));
880           else if (Element.getTag() == dwarf::DW_TAG_variable) // ??
881             ElemDie = CreateGlobalVariableDIE(DW_Unit, 
882                                               DIGlobalVariable(Element.getGV()));
883           else
884             ElemDie = CreateMemberDIE(DW_Unit, 
885                                       DIDerivedType(Element.getGV()));
886           Buffer.AddChild(ElemDie);
887         }
888
889         // FIXME: We'd like an API to register additional attributes for the
890         // frontend to use while synthesizing, and then we'd use that api in
891         // clang instead of this.
892         if (Name == "__block_literal_generic")
893           AddUInt(&Buffer, DW_AT_APPLE_block, DW_FORM_flag, 1);
894
895         unsigned RLang = CTy.getRunTimeLang();
896         if (RLang) 
897           AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
898       }
899       break;
900     default:
901       break;
902     }
903
904     // Add name if not anonymous or intermediate type.
905     if (!Name.empty())
906       AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
907
908     if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
909         || Tag == DW_TAG_union_type) {
910       // Add size if non-zero (derived types might be zero-sized.)
911       if (Size)
912         AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
913       else {
914         // Add zero size if it is not a forward declaration.
915         if (CTy.isForwardDecl())
916           AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
917         else
918           AddUInt(&Buffer, DW_AT_byte_size, 0, 0); 
919       }
920       
921       // Add source line info if available.
922       if (!CTy.isForwardDecl())
923         AddSourceLine(&Buffer, &CTy);
924     }
925   }
926   
927   /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
928   void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
929     int64_t L = SR.getLo();
930     int64_t H = SR.getHi();
931     DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
932     if (L != H) {
933       AddDIEEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
934       if (L)
935         AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
936       AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
937     }
938     Buffer.AddChild(DW_Subrange);
939   }
940
941   /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
942   void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 
943                              DICompositeType *CTy) {
944     Buffer.setTag(DW_TAG_array_type);
945     if (CTy->getTag() == DW_TAG_vector_type)
946       AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
947     
948     // Emit derived type.
949     AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());    
950     DIArray Elements = CTy->getTypeArray();
951
952     // Construct an anonymous type for index type.
953     DIE IdxBuffer(DW_TAG_base_type);
954     AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
955     AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
956     DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
957
958     // Add subranges to array type.
959     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
960       DIDescriptor Element = Elements.getElement(i);
961       if (Element.getTag() == dwarf::DW_TAG_subrange_type)
962         ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
963     }
964   }
965
966   /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
967   DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
968
969     DIE *Enumerator = new DIE(DW_TAG_enumerator);
970     std::string Name;
971     ETy->getName(Name);
972     AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
973     int64_t Value = ETy->getEnumValue();                             
974     AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
975     return Enumerator;
976   }
977
978   /// CreateGlobalVariableDIE - Create new DIE using GV.
979   DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
980   {
981     DIE *GVDie = new DIE(DW_TAG_variable);
982     std::string Name;
983     GV.getDisplayName(Name);
984     AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
985     std::string LinkageName;
986     GV.getLinkageName(LinkageName);
987     if (!LinkageName.empty())
988       AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
989     AddType(DW_Unit, GVDie, GV.getType());
990     if (!GV.isLocalToUnit())
991       AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
992     AddSourceLine(GVDie, &GV);
993     return GVDie;
994   }
995
996   /// CreateMemberDIE - Create new member DIE.
997   DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
998     DIE *MemberDie = new DIE(DT.getTag());
999     std::string Name;
1000     DT.getName(Name);
1001     if (!Name.empty())
1002       AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1003
1004     AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1005
1006     AddSourceLine(MemberDie, &DT);
1007
1008     uint64_t Size = DT.getSizeInBits();
1009     uint64_t FieldSize = DT.getOriginalTypeSize();
1010
1011     if (Size != FieldSize) {
1012       // Handle bitfield.
1013       AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1014       AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1015
1016       uint64_t Offset = DT.getOffsetInBits();
1017       uint64_t FieldOffset = Offset;
1018       uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1019       uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1020       FieldOffset = (HiMark - FieldSize);
1021       Offset -= FieldOffset;
1022       // Maybe we need to work from the other end.
1023       if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1024       AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1025     }
1026     DIEBlock *Block = new DIEBlock();
1027     AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1028     AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1029     AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1030
1031     if (DT.isProtected())
1032       AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1033     else if (DT.isPrivate())
1034       AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1035
1036     return MemberDie;
1037   }
1038
1039   /// CreateSubprogramDIE - Create new DIE using SP.
1040   DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1041                            const DISubprogram &SP,
1042                            bool IsConstructor = false) {
1043     DIE *SPDie = new DIE(DW_TAG_subprogram);
1044
1045     std::string Name;
1046     SP.getName(Name);
1047     AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1048
1049     std::string LinkageName;
1050     SP.getLinkageName(LinkageName);
1051
1052     if (!LinkageName.empty())
1053       AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1054
1055     AddSourceLine(SPDie, &SP);
1056
1057     DICompositeType SPTy = SP.getType();
1058     DIArray Args = SPTy.getTypeArray();
1059
1060     // Add prototyped tag, if C or ObjC.
1061     unsigned Lang = SP.getCompileUnit().getLanguage();
1062     if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89 || Lang == DW_LANG_ObjC)
1063       AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1064     
1065     // Add Return Type.
1066     unsigned SPTag = SPTy.getTag();
1067     if (!IsConstructor) {
1068       if (Args.isNull() || SPTag != DW_TAG_subroutine_type)
1069         AddType(DW_Unit, SPDie, SPTy);
1070       else
1071         AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1072     }
1073
1074     if (!SP.isDefinition()) {
1075       AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);    
1076       // Add arguments. Do not add arguments for subprogram definition. They
1077       // will be handled through RecordVariable.
1078       if (SPTag == DW_TAG_subroutine_type)
1079         for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1080           DIE *Arg = new DIE(DW_TAG_formal_parameter);
1081           AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1082           AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ??
1083           SPDie->AddChild(Arg);
1084         }
1085     }
1086
1087     if (!SP.isLocalToUnit())
1088       AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1089
1090     // DW_TAG_inlined_subroutine may refer to this DIE.
1091     DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
1092     Slot = SPDie;
1093     return SPDie;
1094   }
1095
1096   /// FindCompileUnit - Get the compile unit for the given descriptor. 
1097   ///
1098   CompileUnit &FindCompileUnit(DICompileUnit Unit) const {
1099     DenseMap<Value *, CompileUnit *>::const_iterator I = 
1100       CompileUnitMap.find(Unit.getGV());
1101     assert(I != CompileUnitMap.end() && "Missing compile unit.");
1102     return *I->second;
1103   }
1104
1105   /// NewDbgScopeVariable - Create a new scope variable.
1106   ///
1107   DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1108     // Get the descriptor.
1109     const DIVariable &VD = DV->getVariable();
1110
1111     // Translate tag to proper Dwarf tag.  The result variable is dropped for
1112     // now.
1113     unsigned Tag;
1114     switch (VD.getTag()) {
1115     case DW_TAG_return_variable:  return NULL;
1116     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
1117     case DW_TAG_auto_variable:    // fall thru
1118     default:                      Tag = DW_TAG_variable; break;
1119     }
1120
1121     // Define variable debug information entry.
1122     DIE *VariableDie = new DIE(Tag);
1123     std::string Name;
1124     VD.getName(Name);
1125     AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1126
1127     // Add source line info if available.
1128     AddSourceLine(VariableDie, &VD);
1129
1130     // Add variable type.
1131     AddType(Unit, VariableDie, VD.getType());
1132
1133     // Add variable address.
1134     MachineLocation Location;
1135     Location.set(RI->getFrameRegister(*MF),
1136                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1137     AddAddress(VariableDie, DW_AT_location, Location);
1138
1139     return VariableDie;
1140   }
1141
1142   /// getOrCreateScope - Returns the scope associated with the given descriptor.
1143   ///
1144   DbgScope *getOrCreateScope(GlobalVariable *V) {
1145     DbgScope *&Slot = DbgScopeMap[V];
1146     if (Slot) return Slot;
1147
1148     DbgScope *Parent = NULL;
1149     DIBlock Block(V);
1150
1151     // Don't create a new scope if we already created one for an inlined
1152     // function.
1153     DenseMap<const GlobalVariable *, DbgScope *>::iterator
1154       II = AbstractInstanceRootMap.find(V);
1155     if (II != AbstractInstanceRootMap.end())
1156       return LexicalScopeStack.back();
1157
1158     if (!Block.isNull()) {
1159       DIDescriptor ParentDesc = Block.getContext();
1160       Parent = 
1161         ParentDesc.isNull() ?  NULL : getOrCreateScope(ParentDesc.getGV());
1162     }
1163
1164     Slot = new DbgScope(Parent, DIDescriptor(V));
1165
1166     if (Parent)
1167       Parent->AddScope(Slot);
1168     else
1169       // First function is top level function.
1170       FunctionDbgScope = Slot;
1171
1172     return Slot;
1173   }
1174
1175   /// ConstructDbgScope - Construct the components of a scope.
1176   ///
1177   void ConstructDbgScope(DbgScope *ParentScope,
1178                          unsigned ParentStartID, unsigned ParentEndID,
1179                          DIE *ParentDie, CompileUnit *Unit) {
1180     // Add variables to scope.
1181     SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1182     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1183       DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
1184       if (VariableDie) ParentDie->AddChild(VariableDie);
1185     }
1186
1187     // Add concrete instances to scope.
1188     SmallVector<DbgConcreteScope *, 8> &ConcreteInsts = ParentScope->getConcreteInsts();
1189     for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1190       DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1191       DIE *Die = ConcreteInst->getDie();
1192
1193       unsigned StartID = ConcreteInst->getStartLabelID();
1194       unsigned EndID = ConcreteInst->getEndLabelID();
1195
1196       // Add the scope bounds.
1197       if (StartID)
1198         AddLabel(Die, DW_AT_low_pc, DW_FORM_addr,
1199                  DWLabel("label", StartID));
1200       else
1201         AddLabel(Die, DW_AT_low_pc, DW_FORM_addr,
1202                  DWLabel("func_begin", SubprogramCount));
1203
1204       if (EndID)
1205         AddLabel(Die, DW_AT_high_pc, DW_FORM_addr,
1206                  DWLabel("label", EndID));
1207       else
1208         AddLabel(Die, DW_AT_high_pc, DW_FORM_addr,
1209                  DWLabel("func_end", SubprogramCount));
1210
1211       ParentDie->AddChild(Die);
1212     }
1213
1214     // Add nested scopes.
1215     SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1216     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1217       // Define the Scope debug information entry.
1218       DbgScope *Scope = Scopes[j];
1219
1220       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1221       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1222
1223       // Ignore empty scopes. 
1224       if (StartID == EndID && StartID != 0) continue;
1225
1226       // Do not ignore inlined scopes even if they don't have any variables or
1227       // scopes.
1228       if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1229           Scope->getConcreteInsts().empty())
1230         continue;
1231
1232       if (StartID == ParentStartID && EndID == ParentEndID) {
1233         // Just add stuff to the parent scope.
1234         ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1235       } else {
1236         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1237
1238         // Add the scope bounds.
1239         if (StartID)
1240           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1241                    DWLabel("label", StartID));
1242         else
1243           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1244                    DWLabel("func_begin", SubprogramCount));
1245
1246         if (EndID)
1247           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1248                    DWLabel("label", EndID));
1249         else
1250           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1251                    DWLabel("func_end", SubprogramCount));
1252
1253         // Add the scope's contents.
1254         ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1255         ParentDie->AddChild(ScopeDie);
1256       }
1257     }
1258   }
1259
1260   /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1261   ///
1262   void ConstructFunctionDbgScope(DbgScope *RootScope) {
1263     // Exit if there is no root scope.
1264     if (!RootScope) return;
1265     DIDescriptor Desc = RootScope->getDesc();
1266     if (Desc.isNull())
1267       return;
1268
1269     // Get the subprogram debug information entry.
1270     DISubprogram SPD(Desc.getGV());
1271
1272     // Get the compile unit context.
1273     CompileUnit *Unit = MainCU;
1274     if (!Unit)
1275       Unit = &FindCompileUnit(SPD.getCompileUnit());
1276
1277     // Get the subprogram die.
1278     DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1279     assert(SPDie && "Missing subprogram descriptor");
1280
1281     // Add the function bounds.
1282     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1283                     DWLabel("func_begin", SubprogramCount));
1284     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1285                     DWLabel("func_end", SubprogramCount));
1286     MachineLocation Location(RI->getFrameRegister(*MF));
1287     AddAddress(SPDie, DW_AT_frame_base, Location);
1288
1289     ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1290   }
1291
1292   /// ConstructFunctionDbgScope - Construct the scope for the abstract debug
1293   /// scope.
1294   ///
1295   void ConstructAbstractDbgScope(DbgScope *AbsScope) {
1296     // Exit if there is no root scope.
1297     if (!AbsScope) return;
1298
1299     DIDescriptor Desc = AbsScope->getDesc();
1300     if (Desc.isNull())
1301       return;
1302
1303     // Get the subprogram debug information entry.
1304     DISubprogram SPD(Desc.getGV());
1305
1306     // Get the compile unit context.
1307     CompileUnit *Unit = MainCU;
1308     if (!Unit)
1309       Unit = &FindCompileUnit(SPD.getCompileUnit());
1310
1311     // Get the subprogram die.
1312     DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1313     assert(SPDie && "Missing subprogram descriptor");
1314
1315     ConstructDbgScope(AbsScope, 0, 0, SPDie, Unit);
1316   }
1317
1318   /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1319   ///
1320   void ConstructDefaultDbgScope(MachineFunction *MF) {
1321     const char *FnName = MF->getFunction()->getNameStart();
1322     if (MainCU) {
1323       StringMap<DIE*> &Globals = MainCU->getGlobals();
1324       StringMap<DIE*>::iterator GI = Globals.find(FnName);
1325       if (GI != Globals.end()) {
1326         DIE *SPDie = GI->second;
1327
1328         // Add the function bounds.
1329         AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1330                  DWLabel("func_begin", SubprogramCount));
1331         AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1332                  DWLabel("func_end", SubprogramCount));
1333
1334         MachineLocation Location(RI->getFrameRegister(*MF));
1335         AddAddress(SPDie, DW_AT_frame_base, Location);
1336         return;
1337       }
1338     } else {
1339       for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1340         CompileUnit *Unit = CompileUnits[i];
1341         StringMap<DIE*> &Globals = Unit->getGlobals();
1342         StringMap<DIE*>::iterator GI = Globals.find(FnName);
1343         if (GI != Globals.end()) {
1344           DIE *SPDie = GI->second;
1345
1346           // Add the function bounds.
1347           AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1348                    DWLabel("func_begin", SubprogramCount));
1349           AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1350                    DWLabel("func_end", SubprogramCount));
1351
1352           MachineLocation Location(RI->getFrameRegister(*MF));
1353           AddAddress(SPDie, DW_AT_frame_base, Location);
1354           return;
1355         }
1356       }
1357     }
1358
1359 #if 0
1360     // FIXME: This is causing an abort because C++ mangled names are compared
1361     // with their unmangled counterparts. See PR2885. Don't do this assert.
1362     assert(0 && "Couldn't find DIE for machine function!");
1363 #endif
1364   }
1365
1366   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1367   /// tools to recognize the object file contains Dwarf information.
1368   void EmitInitial() {
1369     // Check to see if we already emitted intial headers.
1370     if (didInitial) return;
1371     didInitial = true;
1372
1373     // Dwarf sections base addresses.
1374     if (TAI->doesDwarfRequireFrameSection()) {
1375       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1376       EmitLabel("section_debug_frame", 0);
1377     }
1378     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1379     EmitLabel("section_info", 0);
1380     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1381     EmitLabel("section_abbrev", 0);
1382     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1383     EmitLabel("section_aranges", 0);
1384     if (TAI->doesSupportMacInfoSection()) {
1385       Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1386       EmitLabel("section_macinfo", 0);
1387     }
1388     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1389     EmitLabel("section_line", 0);
1390     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1391     EmitLabel("section_loc", 0);
1392     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1393     EmitLabel("section_pubnames", 0);
1394     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1395     EmitLabel("section_str", 0);
1396     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1397     EmitLabel("section_ranges", 0);
1398
1399     Asm->SwitchToSection(TAI->getTextSection());
1400     EmitLabel("text_begin", 0);
1401     Asm->SwitchToSection(TAI->getDataSection());
1402     EmitLabel("data_begin", 0);
1403   }
1404
1405   /// EmitDIE - Recusively Emits a debug information entry.
1406   ///
1407   void EmitDIE(DIE *Die) {
1408     // Get the abbreviation for this DIE.
1409     unsigned AbbrevNumber = Die->getAbbrevNumber();
1410     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1411
1412     Asm->EOL();
1413
1414     // Emit the code (index) for the abbreviation.
1415     Asm->EmitULEB128Bytes(AbbrevNumber);
1416
1417     if (Asm->isVerbose())
1418       Asm->EOL(std::string("Abbrev [" +
1419                            utostr(AbbrevNumber) +
1420                            "] 0x" + utohexstr(Die->getOffset()) +
1421                            ":0x" + utohexstr(Die->getSize()) + " " +
1422                            TagString(Abbrev->getTag())));
1423     else
1424       Asm->EOL();
1425
1426     SmallVector<DIEValue*, 32> &Values = Die->getValues();
1427     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1428
1429     // Emit the DIE attribute values.
1430     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1431       unsigned Attr = AbbrevData[i].getAttribute();
1432       unsigned Form = AbbrevData[i].getForm();
1433       assert(Form && "Too many attributes for DIE (check abbreviation)");
1434
1435       switch (Attr) {
1436       case DW_AT_sibling:
1437         Asm->EmitInt32(Die->SiblingOffset());
1438         break;
1439       case DW_AT_abstract_origin: {
1440         DIEEntry *E = cast<DIEEntry>(Values[i]);
1441         DIE *Origin = E->getEntry();
1442         unsigned Addr =
1443           CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1444           Origin->getOffset();
1445
1446         Asm->EmitInt32(Addr);
1447         break;
1448       }
1449       default:
1450         // Emit an attribute using the defined form.
1451         Values[i]->EmitValue(this, Form);
1452         break;
1453       }
1454
1455       Asm->EOL(AttributeString(Attr));
1456     }
1457
1458     // Emit the DIE children if any.
1459     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
1460       const std::vector<DIE *> &Children = Die->getChildren();
1461
1462       for (unsigned j = 0, M = Children.size(); j < M; ++j)
1463         EmitDIE(Children[j]);
1464
1465       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1466     }
1467   }
1468
1469   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1470   ///
1471   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1472     // Get the children.
1473     const std::vector<DIE *> &Children = Die->getChildren();
1474
1475     // If not last sibling and has children then add sibling offset attribute.
1476     if (!Last && !Children.empty()) Die->AddSiblingOffset();
1477
1478     // Record the abbreviation.
1479     AssignAbbrevNumber(Die->getAbbrev());
1480
1481     // Get the abbreviation for this DIE.
1482     unsigned AbbrevNumber = Die->getAbbrevNumber();
1483     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1484
1485     // Set DIE offset
1486     Die->setOffset(Offset);
1487
1488     // Start the size with the size of abbreviation code.
1489     Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1490
1491     const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1492     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1493
1494     // Size the DIE attribute values.
1495     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1496       // Size attribute value.
1497       Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1498     }
1499
1500     // Size the DIE children if any.
1501     if (!Children.empty()) {
1502       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
1503              "Children flag not set");
1504
1505       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1506         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1507       }
1508
1509       // End of children marker.
1510       Offset += sizeof(int8_t);
1511     }
1512
1513     Die->setSize(Offset - Die->getOffset());
1514     return Offset;
1515   }
1516
1517   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1518   ///
1519   void SizeAndOffsets() {
1520     // Compute size of compile unit header.
1521     static unsigned Offset =
1522       sizeof(int32_t) + // Length of Compilation Unit Info
1523       sizeof(int16_t) + // DWARF version number
1524       sizeof(int32_t) + // Offset Into Abbrev. Section
1525       sizeof(int8_t);   // Pointer Size (in bytes)
1526
1527     // Process base compile unit.
1528     if (MainCU) {
1529       SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1530       CompileUnitOffsets[MainCU] = 0;
1531       return;
1532     }
1533
1534     // Process all compile units.
1535     unsigned PrevOffset = 0;
1536
1537     for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1538       CompileUnit *Unit = CompileUnits[i];
1539       CompileUnitOffsets[Unit] = PrevOffset;
1540       PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1541         + sizeof(int32_t);  // FIXME - extra pad for gdb bug.
1542     }
1543   }
1544
1545   /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1546   ///
1547   void EmitDebugInfoPerCU(CompileUnit *Unit) {
1548     DIE *Die = Unit->getDie();
1549     // Emit the compile units header.
1550     EmitLabel("info_begin", Unit->getID());
1551     // Emit size of content not including length itself
1552     unsigned ContentSize = Die->getSize() +
1553       sizeof(int16_t) + // DWARF version number
1554       sizeof(int32_t) + // Offset Into Abbrev. Section
1555       sizeof(int8_t) +  // Pointer Size (in bytes)
1556       sizeof(int32_t);  // FIXME - extra pad for gdb bug.
1557       
1558     Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
1559     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
1560     EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1561     Asm->EOL("Offset Into Abbrev. Section");
1562     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1563       
1564     EmitDIE(Die);
1565     // FIXME - extra padding for gdb bug.
1566     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1567     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1568     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1569     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1570     EmitLabel("info_end", Unit->getID());
1571       
1572     Asm->EOL();
1573   }
1574
1575   void EmitDebugInfo() {
1576     // Start debug info section.
1577     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1578
1579     if (MainCU) {
1580       EmitDebugInfoPerCU(MainCU);
1581       return;
1582     }
1583
1584     for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1585       EmitDebugInfoPerCU(CompileUnits[i]);
1586   }
1587
1588   /// EmitAbbreviations - Emit the abbreviation section.
1589   ///
1590   void EmitAbbreviations() const {
1591     // Check to see if it is worth the effort.
1592     if (!Abbreviations.empty()) {
1593       // Start the debug abbrev section.
1594       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1595
1596       EmitLabel("abbrev_begin", 0);
1597
1598       // For each abbrevation.
1599       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1600         // Get abbreviation data
1601         const DIEAbbrev *Abbrev = Abbreviations[i];
1602
1603         // Emit the abbrevations code (base 1 index.)
1604         Asm->EmitULEB128Bytes(Abbrev->getNumber());
1605         Asm->EOL("Abbreviation Code");
1606
1607         // Emit the abbreviations data.
1608         Abbrev->Emit(Asm);
1609
1610         Asm->EOL();
1611       }
1612
1613       // Mark end of abbreviations.
1614       Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
1615
1616       EmitLabel("abbrev_end", 0);
1617
1618       Asm->EOL();
1619     }
1620   }
1621
1622   /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
1623   /// the line matrix.
1624   ///
1625   void EmitEndOfLineMatrix(unsigned SectionEnd) {
1626     // Define last address of section.
1627     Asm->EmitInt8(0); Asm->EOL("Extended Op");
1628     Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1629     Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1630     EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
1631
1632     // Mark end of matrix.
1633     Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
1634     Asm->EmitULEB128Bytes(1); Asm->EOL();
1635     Asm->EmitInt8(1); Asm->EOL();
1636   }
1637
1638   /// EmitDebugLines - Emit source line information.
1639   ///
1640   void EmitDebugLines() {
1641     // If the target is using .loc/.file, the assembler will be emitting the
1642     // .debug_line table automatically.
1643     if (TAI->hasDotLocAndDotFile())
1644       return;
1645
1646     // Minimum line delta, thus ranging from -10..(255-10).
1647     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
1648     // Maximum line delta, thus ranging from -10..(255-10).
1649     const int MaxLineDelta = 255 + MinLineDelta;
1650
1651     // Start the dwarf line section.
1652     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1653
1654     // Construct the section header.
1655
1656     EmitDifference("line_end", 0, "line_begin", 0, true);
1657     Asm->EOL("Length of Source Line Info");
1658     EmitLabel("line_begin", 0);
1659
1660     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
1661
1662     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
1663     Asm->EOL("Prolog Length");
1664     EmitLabel("line_prolog_begin", 0);
1665
1666     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
1667
1668     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
1669
1670     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
1671
1672     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
1673
1674     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
1675
1676     // Line number standard opcode encodings argument count
1677     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
1678     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
1679     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
1680     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
1681     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
1682     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
1683     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
1684     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
1685     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
1686
1687     // Emit directories.
1688     for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
1689       Asm->EmitString(getSourceDirectoryName(DI));
1690       Asm->EOL("Directory");
1691     }
1692     Asm->EmitInt8(0); Asm->EOL("End of directories");
1693
1694     // Emit files.
1695     for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
1696       // Remember source id starts at 1.
1697       std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
1698       Asm->EmitString(getSourceFileName(Id.second));
1699       Asm->EOL("Source");
1700       Asm->EmitULEB128Bytes(Id.first);
1701       Asm->EOL("Directory #");
1702       Asm->EmitULEB128Bytes(0);
1703       Asm->EOL("Mod date");
1704       Asm->EmitULEB128Bytes(0);
1705       Asm->EOL("File size");
1706     }
1707     Asm->EmitInt8(0); Asm->EOL("End of files");
1708
1709     EmitLabel("line_prolog_end", 0);
1710
1711     // A sequence for each text section.
1712     unsigned SecSrcLinesSize = SectionSourceLines.size();
1713
1714     for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
1715       // Isolate current sections line info.
1716       const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
1717
1718       if (Asm->isVerbose()) {
1719         const Section* S = SectionMap[j + 1];
1720         O << '\t' << TAI->getCommentString() << " Section"
1721           << S->getName() << '\n';
1722       } else
1723         Asm->EOL();
1724
1725       // Dwarf assumes we start with first line of first source file.
1726       unsigned Source = 1;
1727       unsigned Line = 1;
1728
1729       // Construct rows of the address, source, line, column matrix.
1730       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1731         const SrcLineInfo &LineInfo = LineInfos[i];
1732         unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
1733         if (!LabelID) continue;
1734
1735         if (!Asm->isVerbose())
1736           Asm->EOL();
1737         else {
1738           std::pair<unsigned, unsigned> SourceID =
1739             getSourceDirectoryAndFileIds(LineInfo.getSourceID());
1740           O << '\t' << TAI->getCommentString() << ' '
1741             << getSourceDirectoryName(SourceID.first) << ' '
1742             << getSourceFileName(SourceID.second)
1743             <<" :" << utostr_32(LineInfo.getLine()) << '\n';
1744         }
1745
1746         // Define the line address.
1747         Asm->EmitInt8(0); Asm->EOL("Extended Op");
1748         Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1749         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1750         EmitReference("label",  LabelID); Asm->EOL("Location label");
1751
1752         // If change of source, then switch to the new source.
1753         if (Source != LineInfo.getSourceID()) {
1754           Source = LineInfo.getSourceID();
1755           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
1756           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
1757         }
1758
1759         // If change of line.
1760         if (Line != LineInfo.getLine()) {
1761           // Determine offset.
1762           int Offset = LineInfo.getLine() - Line;
1763           int Delta = Offset - MinLineDelta;
1764
1765           // Update line.
1766           Line = LineInfo.getLine();
1767
1768           // If delta is small enough and in range...
1769           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
1770             // ... then use fast opcode.
1771             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
1772           } else {
1773             // ... otherwise use long hand.
1774             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
1775             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
1776             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1777           }
1778         } else {
1779           // Copy the previous row (different address or source)
1780           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1781         }
1782       }
1783
1784       EmitEndOfLineMatrix(j + 1);
1785     }
1786
1787     if (SecSrcLinesSize == 0)
1788       // Because we're emitting a debug_line section, we still need a line
1789       // table. The linker and friends expect it to exist. If there's nothing to
1790       // put into it, emit an empty table.
1791       EmitEndOfLineMatrix(1);
1792
1793     EmitLabel("line_end", 0);
1794
1795     Asm->EOL();
1796   }
1797
1798   /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
1799   ///
1800   void EmitCommonDebugFrame() {
1801     if (!TAI->doesDwarfRequireFrameSection())
1802       return;
1803
1804     int stackGrowth =
1805         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1806           TargetFrameInfo::StackGrowsUp ?
1807         TD->getPointerSize() : -TD->getPointerSize();
1808
1809     // Start the dwarf frame section.
1810     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1811
1812     EmitLabel("debug_frame_common", 0);
1813     EmitDifference("debug_frame_common_end", 0,
1814                    "debug_frame_common_begin", 0, true);
1815     Asm->EOL("Length of Common Information Entry");
1816
1817     EmitLabel("debug_frame_common_begin", 0);
1818     Asm->EmitInt32((int)DW_CIE_ID);
1819     Asm->EOL("CIE Identifier Tag");
1820     Asm->EmitInt8(DW_CIE_VERSION);
1821     Asm->EOL("CIE Version");
1822     Asm->EmitString("");
1823     Asm->EOL("CIE Augmentation");
1824     Asm->EmitULEB128Bytes(1);
1825     Asm->EOL("CIE Code Alignment Factor");
1826     Asm->EmitSLEB128Bytes(stackGrowth);
1827     Asm->EOL("CIE Data Alignment Factor");
1828     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
1829     Asm->EOL("CIE RA Column");
1830
1831     std::vector<MachineMove> Moves;
1832     RI->getInitialFrameState(Moves);
1833
1834     EmitFrameMoves(NULL, 0, Moves, false);
1835
1836     Asm->EmitAlignment(2, 0, 0, false);
1837     EmitLabel("debug_frame_common_end", 0);
1838
1839     Asm->EOL();
1840   }
1841
1842   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
1843   /// section.
1844   void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
1845     if (!TAI->doesDwarfRequireFrameSection())
1846       return;
1847
1848     // Start the dwarf frame section.
1849     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1850
1851     EmitDifference("debug_frame_end", DebugFrameInfo.Number,
1852                    "debug_frame_begin", DebugFrameInfo.Number, true);
1853     Asm->EOL("Length of Frame Information Entry");
1854
1855     EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
1856
1857     EmitSectionOffset("debug_frame_common", "section_debug_frame",
1858                       0, 0, true, false);
1859     Asm->EOL("FDE CIE offset");
1860
1861     EmitReference("func_begin", DebugFrameInfo.Number);
1862     Asm->EOL("FDE initial location");
1863     EmitDifference("func_end", DebugFrameInfo.Number,
1864                    "func_begin", DebugFrameInfo.Number);
1865     Asm->EOL("FDE address range");
1866
1867     EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, 
1868                    false);
1869
1870     Asm->EmitAlignment(2, 0, 0, false);
1871     EmitLabel("debug_frame_end", DebugFrameInfo.Number);
1872
1873     Asm->EOL();
1874   }
1875
1876   void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
1877     EmitDifference("pubnames_end", Unit->getID(),
1878                    "pubnames_begin", Unit->getID(), true);
1879     Asm->EOL("Length of Public Names Info");
1880       
1881     EmitLabel("pubnames_begin", Unit->getID());
1882       
1883     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
1884       
1885     EmitSectionOffset("info_begin", "section_info",
1886                       Unit->getID(), 0, true, false);
1887     Asm->EOL("Offset of Compilation Unit Info");
1888       
1889     EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
1890                    true);
1891     Asm->EOL("Compilation Unit Length");
1892       
1893     StringMap<DIE*> &Globals = Unit->getGlobals();
1894     for (StringMap<DIE*>::const_iterator
1895            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1896       const char *Name = GI->getKeyData();
1897       DIE * Entity = GI->second;
1898         
1899       Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
1900       Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
1901     }
1902       
1903     Asm->EmitInt32(0); Asm->EOL("End Mark");
1904     EmitLabel("pubnames_end", Unit->getID());
1905       
1906     Asm->EOL();
1907   }
1908
1909   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
1910   ///
1911   void EmitDebugPubNames() {
1912     // Start the dwarf pubnames section.
1913     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1914
1915     if (MainCU) {
1916       EmitDebugPubNamesPerCU(MainCU);
1917       return;
1918     }
1919
1920     for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1921       EmitDebugPubNamesPerCU(CompileUnits[i]);
1922   }
1923
1924   /// EmitDebugStr - Emit visible names into a debug str section.
1925   ///
1926   void EmitDebugStr() {
1927     // Check to see if it is worth the effort.
1928     if (!StringPool.empty()) {
1929       // Start the dwarf str section.
1930       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1931
1932       // For each of strings in the string pool.
1933       for (unsigned StringID = 1, N = StringPool.size();
1934            StringID <= N; ++StringID) {
1935         // Emit a label for reference from debug information entries.
1936         EmitLabel("string", StringID);
1937         // Emit the string itself.
1938         const std::string &String = StringPool[StringID];
1939         Asm->EmitString(String); Asm->EOL();
1940       }
1941
1942       Asm->EOL();
1943     }
1944   }
1945
1946   /// EmitDebugLoc - Emit visible names into a debug loc section.
1947   ///
1948   void EmitDebugLoc() {
1949     // Start the dwarf loc section.
1950     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1951
1952     Asm->EOL();
1953   }
1954
1955   /// EmitDebugARanges - Emit visible names into a debug aranges section.
1956   ///
1957   void EmitDebugARanges() {
1958     // Start the dwarf aranges section.
1959     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1960
1961     // FIXME - Mock up
1962 #if 0
1963     CompileUnit *Unit = GetBaseCompileUnit();
1964
1965     // Don't include size of length
1966     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
1967
1968     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
1969
1970     EmitReference("info_begin", Unit->getID());
1971     Asm->EOL("Offset of Compilation Unit Info");
1972
1973     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
1974
1975     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
1976
1977     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
1978     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
1979
1980     // Range 1
1981     EmitReference("text_begin", 0); Asm->EOL("Address");
1982     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
1983
1984     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
1985     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
1986 #endif
1987
1988     Asm->EOL();
1989   }
1990
1991   /// EmitDebugRanges - Emit visible names into a debug ranges section.
1992   ///
1993   void EmitDebugRanges() {
1994     // Start the dwarf ranges section.
1995     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1996
1997     Asm->EOL();
1998   }
1999
2000   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2001   ///
2002   void EmitDebugMacInfo() {
2003     if (TAI->doesSupportMacInfoSection()) {
2004       // Start the dwarf macinfo section.
2005       Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2006
2007       Asm->EOL();
2008     }
2009   }
2010
2011   /// EmitDebugInlineInfo - Emit inline info using following format.
2012   /// Section Header:
2013   /// 1. length of section
2014   /// 2. Dwarf version number
2015   /// 3. address size.
2016   ///
2017   /// Entries (one "entry" for each function that was inlined):
2018   ///
2019   /// 1. offset into __debug_str section for MIPS linkage name, if exists; 
2020   ///   otherwise offset into __debug_str for regular function name.
2021   /// 2. offset into __debug_str section for regular function name.
2022   /// 3. an unsigned LEB128 number indicating the number of distinct inlining 
2023   /// instances for the function.
2024   /// 
2025   /// The rest of the entry consists of a {die_offset, low_pc}  pair for each 
2026   /// inlined instance; the die_offset points to the inlined_subroutine die in
2027   /// the __debug_info section, and the low_pc is the starting address  for the
2028   ///  inlining instance.
2029   void EmitDebugInlineInfo() {
2030     if (!TAI->doesDwarfUsesInlineInfoSection())
2031       return;
2032
2033     if (!MainCU)
2034       return;
2035
2036     Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2037     Asm->EOL();
2038     EmitDifference("debug_inlined_end", 1,
2039                    "debug_inlined_begin", 1, true);
2040     Asm->EOL("Length of Debug Inlined Information Entry");
2041
2042     EmitLabel("debug_inlined_begin", 1);
2043
2044     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2045     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2046
2047     for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator 
2048            I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2049       GlobalVariable *GV = I->first;
2050       SmallVector<unsigned, 4> &Labels = I->second;
2051       DISubprogram SP(GV);
2052       std::string Name;
2053       std::string LName;
2054
2055       SP.getLinkageName(LName);
2056       SP.getName(Name);
2057
2058       Asm->EmitString(LName.empty() ? Name : LName);
2059       Asm->EOL("MIPS linkage name");
2060
2061       Asm->EmitString(Name); Asm->EOL("Function name");
2062
2063       Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2064
2065       for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2066              LE = Labels.end(); LI != LE; ++LI) {
2067         DIE *SP = MainCU->getDieMapSlotFor(GV);
2068         Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2069
2070         if (TD->getPointerSize() == sizeof(int32_t))
2071           O << TAI->getData32bitsDirective();
2072         else
2073           O << TAI->getData64bitsDirective();
2074         PrintLabelName("label", *LI); Asm->EOL("low_pc");
2075       }
2076     }
2077
2078     EmitLabel("debug_inlined_end", 1);
2079     Asm->EOL();
2080   }
2081
2082   /// GetOrCreateSourceID - Look up the source id with the given directory and
2083   /// source file names. If none currently exists, create a new id and insert it
2084   /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2085   /// as well.
2086   unsigned GetOrCreateSourceID(const std::string &DirName,
2087                                const std::string &FileName) {
2088     unsigned DId;
2089     StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2090     if (DI != DirectoryIdMap.end()) {
2091       DId = DI->getValue();
2092     } else {
2093       DId = DirectoryNames.size() + 1;
2094       DirectoryIdMap[DirName] = DId;
2095       DirectoryNames.push_back(DirName);
2096     }
2097   
2098     unsigned FId;
2099     StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2100     if (FI != SourceFileIdMap.end()) {
2101       FId = FI->getValue();
2102     } else {
2103       FId = SourceFileNames.size() + 1;
2104       SourceFileIdMap[FileName] = FId;
2105       SourceFileNames.push_back(FileName);
2106     }
2107
2108     DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2109       SourceIdMap.find(std::make_pair(DId, FId));
2110     if (SI != SourceIdMap.end())
2111       return SI->second;
2112
2113     unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
2114     SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2115     SourceIds.push_back(std::make_pair(DId, FId));
2116
2117     return SrcId;
2118   }
2119
2120   void ConstructCompileUnit(GlobalVariable *GV) {
2121     DICompileUnit DIUnit(GV);
2122     std::string Dir, FN, Prod;
2123     unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
2124                                       DIUnit.getFilename(FN));
2125
2126     DIE *Die = new DIE(DW_TAG_compile_unit);
2127     AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2128                      DWLabel("section_line", 0), DWLabel("section_line", 0),
2129                      false);
2130     AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2131     AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2132     AddString(Die, DW_AT_name, DW_FORM_string, FN);
2133     if (!Dir.empty())
2134       AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2135     if (DIUnit.isOptimized())
2136       AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2137     std::string Flags;
2138     DIUnit.getFlags(Flags);
2139     if (!Flags.empty())
2140       AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2141     unsigned RVer = DIUnit.getRunTimeVersion();
2142     if (RVer)
2143       AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2144
2145     CompileUnit *Unit = new CompileUnit(ID, Die);
2146     if (DIUnit.isMain()) {
2147       assert(!MainCU && "Multiple main compile units are found!");
2148       MainCU = Unit;
2149     }
2150     CompileUnitMap[DIUnit.getGV()] = Unit;
2151     CompileUnits.push_back(Unit);
2152   }
2153
2154   /// ConstructCompileUnits - Create a compile unit DIEs.
2155   void ConstructCompileUnits() {
2156     GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2157     if (!Root)
2158       return;
2159     assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2160            "Malformed compile unit descriptor anchor type");
2161     Constant *RootC = cast<Constant>(*Root->use_begin());
2162     assert(RootC->hasNUsesOrMore(1) &&
2163            "Malformed compile unit descriptor anchor type");
2164     for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2165          UI != UE; ++UI)
2166       for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2167            UUI != UUE; ++UUI) {
2168         GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2169         ConstructCompileUnit(GV);
2170       }
2171   }
2172
2173   bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2174     DIGlobalVariable DI_GV(GV);
2175     CompileUnit *DW_Unit = MainCU;
2176     if (!DW_Unit)
2177       DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
2178
2179     // Check for pre-existence.
2180     DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2181     if (Slot)
2182       return false;
2183
2184     DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2185
2186     // Add address.
2187     DIEBlock *Block = new DIEBlock();
2188     AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2189     std::string GLN;
2190     AddObjectLabel(Block, 0, DW_FORM_udata,
2191                    Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
2192     AddBlock(VariableDie, DW_AT_location, 0, Block);
2193
2194     // Add to map.
2195     Slot = VariableDie;
2196
2197     // Add to context owner.
2198     DW_Unit->getDie()->AddChild(VariableDie);
2199
2200     // Expose as global. FIXME - need to check external flag.
2201     std::string Name;
2202     DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2203     return true;
2204   }
2205
2206   /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally 
2207   /// visible global variables. Return true if at least one global DIE is
2208   /// created.
2209   bool ConstructGlobalVariableDIEs() {
2210     GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2211     if (!Root)
2212       return false;
2213
2214     assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2215            "Malformed global variable descriptor anchor type");
2216     Constant *RootC = cast<Constant>(*Root->use_begin());
2217     assert(RootC->hasNUsesOrMore(1) &&
2218            "Malformed global variable descriptor anchor type");
2219
2220     bool Result = false;
2221     for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2222          UI != UE; ++UI)
2223       for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2224            UUI != UUE; ++UUI)
2225         Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
2226
2227     return Result;
2228   }
2229
2230   bool ConstructSubprogram(GlobalVariable *GV) {
2231     DISubprogram SP(GV);
2232     CompileUnit *Unit = MainCU;
2233     if (!Unit)
2234       Unit = &FindCompileUnit(SP.getCompileUnit());
2235
2236     // Check for pre-existence.
2237     DIE *&Slot = Unit->getDieMapSlotFor(GV);
2238     if (Slot)
2239       return false;
2240
2241     if (!SP.isDefinition())
2242       // This is a method declaration which will be handled while
2243       // constructing class type.
2244       return false;
2245
2246     DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2247
2248     // Add to map.
2249     Slot = SubprogramDie;
2250     // Add to context owner.
2251     Unit->getDie()->AddChild(SubprogramDie);
2252     // Expose as global.
2253     std::string Name;
2254     Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2255     return true;
2256   }
2257
2258   /// ConstructSubprograms - Create DIEs for each of the externally visible
2259   /// subprograms. Return true if at least one subprogram DIE is created.
2260   bool ConstructSubprograms() {
2261     GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2262     if (!Root)
2263       return false;
2264
2265     assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2266            "Malformed subprogram descriptor anchor type");
2267     Constant *RootC = cast<Constant>(*Root->use_begin());
2268     assert(RootC->hasNUsesOrMore(1) &&
2269            "Malformed subprogram descriptor anchor type");
2270
2271     bool Result = false;
2272     for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2273          UI != UE; ++UI)
2274       for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2275            UUI != UUE; ++UUI)
2276         Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
2277
2278     return Result;
2279   }
2280
2281 public:
2282   //===--------------------------------------------------------------------===//
2283   // Main entry points.
2284   //
2285   DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2286     : Dwarf(OS, A, T, "dbg"), MainCU(0),
2287       AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
2288       ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
2289       SectionSourceLines(), didInitial(false), shouldEmit(false),
2290       FunctionDbgScope(0), DebugTimer(0) {
2291     if (TimePassesIsEnabled)
2292       DebugTimer = new Timer("Dwarf Debug Writer",
2293                              getDwarfTimerGroup());
2294   }
2295   virtual ~DwarfDebug() {
2296     for (unsigned j = 0, M = Values.size(); j < M; ++j)
2297       delete Values[j];
2298
2299     for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
2300            I = AbstractInstanceRootMap.begin(),
2301            E = AbstractInstanceRootMap.end(); I != E;++I)
2302       delete I->second;
2303
2304     delete DebugTimer;
2305   }
2306
2307   /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
2308   /// be emitted.
2309   bool ShouldEmitDwarfDebug() const { return shouldEmit; }
2310
2311   /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2312   /// This is inovked by the target AsmPrinter.
2313   void SetDebugInfo(MachineModuleInfo *mmi) {
2314     if (TimePassesIsEnabled)
2315       DebugTimer->startTimer();
2316
2317     // Create all the compile unit DIEs.
2318     ConstructCompileUnits();
2319       
2320     if (CompileUnits.empty()) {
2321       if (TimePassesIsEnabled)
2322         DebugTimer->stopTimer();
2323
2324       return;
2325     }
2326
2327     // Create DIEs for each of the externally visible global variables.
2328     bool globalDIEs = ConstructGlobalVariableDIEs();
2329
2330     // Create DIEs for each of the externally visible subprograms.
2331     bool subprogramDIEs = ConstructSubprograms();
2332
2333     // If there is not any debug info available for any global variables
2334     // and any subprograms then there is not any debug info to emit.
2335     if (!globalDIEs && !subprogramDIEs) {
2336       if (TimePassesIsEnabled)
2337         DebugTimer->stopTimer();
2338
2339       return;
2340     }
2341
2342     MMI = mmi;
2343     shouldEmit = true;
2344     MMI->setDebugInfoAvailability(true);
2345
2346     // Prime section data.
2347     SectionMap.insert(TAI->getTextSection());
2348
2349     // Print out .file directives to specify files for .loc directives. These
2350     // are printed out early so that they precede any .loc directives.
2351     if (TAI->hasDotLocAndDotFile()) {
2352       for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2353         // Remember source id starts at 1.
2354         std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2355         sys::Path FullPath(getSourceDirectoryName(Id.first));
2356         bool AppendOk =
2357           FullPath.appendComponent(getSourceFileName(Id.second));
2358         assert(AppendOk && "Could not append filename to directory!");
2359         AppendOk = false;
2360         Asm->EmitFile(i, FullPath.toString());
2361         Asm->EOL();
2362       }
2363     }
2364
2365     // Emit initial sections
2366     EmitInitial();
2367
2368     if (TimePassesIsEnabled)
2369       DebugTimer->stopTimer();
2370   }
2371
2372   /// BeginModule - Emit all Dwarf sections that should come prior to the
2373   /// content.
2374   void BeginModule(Module *M) {
2375     this->M = M;
2376   }
2377
2378   /// EndModule - Emit all Dwarf sections that should come after the content.
2379   ///
2380   void EndModule() {
2381     if (!ShouldEmitDwarfDebug())
2382       return;
2383
2384     if (TimePassesIsEnabled)
2385       DebugTimer->startTimer();
2386
2387     // Standard sections final addresses.
2388     Asm->SwitchToSection(TAI->getTextSection());
2389     EmitLabel("text_end", 0);
2390     Asm->SwitchToSection(TAI->getDataSection());
2391     EmitLabel("data_end", 0);
2392
2393     // End text sections.
2394     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2395       Asm->SwitchToSection(SectionMap[i]);
2396       EmitLabel("section_end", i);
2397     }
2398
2399     // Emit common frame information.
2400     EmitCommonDebugFrame();
2401
2402     // Emit function debug frame information
2403     for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2404            E = DebugFrames.end(); I != E; ++I)
2405       EmitFunctionDebugFrame(*I);
2406
2407     // Compute DIE offsets and sizes.
2408     SizeAndOffsets();
2409
2410     // Emit all the DIEs into a debug info section
2411     EmitDebugInfo();
2412
2413     // Corresponding abbreviations into a abbrev section.
2414     EmitAbbreviations();
2415
2416     // Emit source line correspondence into a debug line section.
2417     EmitDebugLines();
2418
2419     // Emit info into a debug pubnames section.
2420     EmitDebugPubNames();
2421
2422     // Emit info into a debug str section.
2423     EmitDebugStr();
2424
2425     // Emit info into a debug loc section.
2426     EmitDebugLoc();
2427
2428     // Emit info into a debug aranges section.
2429     EmitDebugARanges();
2430
2431     // Emit info into a debug ranges section.
2432     EmitDebugRanges();
2433
2434     // Emit info into a debug macinfo section.
2435     EmitDebugMacInfo();
2436
2437     // Emit inline info.
2438     EmitDebugInlineInfo();
2439
2440     if (TimePassesIsEnabled)
2441       DebugTimer->stopTimer();
2442   }
2443
2444   /// BeginFunction - Gather pre-function debug information.  Assumes being
2445   /// emitted immediately after the function entry point.
2446   void BeginFunction(MachineFunction *MF) {
2447     this->MF = MF;
2448
2449     if (!ShouldEmitDwarfDebug()) return;
2450
2451     if (TimePassesIsEnabled)
2452       DebugTimer->startTimer();
2453
2454     // Begin accumulating function debug information.
2455     MMI->BeginFunction(MF);
2456
2457     // Assumes in correct section after the entry point.
2458     EmitLabel("func_begin", ++SubprogramCount);
2459
2460     // Emit label for the implicitly defined dbg.stoppoint at the start of
2461     // the function.
2462     DebugLoc FDL = MF->getDefaultDebugLoc();
2463     if (!FDL.isUnknown()) {
2464       DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2465       unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
2466                                           DICompileUnit(DLT.CompileUnit));
2467       Asm->printLabel(LabelID);
2468     }
2469
2470     if (TimePassesIsEnabled)
2471       DebugTimer->stopTimer();
2472   }
2473
2474   /// EndFunction - Gather and emit post-function debug information.
2475   ///
2476   void EndFunction(MachineFunction *MF) {
2477     if (!ShouldEmitDwarfDebug()) return;
2478
2479     if (TimePassesIsEnabled)
2480       DebugTimer->startTimer();
2481
2482     // Define end label for subprogram.
2483     EmitLabel("func_end", SubprogramCount);
2484
2485     // Get function line info.
2486     if (!Lines.empty()) {
2487       // Get section line info.
2488       unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2489       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2490       std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2491       // Append the function info to section info.
2492       SectionLineInfos.insert(SectionLineInfos.end(),
2493                               Lines.begin(), Lines.end());
2494     }
2495
2496     // Construct the DbgScope for abstract instances.
2497     for (SmallVector<DbgScope *, 32>::iterator
2498            I = AbstractInstanceRootList.begin(),
2499            E = AbstractInstanceRootList.end(); I != E; ++I)
2500       ConstructAbstractDbgScope(*I);
2501
2502     // Construct scopes for subprogram.
2503     if (FunctionDbgScope)
2504       ConstructFunctionDbgScope(FunctionDbgScope);
2505     else
2506       // FIXME: This is wrong. We are essentially getting past a problem with
2507       // debug information not being able to handle unreachable blocks that have
2508       // debug information in them. In particular, those unreachable blocks that
2509       // have "region end" info in them. That situation results in the "root
2510       // scope" not being created. If that's the case, then emit a "default"
2511       // scope, i.e., one that encompasses the whole function. This isn't
2512       // desirable. And a better way of handling this (and all of the debugging
2513       // information) needs to be explored.
2514       ConstructDefaultDbgScope(MF);
2515
2516     DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2517                                                  MMI->getFrameMoves()));
2518
2519     // Clear debug info
2520     if (FunctionDbgScope) {
2521       delete FunctionDbgScope;
2522       DbgScopeMap.clear();
2523       DbgAbstractScopeMap.clear();
2524       DbgConcreteScopeMap.clear();
2525       InlinedVariableScopes.clear();
2526       FunctionDbgScope = NULL;
2527       LexicalScopeStack.clear();
2528       AbstractInstanceRootList.clear();
2529     }
2530
2531     Lines.clear();
2532
2533     if (TimePassesIsEnabled)
2534       DebugTimer->stopTimer();
2535   }
2536
2537   /// RecordSourceLine - Records location information and associates it with a 
2538   /// label. Returns a unique label ID used to generate a label and provide
2539   /// correspondence to the source line list.
2540   unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2541     if (TimePassesIsEnabled)
2542       DebugTimer->startTimer();
2543
2544     CompileUnit *Unit = CompileUnitMap[V];
2545     assert(Unit && "Unable to find CompileUnit");
2546     unsigned ID = MMI->NextLabelID();
2547     Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2548
2549     if (TimePassesIsEnabled)
2550       DebugTimer->stopTimer();
2551
2552     return ID;
2553   }
2554   
2555   /// RecordSourceLine - Records location information and associates it with a 
2556   /// label. Returns a unique label ID used to generate a label and provide
2557   /// correspondence to the source line list.
2558   unsigned RecordSourceLine(unsigned Line, unsigned Col, DICompileUnit CU) {
2559     if (TimePassesIsEnabled)
2560       DebugTimer->startTimer();
2561
2562     std::string Dir, Fn;
2563     unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
2564                                        CU.getFilename(Fn));
2565     unsigned ID = MMI->NextLabelID();
2566     Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2567
2568     if (TimePassesIsEnabled)
2569       DebugTimer->stopTimer();
2570
2571     return ID;
2572   }
2573
2574   /// getRecordSourceLineCount - Return the number of source lines in the debug
2575   /// info.
2576   unsigned getRecordSourceLineCount() const {
2577     return Lines.size();
2578   }
2579                             
2580   /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2581   /// timed. Look up the source id with the given directory and source file
2582   /// names. If none currently exists, create a new id and insert it in the
2583   /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2584   /// well.
2585   unsigned getOrCreateSourceID(const std::string &DirName,
2586                                const std::string &FileName) {
2587     if (TimePassesIsEnabled)
2588       DebugTimer->startTimer();
2589
2590     unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
2591
2592     if (TimePassesIsEnabled)
2593       DebugTimer->stopTimer();
2594
2595     return SrcId;
2596   }
2597
2598   /// RecordRegionStart - Indicate the start of a region.
2599   unsigned RecordRegionStart(GlobalVariable *V) {
2600     if (TimePassesIsEnabled)
2601       DebugTimer->startTimer();
2602
2603     DbgScope *Scope = getOrCreateScope(V);
2604     unsigned ID = MMI->NextLabelID();
2605     if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2606     LexicalScopeStack.push_back(Scope);
2607
2608     if (TimePassesIsEnabled)
2609       DebugTimer->stopTimer();
2610
2611     return ID;
2612   }
2613
2614   /// RecordRegionEnd - Indicate the end of a region.
2615   unsigned RecordRegionEnd(GlobalVariable *V) {
2616     if (TimePassesIsEnabled)
2617       DebugTimer->startTimer();
2618
2619     DbgScope *Scope = getOrCreateScope(V);
2620     unsigned ID = MMI->NextLabelID();
2621     Scope->setEndLabelID(ID);
2622     if (LexicalScopeStack.size() != 0)
2623       LexicalScopeStack.pop_back();
2624
2625     if (TimePassesIsEnabled)
2626       DebugTimer->stopTimer();
2627
2628     return ID;
2629   }
2630
2631   /// RecordVariable - Indicate the declaration of  a local variable.
2632   void RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
2633                       const MachineInstr *MI) {
2634     if (TimePassesIsEnabled)
2635       DebugTimer->startTimer();
2636
2637     DIDescriptor Desc(GV);
2638     DbgScope *Scope = NULL;
2639
2640     if (Desc.getTag() == DW_TAG_variable) {
2641       // GV is a global variable.
2642       DIGlobalVariable DG(GV);
2643       Scope = getOrCreateScope(DG.getContext().getGV());
2644     } else {
2645       DenseMap<const MachineInstr *, DbgScope *>::iterator 
2646         SI = InlinedVariableScopes.find(MI);
2647
2648       if (SI != InlinedVariableScopes.end()) {
2649         // or GV is an inlined local variable.
2650         Scope = SI->second;
2651       } else {
2652         DIVariable DV(GV);
2653         GlobalVariable *V = DV.getContext().getGV();
2654
2655         // FIXME: The code that checks for the inlined local variable is a hack!
2656         DenseMap<const GlobalVariable *, DbgScope *>::iterator
2657           AI = AbstractInstanceRootMap.find(V);
2658
2659         if (AI != AbstractInstanceRootMap.end())
2660           // or GV is an inlined local variable.
2661           Scope = AI->second;
2662         else
2663           // or GV is a local variable.
2664           Scope = getOrCreateScope(V);
2665       }
2666     }
2667
2668     assert(Scope && "Unable to find the variable's scope");
2669     DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
2670     Scope->AddVariable(DV);
2671
2672     if (TimePassesIsEnabled)
2673       DebugTimer->stopTimer();
2674   }
2675
2676   //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
2677   unsigned RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
2678                                 unsigned Line, unsigned Col) {
2679     unsigned LabelID = MMI->NextLabelID();
2680
2681     if (!TAI->doesDwarfUsesInlineInfoSection())
2682       return LabelID;
2683
2684     if (TimePassesIsEnabled)
2685       DebugTimer->startTimer();
2686
2687     GlobalVariable *GV = SP.getGV();
2688     DenseMap<const GlobalVariable *, DbgScope *>::iterator
2689       II = AbstractInstanceRootMap.find(GV);
2690
2691     if (II == AbstractInstanceRootMap.end()) {
2692       // Create an abstract instance entry for this inlined function if it
2693       // doesn't already exist.
2694       DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
2695
2696       // Get the compile unit context.
2697       CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2698       DIE *SPDie = Unit->getDieMapSlotFor(GV);
2699       if (!SPDie)
2700         SPDie = CreateSubprogramDIE(Unit, SP);
2701
2702       // Mark as being inlined. This makes this subprogram entry an abstract
2703       // instance root.
2704       // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
2705       // that it's defined. It probably won't change in the future, but this
2706       // could be more elegant.
2707       AddUInt(SPDie, DW_AT_inline, 0, DW_INL_declared_not_inlined);
2708
2709       // Keep track of the abstract scope for this function.
2710       DbgAbstractScopeMap[GV] = Scope;
2711
2712       AbstractInstanceRootMap[GV] = Scope;
2713       AbstractInstanceRootList.push_back(Scope);
2714     }
2715
2716     // Create a concrete inlined instance for this inlined function.
2717     DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
2718     DIE *ScopeDie = new DIE(DW_TAG_inlined_subroutine);
2719     CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2720     ScopeDie->setAbstractCompileUnit(Unit);
2721
2722     DIE *Origin = Unit->getDieMapSlotFor(GV);
2723     AddDIEEntry(ScopeDie, DW_AT_abstract_origin, DW_FORM_ref4, Origin);
2724     AddUInt(ScopeDie, DW_AT_call_file, 0, Unit->getID());
2725     AddUInt(ScopeDie, DW_AT_call_line, 0, Line);
2726     AddUInt(ScopeDie, DW_AT_call_column, 0, Col);
2727
2728     ConcreteScope->setDie(ScopeDie);
2729     ConcreteScope->setStartLabelID(LabelID);
2730     MMI->RecordUsedDbgLabel(LabelID);
2731
2732     LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2733
2734     // Keep track of the concrete scope that's inlined into this function.
2735     DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2736       SI = DbgConcreteScopeMap.find(GV);
2737
2738     if (SI == DbgConcreteScopeMap.end())
2739       DbgConcreteScopeMap[GV].push_back(ConcreteScope);
2740     else
2741       SI->second.push_back(ConcreteScope);
2742
2743     // Track the start label for this inlined function.
2744     DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2745       I = InlineInfo.find(GV);
2746
2747     if (I == InlineInfo.end())
2748       InlineInfo[GV].push_back(LabelID);
2749     else
2750       I->second.push_back(LabelID);
2751
2752     if (TimePassesIsEnabled)
2753       DebugTimer->stopTimer();
2754
2755     return LabelID;
2756   }
2757
2758   /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2759   unsigned RecordInlinedFnEnd(DISubprogram &SP) {
2760     if (!TAI->doesDwarfUsesInlineInfoSection())
2761       return 0;
2762
2763     if (TimePassesIsEnabled)
2764       DebugTimer->startTimer();
2765
2766     GlobalVariable *GV = SP.getGV();
2767     DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2768       I = DbgConcreteScopeMap.find(GV);
2769
2770     if (I == DbgConcreteScopeMap.end()) {
2771       if (TimePassesIsEnabled)
2772         DebugTimer->stopTimer();
2773
2774       return 0;
2775     }
2776
2777     SmallVector<DbgScope *, 8> &Scopes = I->second;
2778     assert(!Scopes.empty() && "We should have at least one debug scope!");
2779     DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2780     unsigned ID = MMI->NextLabelID();
2781     MMI->RecordUsedDbgLabel(ID);
2782     Scope->setEndLabelID(ID);
2783
2784     if (TimePassesIsEnabled)
2785       DebugTimer->stopTimer();
2786
2787     return ID;
2788   }
2789
2790   /// RecordVariableScope - Record scope for the variable declared by
2791   /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
2792   /// for only inlined subroutine variables. Other variables's scopes are
2793   /// determined during RecordVariable().
2794   void RecordVariableScope(DIVariable &DV, const MachineInstr *DeclareMI) {
2795     if (TimePassesIsEnabled)
2796       DebugTimer->startTimer();
2797
2798     DISubprogram SP(DV.getContext().getGV());
2799
2800     if (SP.isNull()) {
2801       if (TimePassesIsEnabled)
2802         DebugTimer->stopTimer();
2803
2804       return;
2805     }
2806
2807     DenseMap<GlobalVariable *, DbgScope *>::iterator
2808       I = DbgAbstractScopeMap.find(SP.getGV());
2809     if (I != DbgAbstractScopeMap.end())
2810       InlinedVariableScopes[DeclareMI] = I->second;
2811
2812     if (TimePassesIsEnabled)
2813       DebugTimer->stopTimer();
2814   }
2815 };
2816
2817 } // End of namespace llvm
2818
2819 //===----------------------------------------------------------------------===//
2820 /// DwarfWriter Implementation
2821 ///
2822
2823 DwarfWriter::DwarfWriter()
2824   : ImmutablePass(&ID), DD(0), DE(0) {}
2825
2826 DwarfWriter::~DwarfWriter() {
2827   delete DE;
2828   delete DD;
2829 }
2830
2831 /// BeginModule - Emit all Dwarf sections that should come prior to the
2832 /// content.
2833 void DwarfWriter::BeginModule(Module *M,
2834                               MachineModuleInfo *MMI,
2835                               raw_ostream &OS, AsmPrinter *A,
2836                               const TargetAsmInfo *T) {
2837   DE = new DwarfException(OS, A, T);
2838   DD = new DwarfDebug(OS, A, T);
2839   DE->BeginModule(M);
2840   DD->BeginModule(M);
2841   DD->SetDebugInfo(MMI);
2842   DE->SetModuleInfo(MMI);
2843 }
2844
2845 /// EndModule - Emit all Dwarf sections that should come after the content.
2846 ///
2847 void DwarfWriter::EndModule() {
2848   DE->EndModule();
2849   DD->EndModule();
2850 }
2851
2852 /// BeginFunction - Gather pre-function debug information.  Assumes being
2853 /// emitted immediately after the function entry point.
2854 void DwarfWriter::BeginFunction(MachineFunction *MF) {
2855   DE->BeginFunction(MF);
2856   DD->BeginFunction(MF);
2857 }
2858
2859 /// EndFunction - Gather and emit post-function debug information.
2860 ///
2861 void DwarfWriter::EndFunction(MachineFunction *MF) {
2862   DD->EndFunction(MF);
2863   DE->EndFunction();
2864
2865   if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
2866     // Clear function debug information.
2867     MMI->EndFunction();
2868 }
2869
2870 /// RecordSourceLine - Records location information and associates it with a 
2871 /// label. Returns a unique label ID used to generate a label and provide
2872 /// correspondence to the source line list.
2873 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col, 
2874                                        DICompileUnit CU) {
2875   return DD->RecordSourceLine(Line, Col, CU);
2876 }
2877
2878 /// RecordRegionStart - Indicate the start of a region.
2879 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
2880   return DD->RecordRegionStart(V);
2881 }
2882
2883 /// RecordRegionEnd - Indicate the end of a region.
2884 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
2885   return DD->RecordRegionEnd(V);
2886 }
2887
2888 /// getRecordSourceLineCount - Count source lines.
2889 unsigned DwarfWriter::getRecordSourceLineCount() {
2890   return DD->getRecordSourceLineCount();
2891 }
2892
2893 /// RecordVariable - Indicate the declaration of  a local variable.
2894 ///
2895 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
2896                                  const MachineInstr *MI) {
2897   DD->RecordVariable(GV, FrameIndex, MI);
2898 }
2899
2900 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
2901 /// be emitted.
2902 bool DwarfWriter::ShouldEmitDwarfDebug() const {
2903   return DD && DD->ShouldEmitDwarfDebug();
2904 }
2905
2906 //// RecordInlinedFnStart - Global variable GV is inlined at the location marked
2907 //// by LabelID label.
2908 unsigned DwarfWriter::RecordInlinedFnStart(DISubprogram SP, DICompileUnit CU,
2909                                            unsigned Line, unsigned Col) {
2910   return DD->RecordInlinedFnStart(SP, CU, Line, Col);
2911 }
2912
2913 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2914 unsigned DwarfWriter::RecordInlinedFnEnd(DISubprogram SP) {
2915   return DD->RecordInlinedFnEnd(SP);
2916 }
2917
2918 /// RecordVariableScope - Record scope for the variable declared by
2919 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE.
2920 void DwarfWriter::RecordVariableScope(DIVariable &DV,
2921                                       const MachineInstr *DeclareMI) {
2922   DD->RecordVariableScope(DV, DeclareMI);
2923 }