Add debug support for X86/ELF targets (Linux). This allows llvm-gcc4
[oota-llvm.git] / lib / CodeGen / DwarfWriter.cpp
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/DwarfWriter.h"
15
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/UniqueVector.h"
19 #include "llvm/Module.h"
20 #include "llvm/Type.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineDebugInfo.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineLocation.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/DataTypes.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/MRegisterInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34
35 #include <iostream>
36 #include <string>
37
38 using namespace llvm;
39 using namespace llvm::dwarf;
40
41 static cl::opt<bool>
42 DwarfVerbose("dwarf-verbose", cl::Hidden,
43                               cl::desc("Add comments to Dwarf directives."));
44
45 namespace llvm {
46   
47 //===----------------------------------------------------------------------===//
48 /// DWLabel - Labels are used to track locations in the assembler file.
49 /// Labels appear in the form <prefix>debug_<Tag><Number>, where the tag is a
50 /// category of label (Ex. location) and number is a value unique in that
51 /// category.
52 class DWLabel {
53 public:
54   const char *Tag;                    // Label category tag. Should always be
55                                       // a staticly declared C string.
56   unsigned    Number;                 // Unique number.
57
58   DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
59 };
60
61 //===----------------------------------------------------------------------===//
62 /// Forward declarations.
63 //
64 class DIE;
65
66 //===----------------------------------------------------------------------===//
67 /// CompileUnit - This dwarf writer support class manages information associate
68 /// with a source file.
69 class CompileUnit {
70 private:
71   CompileUnitDesc *Desc;                // Compile unit debug descriptor.
72   unsigned ID;                          // File ID for source.
73   DIE *Die;                             // Compile unit debug information entry.
74   std::map<std::string, DIE *> Globals; // A map of globally visible named
75                                         // entities for this unit.
76   std::map<DebugInfoDesc *, DIE *> DescToDieMap;
77                                         // Tracks the mapping of unit level
78                                         // debug informaton descriptors to debug
79                                         // information entries.
80
81 public:
82   CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
83   : Desc(CUD)
84   , ID(I)
85   , Die(D)
86   , Globals()
87   , DescToDieMap()
88   {}
89   
90   ~CompileUnit();
91   
92   // Accessors.
93   CompileUnitDesc *getDesc() const { return Desc; }
94   unsigned getID()           const { return ID; }
95   DIE* getDie()              const { return Die; }
96   std::map<std::string, DIE *> &getGlobals() { return Globals; }
97   
98   /// hasContent - Return true if this compile unit has something to write out.
99   ///
100   bool hasContent() const;
101   
102   /// AddGlobal - Add a new global entity to the compile unit.
103   ///
104   void AddGlobal(const std::string &Name, DIE *Die);
105   
106   /// getDieMapSlotFor - Returns the debug information entry map slot for the
107   /// specified debug descriptor.
108   DIE *&getDieMapSlotFor(DebugInfoDesc *DD) {
109     return DescToDieMap[DD];
110   }
111 };
112
113 //===----------------------------------------------------------------------===//
114 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
115 /// Dwarf abbreviation.
116 class DIEAbbrevData {
117 private:
118   unsigned Attribute;                 // Dwarf attribute code.
119   unsigned Form;                      // Dwarf form code.
120   
121 public:
122   DIEAbbrevData(unsigned A, unsigned F)
123   : Attribute(A)
124   , Form(F)
125   {}
126   
127   // Accessors.
128   unsigned getAttribute() const { return Attribute; }
129   unsigned getForm()      const { return Form; }
130
131   /// Profile - Used to gather unique data for the abbreviation folding set.
132   ///
133   void Profile(FoldingSetNodeID &ID) {
134     ID.AddInteger(Attribute);
135     ID.AddInteger(Form);
136   }
137 };
138
139 //===----------------------------------------------------------------------===//
140 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
141 /// information object.
142 class DIEAbbrev : public FoldingSetNode {
143 private:
144   unsigned Number;                    // Unique number for abbreviation.
145   unsigned Tag;                       // Dwarf tag code.
146   unsigned ChildrenFlag;              // Dwarf children flag.
147   std::vector<DIEAbbrevData> Data;    // Raw data bytes for abbreviation.
148
149 public:
150
151   DIEAbbrev(unsigned T, unsigned C)
152   : Number(0)
153   , Tag(T)
154   , ChildrenFlag(C)
155   , Data()
156   {}
157   ~DIEAbbrev() {}
158   
159   // Accessors.
160   unsigned getNumber()                        const { return Number; }
161   unsigned getTag()                           const { return Tag; }
162   unsigned getChildrenFlag()                  const { return ChildrenFlag; }
163   const std::vector<DIEAbbrevData> &getData() const { return Data; }
164   void setNumber(unsigned N)                        { Number = N; }
165   void setChildrenFlag(unsigned CF)                 { ChildrenFlag = CF; }
166
167   /// AddAttribute - Adds another set of attribute information to the
168   /// abbreviation.
169   void AddAttribute(unsigned Attribute, unsigned Form) {
170     Data.push_back(DIEAbbrevData(Attribute, Form));
171   }
172   
173   /// AddFirstAttribute - Adds a set of attribute information to the front
174   /// of the abbreviation.
175   void AddFirstAttribute(unsigned Attribute, unsigned Form) {
176     Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
177   }
178   
179   /// Profile - Used to gather unique data for the abbreviation folding set.
180   ///
181   void Profile(FoldingSetNodeID &ID) {
182     ID.AddInteger(Tag);
183     ID.AddInteger(ChildrenFlag);
184     
185     // For each attribute description.
186     for (unsigned i = 0, N = Data.size(); i < N; ++i)
187       Data[i].Profile(ID);
188   }
189   
190   /// Emit - Print the abbreviation using the specified Dwarf writer.
191   ///
192   void Emit(const Dwarf &DW) const; 
193       
194 #ifndef NDEBUG
195   void print(std::ostream &O);
196   void dump();
197 #endif
198 };
199
200 //===----------------------------------------------------------------------===//
201 /// DIEValue - A debug information entry value.
202 //
203 class DIEValue {
204 public:
205   enum {
206     isInteger,
207     isString,
208     isLabel,
209     isAsIsLabel,
210     isDelta,
211     isEntry,
212     isBlock
213   };
214   
215   unsigned Type;                      // Type of the value
216   
217   DIEValue(unsigned T) : Type(T) {}
218   virtual ~DIEValue() {}
219   
220   // Implement isa/cast/dyncast.
221   static bool classof(const DIEValue *) { return true; }
222   
223   /// EmitValue - Emit value via the Dwarf writer.
224   ///
225   virtual void EmitValue(const Dwarf &DW, unsigned Form) const = 0;
226   
227   /// SizeOf - Return the size of a value in bytes.
228   ///
229   virtual unsigned SizeOf(const Dwarf &DW, unsigned Form) const = 0;
230 };
231
232 //===----------------------------------------------------------------------===//
233 /// DWInteger - An integer value DIE.
234 /// 
235 class DIEInteger : public DIEValue {
236 private:
237   uint64_t Integer;
238   
239 public:
240   DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
241
242   // Implement isa/cast/dyncast.
243   static bool classof(const DIEInteger *) { return true; }
244   static bool classof(const DIEValue *I)  { return I->Type == isInteger; }
245   
246   /// BestForm - Choose the best form for integer.
247   ///
248   unsigned BestForm(bool IsSigned);
249
250   /// EmitValue - Emit integer of appropriate size.
251   ///
252   virtual void EmitValue(const Dwarf &DW, unsigned Form) const;
253   
254   /// SizeOf - Determine size of integer value in bytes.
255   ///
256   virtual unsigned SizeOf(const Dwarf &DW, unsigned Form) const;
257 };
258
259 //===----------------------------------------------------------------------===//
260 /// DIEString - A string value DIE.
261 /// 
262 struct DIEString : public DIEValue {
263   const std::string String;
264   
265   DIEString(const std::string &S) : DIEValue(isString), String(S) {}
266
267   // Implement isa/cast/dyncast.
268   static bool classof(const DIEString *) { return true; }
269   static bool classof(const DIEValue *S) { return S->Type == isString; }
270   
271   /// EmitValue - Emit string value.
272   ///
273   virtual void EmitValue(const Dwarf &DW, unsigned Form) const;
274   
275   /// SizeOf - Determine size of string value in bytes.
276   ///
277   virtual unsigned SizeOf(const Dwarf &DW, unsigned Form) const;
278 };
279
280 //===----------------------------------------------------------------------===//
281 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
282 //
283 struct DIEDwarfLabel : public DIEValue {
284   const DWLabel Label;
285   
286   DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
287
288   // Implement isa/cast/dyncast.
289   static bool classof(const DIEDwarfLabel *)  { return true; }
290   static bool classof(const DIEValue *L) { return L->Type == isLabel; }
291   
292   /// EmitValue - Emit label value.
293   ///
294   virtual void EmitValue(const Dwarf &DW, unsigned Form) const;
295   
296   /// SizeOf - Determine size of label value in bytes.
297   ///
298   virtual unsigned SizeOf(const Dwarf &DW, unsigned Form) const;
299 };
300
301
302 //===----------------------------------------------------------------------===//
303 /// DIEObjectLabel - A label to an object in code or data.
304 //
305 struct DIEObjectLabel : public DIEValue {
306   const std::string Label;
307   
308   DIEObjectLabel(const std::string &L) : DIEValue(isAsIsLabel), Label(L) {}
309
310   // Implement isa/cast/dyncast.
311   static bool classof(const DIEObjectLabel *) { return true; }
312   static bool classof(const DIEValue *L)    { return L->Type == isAsIsLabel; }
313   
314   /// EmitValue - Emit label value.
315   ///
316   virtual void EmitValue(const Dwarf &DW, unsigned Form) const;
317   
318   /// SizeOf - Determine size of label value in bytes.
319   ///
320   virtual unsigned SizeOf(const Dwarf &DW, unsigned Form) const;
321 };
322
323 //===----------------------------------------------------------------------===//
324 /// DIEDelta - A simple label difference DIE.
325 /// 
326 struct DIEDelta : public DIEValue {
327   const DWLabel LabelHi;
328   const DWLabel LabelLo;
329   
330   DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
331   : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
332
333   // Implement isa/cast/dyncast.
334   static bool classof(const DIEDelta *)  { return true; }
335   static bool classof(const DIEValue *D) { return D->Type == isDelta; }
336   
337   /// EmitValue - Emit delta value.
338   ///
339   virtual void EmitValue(const Dwarf &DW, unsigned Form) const;
340   
341   /// SizeOf - Determine size of delta value in bytes.
342   ///
343   virtual unsigned SizeOf(const Dwarf &DW, unsigned Form) const;
344 };
345
346 //===----------------------------------------------------------------------===//
347 /// DIEntry - A pointer to a debug information entry.
348 /// 
349 struct DIEntry : public DIEValue {
350   DIE *Entry;
351   
352   DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
353
354   // Implement isa/cast/dyncast.
355   static bool classof(const DIEntry *)   { return true; }
356   static bool classof(const DIEValue *E) { return E->Type == isEntry; }
357   
358   /// EmitValue - Emit debug information entry offset.
359   ///
360   virtual void EmitValue(const Dwarf &DW, unsigned Form) const;
361   
362   /// SizeOf - Determine size of debug information entry in bytes.
363   ///
364   virtual unsigned SizeOf(const Dwarf &DW, unsigned Form) const;
365 };
366
367 //===----------------------------------------------------------------------===//
368 /// DIEBlock - A block of values.  Primarily used for location expressions.
369 //
370 struct DIEBlock : public DIEValue {
371   unsigned Size;                        // Size in bytes excluding size header.
372   std::vector<unsigned> Forms;          // Data forms.
373   std::vector<DIEValue *> Values;       // Block values.
374   
375   DIEBlock()
376   : DIEValue(isBlock)
377   , Size(0)
378   , Forms()
379   , Values()
380   {}
381   ~DIEBlock();
382
383   // Implement isa/cast/dyncast.
384   static bool classof(const DIEBlock *)  { return true; }
385   static bool classof(const DIEValue *E) { return E->Type == isBlock; }
386   
387   /// ComputeSize - calculate the size of the block.
388   ///
389   unsigned ComputeSize(Dwarf &DW);
390   
391   /// BestForm - Choose the best form for data.
392   ///
393   unsigned BestForm();
394
395   /// EmitValue - Emit block data.
396   ///
397   virtual void EmitValue(const Dwarf &DW, unsigned Form) const;
398   
399   /// SizeOf - Determine size of block data in bytes.
400   ///
401   virtual unsigned SizeOf(const Dwarf &DW, unsigned Form) const;
402
403   /// AddUInt - Add an unsigned integer value.
404   ///
405   void AddUInt(unsigned Form, uint64_t Integer);
406
407   /// AddSInt - Add an signed integer value.
408   ///
409   void AddSInt(unsigned Form, int64_t Integer);
410       
411   /// AddString - Add a std::string value.
412   ///
413   void AddString(unsigned Form, const std::string &String);
414       
415   /// AddLabel - Add a Dwarf label value.
416   ///
417   void AddLabel(unsigned Form, const DWLabel &Label);
418       
419   /// AddObjectLabel - Add a non-Dwarf label value.
420   ///
421   void AddObjectLabel(unsigned Form, const std::string &Label);
422       
423   /// AddDelta - Add a label delta value.
424   ///
425   void AddDelta(unsigned Form, const DWLabel &Hi, const DWLabel &Lo);
426       
427   /// AddDIEntry - Add a DIE value.
428   ///
429   void AddDIEntry(unsigned Form, DIE *Entry);
430
431 };
432
433 //===----------------------------------------------------------------------===//
434 /// DIE - A structured debug information entry.  Has an abbreviation which
435 /// describes it's organization.
436 class DIE {
437 private:
438   DIEAbbrev Abbrev;                     // Buffer for constructing abbreviation.
439   unsigned Offset;                      // Offset in debug info section.
440   unsigned Size;                        // Size of instance + children.
441   std::vector<DIE *> Children;          // Children DIEs.
442   std::vector<DIEValue *> Values;       // Attributes values.
443   
444 public:
445   DIE(unsigned Tag);
446   ~DIE();
447   
448   // Accessors.
449   unsigned   getAbbrevNumber()               const {
450     return Abbrev.getNumber();
451   }
452   unsigned   getOffset()                     const { return Offset; }
453   unsigned   getSize()                       const { return Size; }
454   const std::vector<DIE *> &getChildren()    const { return Children; }
455   const std::vector<DIEValue *> &getValues() const { return Values; }
456   void setOffset(unsigned O)                 { Offset = O; }
457   void setSize(unsigned S)                   { Size = S; }
458   
459   /// SiblingOffset - Return the offset of the debug information entry's
460   /// sibling.
461   unsigned SiblingOffset() const { return Offset + Size; }
462   
463   /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
464   ///
465   void AddSiblingOffset();
466
467   /// AddUInt - Add an unsigned integer attribute data and value.
468   ///
469   void AddUInt(unsigned Attribute, unsigned Form, uint64_t Integer);
470
471   /// AddSInt - Add an signed integer attribute data and value.
472   ///
473   void AddSInt(unsigned Attribute, unsigned Form, int64_t Integer);
474       
475   /// AddString - Add a std::string attribute data and value.
476   ///
477   void AddString(unsigned Attribute, unsigned Form,
478                  const std::string &String);
479       
480   /// AddLabel - Add a Dwarf label attribute data and value.
481   ///
482   void AddLabel(unsigned Attribute, unsigned Form, const DWLabel &Label);
483       
484   /// AddObjectLabel - Add a non-Dwarf label attribute data and value.
485   ///
486   void AddObjectLabel(unsigned Attribute, unsigned Form,
487                       const std::string &Label);
488       
489   /// AddDelta - Add a label delta attribute data and value.
490   ///
491   void AddDelta(unsigned Attribute, unsigned Form,
492                 const DWLabel &Hi, const DWLabel &Lo);
493       
494   /// AddDIEntry - Add a DIE attribute data and value.
495   ///
496   void AddDIEntry(unsigned Attribute, unsigned Form, DIE *Entry);
497
498   /// AddBlock - Add block data.
499   ///
500   void AddBlock(unsigned Attribute, unsigned Form, DIEBlock *Block);
501
502   /// Complete - Indicate that all attributes have been added and
503   /// ready to get an abbreviation ID.
504   ///
505   void Complete(Dwarf &DW);
506   
507   /// AddChild - Add a child to the DIE.
508   void AddChild(DIE *Child);
509 };
510
511 //===----------------------------------------------------------------------===//
512 /// Dwarf - Emits Dwarf debug and exception handling directives.
513 //
514 class Dwarf {
515
516 private:
517
518   //===--------------------------------------------------------------------===//
519   // Core attributes used by the Dwarf  writer.
520   //
521   
522   //
523   /// O - Stream to .s file.
524   ///
525   std::ostream &O;
526
527   /// Asm - Target of Dwarf emission.
528   ///
529   AsmPrinter *Asm;
530   
531   /// TAI - Target Asm Printer.
532   const TargetAsmInfo *TAI;
533   
534   /// TD - Target data.
535   const TargetData *TD;
536   
537   /// RI - Register Information.
538   const MRegisterInfo *RI;
539   
540   /// M - Current module.
541   ///
542   Module *M;
543   
544   /// MF - Current machine function.
545   ///
546   MachineFunction *MF;
547   
548   /// DebugInfo - Collected debug information.
549   ///
550   MachineDebugInfo *DebugInfo;
551   
552   /// didInitial - Flag to indicate if initial emission has been done.
553   ///
554   bool didInitial;
555   
556   /// shouldEmit - Flag to indicate if debug information should be emitted.
557   ///
558   bool shouldEmit;
559   
560   /// SubprogramCount - The running count of functions being compiled.
561   ///
562   unsigned SubprogramCount;
563   
564   //===--------------------------------------------------------------------===//
565   // Attributes used to construct specific Dwarf sections.
566   //
567   
568   /// CompileUnits - All the compile units involved in this build.  The index
569   /// of each entry in this vector corresponds to the sources in DebugInfo.
570   std::vector<CompileUnit *> CompileUnits;
571   
572   /// AbbreviationsSet - Used to uniquely define the abbreviations.
573   ///
574   FoldingSet<DIEAbbrev> AbbreviationsSet;
575
576   /// Abbreviations - A list of all the unique abbreviations in use.
577   ///
578   std::vector<DIEAbbrev *> Abbreviations;
579   
580   /// StringPool - A UniqueVector of strings used by indirect references.
581   /// UnitMap - Map debug information descriptor to compile unit.
582    ///
583   UniqueVector<std::string> StringPool;
584
585   /// UnitMap - Map debug information descriptor to compile unit.
586   ///
587   std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
588   
589   /// DescToDieMap - Tracks the mapping of top level debug informaton
590   /// descriptors to debug information entries.
591   std::map<DebugInfoDesc *, DIE *> DescToDieMap;
592   
593   /// SectionMap - Provides a unique id per text section.
594   ///
595   UniqueVector<std::string> SectionMap;
596   
597   /// SectionSourceLines - Tracks line numbers per text section.
598   ///
599   std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
600
601
602 public:
603
604   //===--------------------------------------------------------------------===//
605   // Emission and print routines
606   //
607
608   /// PrintHex - Print a value as a hexidecimal value.
609   ///
610   void PrintHex(int Value) const;
611
612   /// EOL - Print a newline character to asm stream.  If a comment is present
613   /// then it will be printed first.  Comments should not contain '\n'.
614   void EOL(const std::string &Comment) const;
615   
616   /// EmitAlign - Print a align directive.
617   ///
618   void EmitAlign(unsigned Alignment) const;
619                                         
620   /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
621   /// unsigned leb128 value.
622   void EmitULEB128Bytes(unsigned Value) const;
623   
624   /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
625   /// signed leb128 value.
626   void EmitSLEB128Bytes(int Value) const;
627   
628   /// PrintULEB128 - Print a series of hexidecimal values (separated by
629   /// commas) representing an unsigned leb128 value.
630   void PrintULEB128(unsigned Value) const;
631
632   /// SizeULEB128 - Compute the number of bytes required for an unsigned
633   /// leb128 value.
634   static unsigned SizeULEB128(unsigned Value);
635   
636   /// PrintSLEB128 - Print a series of hexidecimal values (separated by
637   /// commas) representing a signed leb128 value.
638   void PrintSLEB128(int Value) const;
639   
640   /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
641   /// value.
642   static unsigned SizeSLEB128(int Value);
643   
644   /// EmitInt8 - Emit a byte directive and value.
645   ///
646   void EmitInt8(int Value) const;
647
648   /// EmitInt16 - Emit a short directive and value.
649   ///
650   void EmitInt16(int Value) const;
651
652   /// EmitInt32 - Emit a long directive and value.
653   ///
654   void EmitInt32(int Value) const;
655   
656   /// EmitInt64 - Emit a long long directive and value.
657   ///
658   void EmitInt64(uint64_t Value) const;
659   
660   /// EmitString - Emit a string with quotes and a null terminator.
661   /// Special characters are emitted properly. 
662   /// \literal (Eg. '\t') \endliteral
663   void EmitString(const std::string &String) const;
664
665   /// PrintLabelName - Print label name in form used by Dwarf writer.
666   ///
667   void PrintLabelName(DWLabel Label) const {
668     PrintLabelName(Label.Tag, Label.Number);
669   }
670   void PrintLabelName(const char *Tag, unsigned Number) const;
671   
672   /// EmitLabel - Emit location label for internal use by Dwarf.
673   ///
674   void EmitLabel(DWLabel Label) const {
675     EmitLabel(Label.Tag, Label.Number);
676   }
677   void EmitLabel(const char *Tag, unsigned Number) const;
678   
679   /// EmitReference - Emit a reference to a label.
680   ///
681   void EmitReference(DWLabel Label) const {
682     EmitReference(Label.Tag, Label.Number);
683   }
684   void EmitReference(const char *Tag, unsigned Number) const;
685   void EmitReference(const std::string &Name) const;
686
687   /// EmitDifference - Emit the difference between two labels.  Some
688   /// assemblers do not behave with absolute expressions with data directives,
689   /// so there is an option (needsSet) to use an intermediary set expression.
690   void EmitDifference(DWLabel LabelHi, DWLabel LabelLo) const {
691     EmitDifference(LabelHi.Tag, LabelHi.Number, LabelLo.Tag, LabelLo.Number);
692   }
693   void EmitDifference(const char *TagHi, unsigned NumberHi,
694                       const char *TagLo, unsigned NumberLo) const;
695                       
696   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
697   ///  
698   void AssignAbbrevNumber(DIEAbbrev *Abbrev);
699   
700   /// NewString - Add a string to the constant pool and returns a label.
701   ///
702   DWLabel NewString(const std::string &String);
703   
704   /// getDieMapSlotFor - Returns the debug information entry map slot for the
705   /// specified debug descriptor.
706   DIE *&getDieMapSlotFor(DebugInfoDesc *DD);
707                                  
708 private:
709
710   /// AddSourceLine - Add location information to specified debug information
711   /// entry. 
712   void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line);
713
714   /// AddAddress - Add an address attribute to a die based on the location
715   /// provided.
716   void AddAddress(DIE *Die, unsigned Attribute,
717                   const MachineLocation &Location);
718
719   /// NewType - Create a new type DIE.
720   ///
721   DIE *NewType(DIE *Context, TypeDesc *TyDesc, CompileUnit *Unit);
722   
723   /// NewCompileUnit - Create new compile unit and it's die.
724   ///
725   CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID);
726   
727   /// FindCompileUnit - Get the compile unit for the given descriptor.
728   ///
729   CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc);
730   
731   /// NewGlobalVariable - Make a new global variable DIE.
732   ///
733   DIE *NewGlobalVariable(GlobalVariableDesc *GVD);
734
735   /// NewSubprogram - Add a new subprogram DIE.
736   ///
737   DIE *NewSubprogram(SubprogramDesc *SPD);
738
739   /// NewScopeVariable - Create a new scope variable.
740   ///
741   DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit);
742
743   /// ConstructScope - Construct the components of a scope.
744   ///
745   void ConstructScope(DebugScope *ParentScope, DIE *ParentDie,
746                       CompileUnit *Unit);
747
748   /// ConstructRootScope - Construct the scope for the subprogram.
749   ///
750   void ConstructRootScope(DebugScope *RootScope);
751
752   /// EmitInitial - Emit initial Dwarf declarations.
753   ///
754   void EmitInitial();
755   
756   /// EmitDIE - Recusively Emits a debug information entry.
757   ///
758   void EmitDIE(DIE *Die) const;
759   
760   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
761   ///
762   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last);
763
764   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
765   ///
766   void SizeAndOffsets();
767   
768   /// EmitFrameMoves - Emit frame instructions to describe the layout of the
769   /// frame.
770   void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
771                       std::vector<MachineMove *> &Moves);
772
773   /// EmitDebugInfo - Emit the debug info section.
774   ///
775   void EmitDebugInfo() const;
776   
777   /// EmitAbbreviations - Emit the abbreviation section.
778   ///
779   void EmitAbbreviations() const;
780   
781   /// EmitDebugLines - Emit source line information.
782   ///
783   void EmitDebugLines() const;
784
785   /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
786   ///
787   void EmitInitialDebugFrame();
788     
789   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
790   /// section.
791   void EmitFunctionDebugFrame();
792
793   /// EmitDebugPubNames - Emit info into a debug pubnames section.
794   ///
795   void EmitDebugPubNames();
796   
797   /// EmitDebugStr - Emit info into a debug str section.
798   ///
799   void EmitDebugStr();
800   
801   /// EmitDebugLoc - Emit info into a debug loc section.
802   ///
803   void EmitDebugLoc();
804   
805   /// EmitDebugARanges - Emit info into a debug aranges section.
806   ///
807   void EmitDebugARanges();
808   
809   /// EmitDebugRanges - Emit info into a debug ranges section.
810   ///
811   void EmitDebugRanges();
812   
813   /// EmitDebugMacInfo - Emit info into a debug macinfo section.
814   ///
815   void EmitDebugMacInfo();
816   
817   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
818   /// header file.
819   void ConstructCompileUnitDIEs();
820   
821   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
822   /// global variables.
823   void ConstructGlobalDIEs();
824
825   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
826   /// subprograms.
827   void ConstructSubprogramDIEs();
828
829   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
830   ///
831   bool ShouldEmitDwarf() const { return shouldEmit; }
832
833 public:
834   
835   Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T);
836   virtual ~Dwarf();
837   
838   // Accessors.
839   //
840   const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
841   
842   /// SetDebugInfo - Set DebugInfo when it's known that pass manager has
843   /// created it.  Set by the target AsmPrinter.
844   void SetDebugInfo(MachineDebugInfo *DI);
845
846   //===--------------------------------------------------------------------===//
847   // Main entry points.
848   //
849   
850   /// BeginModule - Emit all Dwarf sections that should come prior to the
851   /// content.
852   void BeginModule(Module *M);
853   
854   /// EndModule - Emit all Dwarf sections that should come after the content.
855   ///
856   void EndModule();
857   
858   /// BeginFunction - Gather pre-function debug information.  Assumes being 
859   /// emitted immediately after the function entry point.
860   void BeginFunction(MachineFunction *MF);
861   
862   /// EndFunction - Gather and emit post-function debug information.
863   ///
864   void EndFunction();
865 };
866
867 } // End of namespace llvm
868
869 //===----------------------------------------------------------------------===//
870
871 CompileUnit::~CompileUnit() {
872   delete Die;
873 }
874
875 /// hasContent - Return true if this compile unit has something to write out.
876 ///
877 bool CompileUnit::hasContent() const {
878   return !Die->getChildren().empty();
879 }
880
881 /// AddGlobal - Add a new global entity to the compile unit.
882 ///
883 void CompileUnit::AddGlobal(const std::string &Name, DIE *Die) {
884   Globals[Name] = Die;
885 }
886
887 //===----------------------------------------------------------------------===//
888
889 /// Emit - Print the abbreviation using the specified Dwarf writer.
890 ///
891 void DIEAbbrev::Emit(const Dwarf &DW) const {
892   // Emit its Dwarf tag type.
893   DW.EmitULEB128Bytes(Tag);
894   DW.EOL(TagString(Tag));
895   
896   // Emit whether it has children DIEs.
897   DW.EmitULEB128Bytes(ChildrenFlag);
898   DW.EOL(ChildrenString(ChildrenFlag));
899   
900   // For each attribute description.
901   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
902     const DIEAbbrevData &AttrData = Data[i];
903     
904     // Emit attribute type.
905     DW.EmitULEB128Bytes(AttrData.getAttribute());
906     DW.EOL(AttributeString(AttrData.getAttribute()));
907     
908     // Emit form type.
909     DW.EmitULEB128Bytes(AttrData.getForm());
910     DW.EOL(FormEncodingString(AttrData.getForm()));
911   }
912
913   // Mark end of abbreviation.
914   DW.EmitULEB128Bytes(0); DW.EOL("EOM(1)");
915   DW.EmitULEB128Bytes(0); DW.EOL("EOM(2)");
916 }
917
918 #ifndef NDEBUG
919 void DIEAbbrev::print(std::ostream &O) {
920   O << "Abbreviation @"
921     << std::hex << (intptr_t)this << std::dec
922     << "  "
923     << TagString(Tag)
924     << " "
925     << ChildrenString(ChildrenFlag)
926     << "\n";
927   
928   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
929     O << "  "
930       << AttributeString(Data[i].getAttribute())
931       << "  "
932       << FormEncodingString(Data[i].getForm())
933       << "\n";
934   }
935 }
936 void DIEAbbrev::dump() { print(std::cerr); }
937 #endif
938
939 //===----------------------------------------------------------------------===//
940
941 /// BestForm - Choose the best form for integer.
942 ///
943 unsigned DIEInteger::BestForm(bool IsSigned) {
944   if (IsSigned) {
945     if ((char)Integer == (signed)Integer)   return DW_FORM_data1;
946     if ((short)Integer == (signed)Integer)  return DW_FORM_data2;
947     if ((int)Integer == (signed)Integer)    return DW_FORM_data4;
948   } else {
949     if ((unsigned char)Integer == Integer)  return DW_FORM_data1;
950     if ((unsigned short)Integer == Integer) return DW_FORM_data2;
951     if ((unsigned int)Integer == Integer)   return DW_FORM_data4;
952   }
953   return DW_FORM_data8;
954 }
955     
956 /// EmitValue - Emit integer of appropriate size.
957 ///
958 void DIEInteger::EmitValue(const Dwarf &DW, unsigned Form) const {
959   switch (Form) {
960   case DW_FORM_flag:  // Fall thru
961   case DW_FORM_ref1:  // Fall thru
962   case DW_FORM_data1: DW.EmitInt8(Integer);         break;
963   case DW_FORM_ref2:  // Fall thru
964   case DW_FORM_data2: DW.EmitInt16(Integer);        break;
965   case DW_FORM_ref4:  // Fall thru
966   case DW_FORM_data4: DW.EmitInt32(Integer);        break;
967   case DW_FORM_ref8:  // Fall thru
968   case DW_FORM_data8: DW.EmitInt64(Integer);        break;
969   case DW_FORM_udata: DW.EmitULEB128Bytes(Integer); break;
970   case DW_FORM_sdata: DW.EmitSLEB128Bytes(Integer); break;
971   default: assert(0 && "DIE Value form not supported yet"); break;
972   }
973 }
974
975 /// SizeOf - Determine size of integer value in bytes.
976 ///
977 unsigned DIEInteger::SizeOf(const Dwarf &DW, unsigned Form) const {
978   switch (Form) {
979   case DW_FORM_flag:  // Fall thru
980   case DW_FORM_ref1:  // Fall thru
981   case DW_FORM_data1: return sizeof(int8_t);
982   case DW_FORM_ref2:  // Fall thru
983   case DW_FORM_data2: return sizeof(int16_t);
984   case DW_FORM_ref4:  // Fall thru
985   case DW_FORM_data4: return sizeof(int32_t);
986   case DW_FORM_ref8:  // Fall thru
987   case DW_FORM_data8: return sizeof(int64_t);
988   case DW_FORM_udata: return DW.SizeULEB128(Integer);
989   case DW_FORM_sdata: return DW.SizeSLEB128(Integer);
990   default: assert(0 && "DIE Value form not supported yet"); break;
991   }
992   return 0;
993 }
994
995 //===----------------------------------------------------------------------===//
996
997 /// EmitValue - Emit string value.
998 ///
999 void DIEString::EmitValue(const Dwarf &DW, unsigned Form) const {
1000   DW.EmitString(String);
1001 }
1002
1003 /// SizeOf - Determine size of string value in bytes.
1004 ///
1005 unsigned DIEString::SizeOf(const Dwarf &DW, unsigned Form) const {
1006   return String.size() + sizeof(char); // sizeof('\0');
1007 }
1008
1009 //===----------------------------------------------------------------------===//
1010
1011 /// EmitValue - Emit label value.
1012 ///
1013 void DIEDwarfLabel::EmitValue(const Dwarf &DW, unsigned Form) const {
1014   DW.EmitReference(Label);
1015 }
1016
1017 /// SizeOf - Determine size of label value in bytes.
1018 ///
1019 unsigned DIEDwarfLabel::SizeOf(const Dwarf &DW, unsigned Form) const {
1020   return DW.getTargetAsmInfo()->getAddressSize();
1021 }
1022     
1023 //===----------------------------------------------------------------------===//
1024
1025 /// EmitValue - Emit label value.
1026 ///
1027 void DIEObjectLabel::EmitValue(const Dwarf &DW, unsigned Form) const {
1028   DW.EmitReference(Label);
1029 }
1030
1031 /// SizeOf - Determine size of label value in bytes.
1032 ///
1033 unsigned DIEObjectLabel::SizeOf(const Dwarf &DW, unsigned Form) const {
1034   return DW.getTargetAsmInfo()->getAddressSize();
1035 }
1036     
1037 //===----------------------------------------------------------------------===//
1038
1039 /// EmitValue - Emit delta value.
1040 ///
1041 void DIEDelta::EmitValue(const Dwarf &DW, unsigned Form) const {
1042   DW.EmitDifference(LabelHi, LabelLo);
1043 }
1044
1045 /// SizeOf - Determine size of delta value in bytes.
1046 ///
1047 unsigned DIEDelta::SizeOf(const Dwarf &DW, unsigned Form) const {
1048   return DW.getTargetAsmInfo()->getAddressSize();
1049 }
1050
1051 //===----------------------------------------------------------------------===//
1052 /// EmitValue - Emit debug information entry offset.
1053 ///
1054 void DIEntry::EmitValue(const Dwarf &DW, unsigned Form) const {
1055   DW.EmitInt32(Entry->getOffset());
1056 }
1057
1058 /// SizeOf - Determine size of debug information entry value in bytes.
1059 ///
1060 unsigned DIEntry::SizeOf(const Dwarf &DW, unsigned Form) const {
1061   return sizeof(int32_t);
1062 }
1063     
1064 //===----------------------------------------------------------------------===//
1065
1066 DIEBlock::~DIEBlock() {
1067   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1068     delete Values[i];
1069   }
1070 }
1071
1072 /// ComputeSize - calculate the size of the block.
1073 ///
1074 unsigned DIEBlock::ComputeSize(Dwarf &DW) {
1075   Size = 0;
1076   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1077     Size += Values[i]->SizeOf(DW, Forms[i]);
1078   }
1079   return Size;
1080 }
1081
1082 /// BestForm - Choose the best form for data.
1083 ///
1084 unsigned DIEBlock::BestForm() {
1085   if ((unsigned char)Size == Size)  return DW_FORM_block1;
1086   if ((unsigned short)Size == Size) return DW_FORM_block2;
1087   if ((unsigned int)Size == Size)   return DW_FORM_block4;
1088   return DW_FORM_block;
1089 }
1090
1091 /// EmitValue - Emit block data.
1092 ///
1093 void DIEBlock::EmitValue(const Dwarf &DW, unsigned Form) const {
1094   switch (Form) {
1095   case DW_FORM_block1: DW.EmitInt8(Size);         break;
1096   case DW_FORM_block2: DW.EmitInt16(Size);        break;
1097   case DW_FORM_block4: DW.EmitInt32(Size);        break;
1098   case DW_FORM_block:  DW.EmitULEB128Bytes(Size); break;
1099   default: assert(0 && "Improper form for block"); break;
1100   }
1101   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1102     DW.EOL("");
1103     Values[i]->EmitValue(DW, Forms[i]);
1104   }
1105 }
1106
1107 /// SizeOf - Determine size of block data in bytes.
1108 ///
1109 unsigned DIEBlock::SizeOf(const Dwarf &DW, unsigned Form) const {
1110   switch (Form) {
1111   case DW_FORM_block1: return Size + sizeof(int8_t);
1112   case DW_FORM_block2: return Size + sizeof(int16_t);
1113   case DW_FORM_block4: return Size + sizeof(int32_t);
1114   case DW_FORM_block: return Size + DW.SizeULEB128(Size);
1115   default: assert(0 && "Improper form for block"); break;
1116   }
1117   return 0;
1118 }
1119
1120 /// AddUInt - Add an unsigned integer value.
1121 ///
1122 void DIEBlock::AddUInt(unsigned Form, uint64_t Integer) {
1123   DIEInteger *DI = new DIEInteger(Integer);
1124   Values.push_back(DI);
1125   if (Form == 0) Form = DI->BestForm(false);
1126   Forms.push_back(Form);
1127 }
1128
1129 /// AddSInt - Add an signed integer value.
1130 ///
1131 void DIEBlock::AddSInt(unsigned Form, int64_t Integer) {
1132   DIEInteger *DI = new DIEInteger(Integer);
1133   Values.push_back(DI);
1134   if (Form == 0) Form = DI->BestForm(true);
1135   Forms.push_back(Form);
1136 }
1137     
1138 /// AddString - Add a std::string value.
1139 ///
1140 void DIEBlock::AddString(unsigned Form, const std::string &String) {
1141   Values.push_back(new DIEString(String));
1142   Forms.push_back(Form);
1143 }
1144     
1145 /// AddLabel - Add a Dwarf label value.
1146 ///
1147 void DIEBlock::AddLabel(unsigned Form, const DWLabel &Label) {
1148   Values.push_back(new DIEDwarfLabel(Label));
1149   Forms.push_back(Form);
1150 }
1151     
1152 /// AddObjectLabel - Add a non-Dwarf label value.
1153 ///
1154 void DIEBlock::AddObjectLabel(unsigned Form, const std::string &Label) {
1155   Values.push_back(new DIEObjectLabel(Label));
1156   Forms.push_back(Form);
1157 }
1158     
1159 /// AddDelta - Add a label delta value.
1160 ///
1161 void DIEBlock::AddDelta(unsigned Form, const DWLabel &Hi, const DWLabel &Lo) {
1162   Values.push_back(new DIEDelta(Hi, Lo));
1163   Forms.push_back(Form);
1164 }
1165     
1166 /// AddDIEntry - Add a DIE value.
1167 ///
1168 void DIEBlock::AddDIEntry(unsigned Form, DIE *Entry) {
1169   Values.push_back(new DIEntry(Entry));
1170   Forms.push_back(Form);
1171 }
1172
1173 //===----------------------------------------------------------------------===//
1174
1175 DIE::DIE(unsigned Tag)
1176 : Abbrev(Tag, DW_CHILDREN_no)
1177 , Offset(0)
1178 , Size(0)
1179 , Children()
1180 , Values()
1181 {}
1182
1183 DIE::~DIE() {
1184   for (unsigned i = 0, N = Children.size(); i < N; ++i) {
1185     delete Children[i];
1186   }
1187
1188   for (unsigned j = 0, M = Values.size(); j < M; ++j) {
1189     delete Values[j];
1190   }
1191 }
1192     
1193 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
1194 ///
1195 void DIE::AddSiblingOffset() {
1196   DIEInteger *DI = new DIEInteger(0);
1197   Values.insert(Values.begin(), DI);
1198   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
1199 }
1200
1201 /// AddUInt - Add an unsigned integer attribute data and value.
1202 ///
1203 void DIE::AddUInt(unsigned Attribute, unsigned Form, uint64_t Integer) {
1204   DIEInteger *DI = new DIEInteger(Integer);
1205   Values.push_back(DI);
1206   if (!Form) Form = DI->BestForm(false);
1207   Abbrev.AddAttribute(Attribute, Form);
1208 }
1209     
1210 /// AddSInt - Add an signed integer attribute data and value.
1211 ///
1212 void DIE::AddSInt(unsigned Attribute, unsigned Form, int64_t Integer) {
1213   DIEInteger *DI = new DIEInteger(Integer);
1214   Values.push_back(DI);
1215   if (!Form) Form = DI->BestForm(true);
1216   Abbrev.AddAttribute(Attribute, Form);
1217 }
1218     
1219 /// AddString - Add a std::string attribute data and value.
1220 ///
1221 void DIE::AddString(unsigned Attribute, unsigned Form,
1222                     const std::string &String) {
1223   Values.push_back(new DIEString(String));
1224   Abbrev.AddAttribute(Attribute, Form);
1225 }
1226     
1227 /// AddLabel - Add a Dwarf label attribute data and value.
1228 ///
1229 void DIE::AddLabel(unsigned Attribute, unsigned Form,
1230                    const DWLabel &Label) {
1231   Values.push_back(new DIEDwarfLabel(Label));
1232   Abbrev.AddAttribute(Attribute, Form);
1233 }
1234     
1235 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1236 ///
1237 void DIE::AddObjectLabel(unsigned Attribute, unsigned Form,
1238                          const std::string &Label) {
1239   Values.push_back(new DIEObjectLabel(Label));
1240   Abbrev.AddAttribute(Attribute, Form);
1241 }
1242     
1243 /// AddDelta - Add a label delta attribute data and value.
1244 ///
1245 void DIE::AddDelta(unsigned Attribute, unsigned Form,
1246                    const DWLabel &Hi, const DWLabel &Lo) {
1247   Values.push_back(new DIEDelta(Hi, Lo));
1248   Abbrev.AddAttribute(Attribute, Form);
1249 }
1250     
1251 /// AddDIEntry - Add a DIE attribute data and value.
1252 ///
1253 void DIE::AddDIEntry(unsigned Attribute, unsigned Form, DIE *Entry) {
1254   Values.push_back(new DIEntry(Entry));
1255   Abbrev.AddAttribute(Attribute, Form);
1256 }
1257
1258 /// AddBlock - Add block data.
1259 ///
1260 void DIE::AddBlock(unsigned Attribute, unsigned Form, DIEBlock *Block) {
1261   assert(Block->Size && "Block size has not been computed");
1262   Values.push_back(Block);
1263   if (!Form) Form = Block->BestForm();
1264   Abbrev.AddAttribute(Attribute, Form);
1265 }
1266
1267 /// Complete - Indicate that all attributes have been added and ready to get an
1268 /// abbreviation ID.
1269 void DIE::Complete(Dwarf &DW) {
1270   DW.AssignAbbrevNumber(&Abbrev);
1271 }
1272
1273 /// AddChild - Add a child to the DIE.
1274 ///
1275 void DIE::AddChild(DIE *Child) {
1276   Abbrev.setChildrenFlag(DW_CHILDREN_yes);
1277   Children.push_back(Child);
1278 }
1279
1280 //===----------------------------------------------------------------------===//
1281
1282 /// Dwarf
1283
1284 //===----------------------------------------------------------------------===//
1285
1286 /// PrintHex - Print a value as a hexidecimal value.
1287 ///
1288 void Dwarf::PrintHex(int Value) const { 
1289   O << "0x" << std::hex << Value << std::dec;
1290 }
1291
1292 /// EOL - Print a newline character to asm stream.  If a comment is present
1293 /// then it will be printed first.  Comments should not contain '\n'.
1294 void Dwarf::EOL(const std::string &Comment) const {
1295   if (DwarfVerbose && !Comment.empty()) {
1296     O << "\t"
1297       << TAI->getCommentString()
1298       << " "
1299       << Comment;
1300   }
1301   O << "\n";
1302 }
1303
1304 /// EmitAlign - Print a align directive.
1305 ///
1306 void Dwarf::EmitAlign(unsigned Alignment) const {
1307   O << TAI->getAlignDirective() << Alignment << "\n";
1308 }
1309
1310 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
1311 /// unsigned leb128 value.
1312 void Dwarf::EmitULEB128Bytes(unsigned Value) const {
1313   if (TAI->hasLEB128()) {
1314     O << "\t.uleb128\t"
1315       << Value;
1316   } else {
1317     O << TAI->getData8bitsDirective();
1318     PrintULEB128(Value);
1319   }
1320 }
1321
1322 /// EmitSLEB128Bytes - Emit an assembler byte data directive to compose a
1323 /// signed leb128 value.
1324 void Dwarf::EmitSLEB128Bytes(int Value) const {
1325   if (TAI->hasLEB128()) {
1326     O << "\t.sleb128\t"
1327       << Value;
1328   } else {
1329     O << TAI->getData8bitsDirective();
1330     PrintSLEB128(Value);
1331   }
1332 }
1333
1334 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
1335 /// representing an unsigned leb128 value.
1336 void Dwarf::PrintULEB128(unsigned Value) const {
1337   do {
1338     unsigned Byte = Value & 0x7f;
1339     Value >>= 7;
1340     if (Value) Byte |= 0x80;
1341     PrintHex(Byte);
1342     if (Value) O << ", ";
1343   } while (Value);
1344 }
1345
1346 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
1347 /// value.
1348 unsigned Dwarf::SizeULEB128(unsigned Value) {
1349   unsigned Size = 0;
1350   do {
1351     Value >>= 7;
1352     Size += sizeof(int8_t);
1353   } while (Value);
1354   return Size;
1355 }
1356
1357 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
1358 /// representing a signed leb128 value.
1359 void Dwarf::PrintSLEB128(int Value) const {
1360   int Sign = Value >> (8 * sizeof(Value) - 1);
1361   bool IsMore;
1362   
1363   do {
1364     unsigned Byte = Value & 0x7f;
1365     Value >>= 7;
1366     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
1367     if (IsMore) Byte |= 0x80;
1368     PrintHex(Byte);
1369     if (IsMore) O << ", ";
1370   } while (IsMore);
1371 }
1372
1373 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
1374 /// value.
1375 unsigned Dwarf::SizeSLEB128(int Value) {
1376   unsigned Size = 0;
1377   int Sign = Value >> (8 * sizeof(Value) - 1);
1378   bool IsMore;
1379   
1380   do {
1381     unsigned Byte = Value & 0x7f;
1382     Value >>= 7;
1383     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
1384     Size += sizeof(int8_t);
1385   } while (IsMore);
1386   return Size;
1387 }
1388
1389 /// EmitInt8 - Emit a byte directive and value.
1390 ///
1391 void Dwarf::EmitInt8(int Value) const {
1392   O << TAI->getData8bitsDirective();
1393   PrintHex(Value & 0xFF);
1394 }
1395
1396 /// EmitInt16 - Emit a short directive and value.
1397 ///
1398 void Dwarf::EmitInt16(int Value) const {
1399   O << TAI->getData16bitsDirective();
1400   PrintHex(Value & 0xFFFF);
1401 }
1402
1403 /// EmitInt32 - Emit a long directive and value.
1404 ///
1405 void Dwarf::EmitInt32(int Value) const {
1406   O << TAI->getData32bitsDirective();
1407   PrintHex(Value);
1408 }
1409
1410 /// EmitInt64 - Emit a long long directive and value.
1411 ///
1412 void Dwarf::EmitInt64(uint64_t Value) const {
1413   if (TAI->getData64bitsDirective()) {
1414     O << TAI->getData64bitsDirective() << "0x" << std::hex << Value << std::dec;
1415   } else {
1416     if (TD->isBigEndian()) {
1417       EmitInt32(unsigned(Value >> 32)); O << "\n";
1418       EmitInt32(unsigned(Value));
1419     } else {
1420       EmitInt32(unsigned(Value)); O << "\n";
1421       EmitInt32(unsigned(Value >> 32));
1422     }
1423   }
1424 }
1425
1426 /// EmitString - Emit a string with quotes and a null terminator.
1427 /// Special characters are emitted properly. (Eg. '\t')
1428 void Dwarf::EmitString(const std::string &String) const {
1429   O << TAI->getAsciiDirective()
1430     << "\"";
1431   for (unsigned i = 0, N = String.size(); i < N; ++i) {
1432     unsigned char C = String[i];
1433     
1434     if (!isascii(C) || iscntrl(C)) {
1435       switch(C) {
1436       case '\b': O << "\\b"; break;
1437       case '\f': O << "\\f"; break;
1438       case '\n': O << "\\n"; break;
1439       case '\r': O << "\\r"; break;
1440       case '\t': O << "\\t"; break;
1441       default:
1442         O << '\\';
1443         O << char('0' + ((C >> 6) & 7));
1444         O << char('0' + ((C >> 3) & 7));
1445         O << char('0' + ((C >> 0) & 7));
1446         break;
1447       }
1448     } else if (C == '\"') {
1449       O << "\\\"";
1450     } else if (C == '\'') {
1451       O << "\\\'";
1452     } else {
1453      O << C;
1454     }
1455   }
1456   O << "\\0\"";
1457 }
1458
1459 /// PrintLabelName - Print label name in form used by Dwarf writer.
1460 ///
1461 void Dwarf::PrintLabelName(const char *Tag, unsigned Number) const {
1462   O << TAI->getPrivateGlobalPrefix()
1463     << "debug_"
1464     << Tag;
1465   if (Number) O << Number;
1466 }
1467
1468 /// EmitLabel - Emit location label for internal use by Dwarf.
1469 ///
1470 void Dwarf::EmitLabel(const char *Tag, unsigned Number) const {
1471   PrintLabelName(Tag, Number);
1472   O << ":\n";
1473 }
1474
1475 /// EmitReference - Emit a reference to a label.
1476 ///
1477 void Dwarf::EmitReference(const char *Tag, unsigned Number) const {
1478   if (TAI->getAddressSize() == 4)
1479     O << TAI->getData32bitsDirective();
1480   else
1481     O << TAI->getData64bitsDirective();
1482     
1483   PrintLabelName(Tag, Number);
1484 }
1485 void Dwarf::EmitReference(const std::string &Name) const {
1486   if (TAI->getAddressSize() == 4)
1487     O << TAI->getData32bitsDirective();
1488   else
1489     O << TAI->getData64bitsDirective();
1490     
1491   O << Name;
1492 }
1493
1494 /// EmitDifference - Emit an label difference as sizeof(pointer) value.  Some
1495 /// assemblers do not accept absolute expressions with data directives, so there 
1496 /// is an option (needsSet) to use an intermediary 'set' expression.
1497 void Dwarf::EmitDifference(const char *TagHi, unsigned NumberHi,
1498                                  const char *TagLo, unsigned NumberLo) const {
1499   if (TAI->needsSet()) {
1500     static unsigned SetCounter = 0;
1501     
1502     O << "\t.set\t";
1503     PrintLabelName("set", SetCounter);
1504     O << ",";
1505     PrintLabelName(TagHi, NumberHi);
1506     O << "-";
1507     PrintLabelName(TagLo, NumberLo);
1508     O << "\n";
1509     
1510     if (TAI->getAddressSize() == sizeof(int32_t))
1511       O << TAI->getData32bitsDirective();
1512     else
1513       O << TAI->getData64bitsDirective();
1514       
1515     PrintLabelName("set", SetCounter);
1516     
1517     ++SetCounter;
1518   } else {
1519     if (TAI->getAddressSize() == sizeof(int32_t))
1520       O << TAI->getData32bitsDirective();
1521     else
1522       O << TAI->getData64bitsDirective();
1523       
1524     PrintLabelName(TagHi, NumberHi);
1525     O << "-";
1526     PrintLabelName(TagLo, NumberLo);
1527   }
1528 }
1529
1530 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1531 ///  
1532 void Dwarf::AssignAbbrevNumber(DIEAbbrev *Abbrev) {
1533   // Profile the node so that we can make it unique.
1534   FoldingSetNodeID ID;
1535   Abbrev->Profile(ID);
1536   
1537   // Check the set for priors.
1538   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(Abbrev);
1539   
1540   // If it's newly added.
1541   if (InSet == Abbrev) {
1542     // Add to abbreviation list. 
1543     Abbreviations.push_back(Abbrev);
1544     // Assign the vector position + 1 as its number.
1545     Abbrev->setNumber(Abbreviations.size());
1546   } else {
1547     // Assign existing abbreviation number.
1548     Abbrev->setNumber(InSet->getNumber());
1549   }
1550 }
1551
1552 /// NewString - Add a string to the constant pool and returns a label.
1553 ///
1554 DWLabel Dwarf::NewString(const std::string &String) {
1555   unsigned StringID = StringPool.insert(String);
1556   return DWLabel("string", StringID);
1557 }
1558
1559 /// AddSourceLine - Add location information to specified debug information
1560 /// entry.
1561 void Dwarf::AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line){
1562   if (File && Line) {
1563     CompileUnit *FileUnit = FindCompileUnit(File);
1564     unsigned FileID = FileUnit->getID();
1565     Die->AddUInt(DW_AT_decl_file, 0, FileID);
1566     Die->AddUInt(DW_AT_decl_line, 0, Line);
1567   }
1568 }
1569
1570 /// AddAddress - Add an address attribute to a die based on the location
1571 /// provided.
1572 void Dwarf::AddAddress(DIE *Die, unsigned Attribute,
1573                              const MachineLocation &Location) {
1574   DIEBlock *Block = new DIEBlock();
1575   unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1576   
1577   if (Location.isRegister()) {
1578     if (Reg < 32) {
1579       Block->AddUInt(DW_FORM_data1, DW_OP_reg0 + Reg);
1580     } else {
1581       Block->AddUInt(DW_FORM_data1, DW_OP_regx);
1582       Block->AddUInt(DW_FORM_udata, Reg);
1583     }
1584   } else {
1585     if (Reg < 32) {
1586       Block->AddUInt(DW_FORM_data1, DW_OP_breg0 + Reg);
1587     } else {
1588       Block->AddUInt(DW_FORM_data1, DW_OP_bregx);
1589       Block->AddUInt(DW_FORM_udata, Reg);
1590     }
1591     Block->AddUInt(DW_FORM_sdata, Location.getOffset());
1592   }
1593   Block->ComputeSize(*this);
1594   Die->AddBlock(Attribute, 0, Block);
1595 }
1596
1597 /// getDieMapSlotFor - Returns the debug information entry map slot for the
1598 /// specified debug descriptor.
1599 DIE *&Dwarf::getDieMapSlotFor(DebugInfoDesc *DD) {
1600   return DescToDieMap[DD];
1601 }
1602
1603 /// NewType - Create a new type DIE.
1604 ///
1605 DIE *Dwarf::NewType(DIE *Context, TypeDesc *TyDesc, CompileUnit *Unit) {
1606   if (!TyDesc) {
1607     // FIXME - Hack for missing types
1608     DIE *Die = new DIE(DW_TAG_base_type);
1609     Die->AddUInt(DW_AT_byte_size, 0, 4);
1610     Die->AddUInt(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1611     Unit->getDie()->AddChild(Die);
1612     return Die;
1613   }
1614  
1615   // Check for pre-existence.
1616   DIE *&Slot = Unit->getDieMapSlotFor(TyDesc);
1617   if (Slot) return Slot;
1618
1619   // Type DIE result.
1620   DIE *Ty = NULL;
1621
1622   // FIXME - Not sure why programs and variables are coming through here.
1623   // Short cut for handling subprogram types (not really a TyDesc.)
1624   if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1625     Slot = Ty = new DIE(DW_TAG_pointer_type);
1626     Ty->AddUInt(DW_AT_byte_size, 0, TAI->getAddressSize());
1627     Ty->AddString(DW_AT_name, DW_FORM_string, SubprogramTy->getName());
1628     Context->AddChild(Ty);
1629     return Slot;
1630   }
1631   // Short cut for handling global variable types (not really a TyDesc.)
1632   if (GlobalVariableDesc *GlobalVariableTy =
1633                                          dyn_cast<GlobalVariableDesc>(TyDesc)) {
1634     Slot = Ty = new DIE(DW_TAG_pointer_type);
1635     Ty->AddUInt(DW_AT_byte_size, 0, TAI->getAddressSize());
1636     Ty->AddString(DW_AT_name, DW_FORM_string, GlobalVariableTy->getName());
1637     Context->AddChild(Ty);
1638     return Slot;
1639   }
1640   
1641   // Get core information.
1642   const std::string &Name = TyDesc->getName();
1643   uint64_t Size = TyDesc->getSize() >> 3;
1644   
1645   if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1646     // Fundamental types like int, float, bool
1647     Slot = Ty = new DIE(DW_TAG_base_type);
1648     unsigned Encoding = BasicTy->getEncoding();
1649     Ty->AddUInt(DW_AT_encoding,  DW_FORM_data1, Encoding);
1650   } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1651     // Create specific DIE.
1652     Slot = Ty = new DIE(DerivedTy->getTag());
1653     
1654     // Map to main type, void will not have a type.
1655     if (TypeDesc *FromTy = DerivedTy->getFromType()) {
1656       Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1657                      NewType(Context, FromTy, Unit));
1658     }
1659   } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)) {
1660     // Fetch tag
1661     unsigned Tag = CompTy->getTag();
1662     
1663     // Create specific DIE.
1664     Slot = Ty = Tag == DW_TAG_vector_type ? new DIE(DW_TAG_array_type) :
1665                                             new DIE(Tag);
1666     
1667     std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1668     
1669     switch (Tag) {
1670     case DW_TAG_vector_type: Ty->AddUInt(DW_AT_GNU_vector, DW_FORM_flag, 1);
1671       // Fall thru
1672     case DW_TAG_array_type: {
1673       // Add element type.
1674       if (TypeDesc *FromTy = CompTy->getFromType()) {
1675         Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1676                        NewType(Context, FromTy, Unit));
1677       }
1678       
1679       // Don't emit size attribute.
1680       Size = 0;
1681       
1682       // Construct an anonymous type for index type.
1683       DIE *IndexTy = new DIE(DW_TAG_base_type);
1684       IndexTy->AddUInt(DW_AT_byte_size, 0, 4);
1685       IndexTy->AddUInt(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1686       // Add to context.
1687       Context->AddChild(IndexTy);
1688     
1689       // Add subranges to array type.
1690       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1691         SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1692         int64_t Lo = SRD->getLo();
1693         int64_t Hi = SRD->getHi();
1694         DIE *Subrange = new DIE(DW_TAG_subrange_type);
1695         
1696         // If a range is available.
1697         if (Lo != Hi) {
1698           Subrange->AddDIEntry(DW_AT_type, DW_FORM_ref4, IndexTy);
1699           // Only add low if non-zero.
1700           if (Lo) Subrange->AddSInt(DW_AT_lower_bound, 0, Lo);
1701           Subrange->AddSInt(DW_AT_upper_bound, 0, Hi);
1702         }
1703         Ty->AddChild(Subrange);
1704       }
1705       
1706       break;
1707     }
1708     case DW_TAG_structure_type:
1709     case DW_TAG_union_type: {
1710       // Add elements to structure type.
1711       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1712         DebugInfoDesc *Element = Elements[i];
1713         
1714         if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)) {
1715           // Add field or base class.
1716           
1717           unsigned Tag = MemberDesc->getTag();
1718         
1719           // Extract the basic information.
1720           const std::string &Name = MemberDesc->getName();
1721           TypeDesc *MemTy = MemberDesc->getFromType();
1722           uint64_t Size = MemberDesc->getSize();
1723           uint64_t Align = MemberDesc->getAlign();
1724           uint64_t Offset = MemberDesc->getOffset();
1725      
1726           // Construct member debug information entry.
1727           DIE *Member = new DIE(Tag);
1728           
1729           // Add name if not "".
1730           if (!Name.empty())Member->AddString(DW_AT_name, DW_FORM_string, Name);
1731           // Add location if available.
1732           AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1733           
1734           // Most of the time the field info is the same as the members.
1735           uint64_t FieldSize = Size;
1736           uint64_t FieldAlign = Align;
1737           uint64_t FieldOffset = Offset;
1738           
1739           if (TypeDesc *FromTy = MemberDesc->getFromType()) {
1740             Member->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1741                                NewType(Context, FromTy, Unit));
1742             FieldSize = FromTy->getSize();
1743             FieldAlign = FromTy->getSize();
1744           }
1745           
1746           // Unless we have a bit field.
1747           if (Tag == DW_TAG_member && FieldSize != Size) {
1748             // Construct the alignment mask.
1749             uint64_t AlignMask = ~(FieldAlign - 1);
1750             // Determine the high bit + 1 of the declared size.
1751             uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1752             // Work backwards to determine the base offset of the field.
1753             FieldOffset = HiMark - FieldSize;
1754             // Now normalize offset to the field.
1755             Offset -= FieldOffset;
1756             
1757             // Maybe we need to work from the other end.
1758             if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1759             
1760             // Add size and offset.
1761             Member->AddUInt(DW_AT_byte_size, 0, FieldSize >> 3);
1762             Member->AddUInt(DW_AT_bit_size, 0, Size);
1763             Member->AddUInt(DW_AT_bit_offset, 0, Offset);
1764           }
1765           
1766           // Add computation for offset.
1767           DIEBlock *Block = new DIEBlock();
1768           Block->AddUInt(DW_FORM_data1, DW_OP_plus_uconst);
1769           Block->AddUInt(DW_FORM_udata, FieldOffset >> 3);
1770           Block->ComputeSize(*this);
1771           Member->AddBlock(DW_AT_data_member_location, 0, Block);
1772
1773           // Add accessibility (public default unless is base class.
1774           if (MemberDesc->isProtected()) {
1775             Member->AddUInt(DW_AT_accessibility, 0, DW_ACCESS_protected);
1776           } else if (MemberDesc->isPrivate()) {
1777             Member->AddUInt(DW_AT_accessibility, 0, DW_ACCESS_private);
1778           } else if (Tag == DW_TAG_inheritance) {
1779             Member->AddUInt(DW_AT_accessibility, 0, DW_ACCESS_public);
1780           }
1781           
1782           Ty->AddChild(Member);
1783         } else if (GlobalVariableDesc *StaticDesc =
1784                                         dyn_cast<GlobalVariableDesc>(Element)) {
1785           // Add static member.
1786           
1787           // Construct member debug information entry.
1788           DIE *Static = new DIE(DW_TAG_variable);
1789           
1790           // Add name and mangled name.
1791           const std::string &Name = StaticDesc->getDisplayName();
1792           const std::string &MangledName = StaticDesc->getName();
1793           Static->AddString(DW_AT_name, DW_FORM_string, Name);
1794           Static->AddString(DW_AT_MIPS_linkage_name, DW_FORM_string,
1795                             MangledName);
1796           
1797           // Add location.
1798           AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1799          
1800           // Add type.
1801           if (TypeDesc *StaticTy = StaticDesc->getType()) {
1802             Static->AddDIEntry(DW_AT_type, DW_FORM_ref4, 
1803                                NewType(Context, StaticTy, Unit));
1804           }
1805           
1806           // Add flags.
1807           Static->AddUInt(DW_AT_external, DW_FORM_flag, 1);
1808           Static->AddUInt(DW_AT_declaration, DW_FORM_flag, 1);
1809           
1810           Ty->AddChild(Static);
1811         } else if (SubprogramDesc *MethodDesc =
1812                                             dyn_cast<SubprogramDesc>(Element)) {
1813           // Add member function.
1814           
1815           // Construct member debug information entry.
1816           DIE *Method = new DIE(DW_TAG_subprogram);
1817          
1818           // Add name and mangled name.
1819           const std::string &Name = MethodDesc->getDisplayName();
1820           const std::string &MangledName = MethodDesc->getName();
1821           bool IsCTor = false;
1822           
1823           if (Name.empty()) {
1824             Method->AddString(DW_AT_name, DW_FORM_string, MangledName);            
1825             IsCTor = TyDesc->getName() == MangledName;
1826           } else {
1827             Method->AddString(DW_AT_name, DW_FORM_string, Name);            
1828             Method->AddString(DW_AT_MIPS_linkage_name, DW_FORM_string,
1829                               MangledName);
1830           }
1831           
1832           // Add location.
1833           AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1834          
1835           // Add type.
1836           if (CompositeTypeDesc *MethodTy =
1837                    dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1838             // Get argument information.
1839             std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1840            
1841             // If not a ctor.
1842             if (!IsCTor) {
1843               // Add return type.
1844               Method->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1845                                  NewType(Context, dyn_cast<TypeDesc>(Args[0]),
1846                                  Unit));
1847             }
1848             
1849             // Add arguments.
1850             for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1851               DIE *Arg = new DIE(DW_TAG_formal_parameter);
1852               Arg->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1853                               NewType(Context, cast<TypeDesc>(Args[i]), Unit));
1854               Arg->AddUInt(DW_AT_artificial, DW_FORM_flag, 1);
1855               Method->AddChild(Arg);
1856             }
1857           }
1858
1859           // Add flags.
1860           Method->AddUInt(DW_AT_external, DW_FORM_flag, 1);
1861           Method->AddUInt(DW_AT_declaration, DW_FORM_flag, 1);
1862             
1863           Ty->AddChild(Method);
1864         }
1865       }
1866       break;
1867     }
1868     case DW_TAG_enumeration_type: {
1869       // Add enumerators to enumeration type.
1870       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1871         EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1872         const std::string &Name = ED->getName();
1873         int64_t Value = ED->getValue();
1874         DIE *Enumerator = new DIE(DW_TAG_enumerator);
1875         Enumerator->AddString(DW_AT_name, DW_FORM_string, Name);
1876         Enumerator->AddSInt(DW_AT_const_value, DW_FORM_sdata, Value);
1877         Ty->AddChild(Enumerator);
1878       }
1879
1880       break;
1881     }
1882     case DW_TAG_subroutine_type: {
1883       // Add prototype flag.
1884       Ty->AddUInt(DW_AT_prototyped, DW_FORM_flag, 1);
1885       // Add return type.
1886       Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1887                      NewType(Context, dyn_cast<TypeDesc>(Elements[0]), Unit));
1888       
1889       // Add arguments.
1890       for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1891         DIE *Arg = new DIE(DW_TAG_formal_parameter);
1892         Arg->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1893                         NewType(Context, cast<TypeDesc>(Elements[i]), Unit));
1894         Ty->AddChild(Arg);
1895       }
1896       
1897       break;
1898     }
1899     default: break;
1900     }
1901   }
1902     
1903   assert(Ty && "Type not supported yet");
1904  
1905   // Add size if non-zero (derived types don't have a size.)
1906   if (Size) Ty->AddUInt(DW_AT_byte_size, 0, Size);
1907   // Add name if not anonymous or intermediate type.
1908   if (!Name.empty()) Ty->AddString(DW_AT_name, DW_FORM_string, Name);
1909   // Add source line info if available.
1910   AddSourceLine(Ty, TyDesc->getFile(), TyDesc->getLine());
1911
1912   // Add to context owner.
1913   Context->AddChild(Ty);
1914   
1915   return Slot;
1916 }
1917
1918 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1919 ///
1920 CompileUnit *Dwarf::NewCompileUnit(CompileUnitDesc *UnitDesc,
1921                                          unsigned ID) {
1922   // Construct debug information entry.
1923   DIE *Die = new DIE(DW_TAG_compile_unit);
1924   Die->AddDelta (DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0), 
1925                                                  DWLabel("section_line", 0));
1926 //  Die->AddLabel (DW_AT_high_pc,   DW_FORM_addr,   DWLabel("text_end", 0));
1927 //  Die->AddLabel (DW_AT_low_pc,    DW_FORM_addr,   DWLabel("text_begin", 0));
1928   Die->AddString(DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
1929   Die->AddUInt  (DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
1930   Die->AddString(DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
1931   Die->AddString(DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
1932   
1933   // Add debug information entry to descriptor map.
1934   DIE *&Slot = getDieMapSlotFor(UnitDesc);
1935   Slot = Die;
1936   
1937   // Construct compile unit.
1938   CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1939   
1940   // Add Unit to compile unit map.
1941   DescToUnitMap[UnitDesc] = Unit;
1942   
1943   return Unit;
1944 }
1945
1946 /// FindCompileUnit - Get the compile unit for the given descriptor.
1947 ///
1948 CompileUnit *Dwarf::FindCompileUnit(CompileUnitDesc *UnitDesc) {
1949   CompileUnit *Unit = DescToUnitMap[UnitDesc];
1950   assert(Unit && "Missing compile unit.");
1951   return Unit;
1952 }
1953
1954 /// NewGlobalVariable - Add a new global variable DIE.
1955 ///
1956 DIE *Dwarf::NewGlobalVariable(GlobalVariableDesc *GVD) {
1957   // Get the compile unit context.
1958   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(GVD->getContext());
1959   CompileUnit *Unit = FindCompileUnit(UnitDesc);
1960
1961   // Check for pre-existence.
1962   DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1963   if (Slot) return Slot;
1964   
1965   // Get the global variable itself.
1966   GlobalVariable *GV = GVD->getGlobalVariable();
1967
1968   const std::string &Name = GVD->hasMangledName() ? GVD->getDisplayName()
1969                                                   : GVD->getName();
1970   const std::string &MangledName = GVD->hasMangledName() ? GVD->getName()
1971                                                          : "";
1972   // Get the global's type.
1973   DIE *Type = NewType(Unit->getDie(), GVD->getType(), Unit); 
1974
1975   // Create the globale variable DIE.
1976   DIE *VariableDie = new DIE(DW_TAG_variable);
1977   VariableDie->AddString(DW_AT_name, DW_FORM_string, Name);
1978   if (!MangledName.empty()) {
1979     VariableDie->AddString(DW_AT_MIPS_linkage_name, DW_FORM_string,
1980                            MangledName);
1981   }
1982   VariableDie->AddDIEntry(DW_AT_type, DW_FORM_ref4, Type);
1983   VariableDie->AddUInt(DW_AT_external, DW_FORM_flag, 1);
1984   
1985   // Add source line info if available.
1986   AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1987   
1988   // Work up linkage name.
1989   const std::string LinkageName = Asm->getGlobalLinkName(GV);
1990
1991   // Add address.
1992   DIEBlock *Block = new DIEBlock();
1993   Block->AddUInt(DW_FORM_data1, DW_OP_addr);
1994   Block->AddObjectLabel(DW_FORM_udata, LinkageName);
1995   Block->ComputeSize(*this);
1996   VariableDie->AddBlock(DW_AT_location,  0, Block);
1997   
1998   // Add to map.
1999   Slot = VariableDie;
2000  
2001   // Add to context owner.
2002   Unit->getDie()->AddChild(VariableDie);
2003   
2004   // Expose as global.
2005   // FIXME - need to check external flag.
2006   Unit->AddGlobal(Name, VariableDie);
2007   
2008   return VariableDie;
2009 }
2010
2011 /// NewSubprogram - Add a new subprogram DIE.
2012 ///
2013 DIE *Dwarf::NewSubprogram(SubprogramDesc *SPD) {
2014   // Get the compile unit context.
2015   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
2016   CompileUnit *Unit = FindCompileUnit(UnitDesc);
2017
2018   // Check for pre-existence.
2019   DIE *&Slot = Unit->getDieMapSlotFor(SPD);
2020   if (Slot) return Slot;
2021   
2022   // Gather the details (simplify add attribute code.)
2023   const std::string &Name = SPD->hasMangledName() ? SPD->getDisplayName()
2024                                                   : SPD->getName();
2025   const std::string &MangledName = SPD->hasMangledName() ? SPD->getName()
2026                                                          : "";
2027   DIE *Type = NewType(Unit->getDie(), SPD->getType(), Unit); 
2028   unsigned IsExternal = SPD->isStatic() ? 0 : 1;
2029                                     
2030   DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2031   SubprogramDie->AddString(DW_AT_name, DW_FORM_string, Name);
2032   if (!MangledName.empty()) {
2033     SubprogramDie->AddString(DW_AT_MIPS_linkage_name, DW_FORM_string,
2034                              MangledName);
2035   }
2036   if (Type) {
2037     SubprogramDie->AddDIEntry(DW_AT_type, DW_FORM_ref4, Type);
2038   }
2039   SubprogramDie->AddUInt(DW_AT_external, DW_FORM_flag, IsExternal);
2040   SubprogramDie->AddUInt(DW_AT_prototyped, DW_FORM_flag, 1);
2041   
2042   // Add source line info if available.
2043   AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2044
2045   // Add to map.
2046   Slot = SubprogramDie;
2047  
2048   // Add to context owner.
2049   Unit->getDie()->AddChild(SubprogramDie);
2050   
2051   // Expose as global.
2052   Unit->AddGlobal(Name, SubprogramDie);
2053   
2054   return SubprogramDie;
2055 }
2056
2057 /// NewScopeVariable - Create a new scope variable.
2058 ///
2059 DIE *Dwarf::NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2060   // Get the descriptor.
2061   VariableDesc *VD = DV->getDesc();
2062
2063   // Translate tag to proper Dwarf tag.  The result variable is dropped for now.
2064   unsigned Tag;
2065   switch (VD->getTag()) {
2066   case DW_TAG_return_variable:  return NULL;
2067   case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
2068   case DW_TAG_auto_variable:    // fall thru
2069   default:                      Tag = DW_TAG_variable; break;
2070   }
2071
2072   // Define variable debug information entry.
2073   DIE *VariableDie = new DIE(Tag);
2074   VariableDie->AddString(DW_AT_name, DW_FORM_string, VD->getName());
2075
2076   // Add source line info if available.
2077   AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2078   
2079   // Add variable type.
2080   DIE *Type = NewType(Unit->getDie(), VD->getType(), Unit); 
2081   VariableDie->AddDIEntry(DW_AT_type, DW_FORM_ref4, Type);
2082   
2083   // Add variable address.
2084   MachineLocation Location;
2085   RI->getLocation(*MF, DV->getFrameIndex(), Location);
2086   AddAddress(VariableDie, DW_AT_location, Location);
2087   
2088   return VariableDie;
2089 }
2090
2091 /// ConstructScope - Construct the components of a scope.
2092 ///
2093 void Dwarf::ConstructScope(DebugScope *ParentScope,
2094                                  DIE *ParentDie, CompileUnit *Unit) {
2095   // Add variables to scope.
2096   std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2097   for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2098     DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2099     if (VariableDie) ParentDie->AddChild(VariableDie);
2100   }
2101   
2102   // Add nested scopes.
2103   std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2104   for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2105     // Define the Scope debug information entry.
2106     DebugScope *Scope = Scopes[j];
2107     // FIXME - Ignore inlined functions for the time being.
2108     if (!Scope->getParent()) continue;
2109     
2110     unsigned StartID = Scope->getStartLabelID();
2111     unsigned EndID = Scope->getEndLabelID();
2112     
2113     // Throw out scope if block is discarded.
2114     if (StartID && !DebugInfo->isLabelValid(StartID)) continue;
2115     if (EndID && !DebugInfo->isLabelValid(EndID)) continue;
2116     
2117     DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2118     
2119     // Add the scope bounds.
2120     if (StartID) {
2121       ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
2122                          DWLabel("loc", StartID));
2123     } else {
2124       ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
2125                          DWLabel("func_begin", SubprogramCount));
2126     }
2127     if (EndID) {
2128       ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
2129                          DWLabel("loc", EndID));
2130     } else {
2131       ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
2132                          DWLabel("func_end", SubprogramCount));
2133     }
2134                        
2135     // Add the scope contents.
2136     ConstructScope(Scope, ScopeDie, Unit);
2137     ParentDie->AddChild(ScopeDie);
2138   }
2139 }
2140
2141 /// ConstructRootScope - Construct the scope for the subprogram.
2142 ///
2143 void Dwarf::ConstructRootScope(DebugScope *RootScope) {
2144   // Exit if there is no root scope.
2145   if (!RootScope) return;
2146   
2147   // Get the subprogram debug information entry. 
2148   SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2149   
2150   // Get the compile unit context.
2151   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
2152   CompileUnit *Unit = FindCompileUnit(UnitDesc);
2153   
2154   // Get the subprogram die.
2155   DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2156   assert(SPDie && "Missing subprogram descriptor");
2157   
2158   // Add the function bounds.
2159   SPDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
2160                   DWLabel("func_begin", SubprogramCount));
2161   SPDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
2162                   DWLabel("func_end", SubprogramCount));
2163   MachineLocation Location(RI->getFrameRegister(*MF));
2164   AddAddress(SPDie, DW_AT_frame_base, Location);
2165                   
2166   ConstructScope(RootScope, SPDie, Unit);
2167 }
2168
2169 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
2170 /// tools to recognize the object file contains Dwarf information.
2171 ///
2172 void Dwarf::EmitInitial() {
2173   // Check to see if we already emitted intial headers.
2174   if (didInitial) return;
2175   didInitial = true;
2176   
2177   // Dwarf sections base addresses.
2178   if (TAI->getDwarfRequiresFrameSection()) {
2179     Asm->SwitchToDataSection(TAI->getDwarfFrameSection(), 0);
2180     EmitLabel("section_frame", 0);
2181   }
2182   Asm->SwitchToDataSection(TAI->getDwarfInfoSection(), 0);
2183   EmitLabel("section_info", 0);
2184   Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection(), 0);
2185   EmitLabel("section_abbrev", 0);
2186   Asm->SwitchToDataSection(TAI->getDwarfARangesSection(), 0);
2187   EmitLabel("section_aranges", 0);
2188   Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection(), 0);
2189   EmitLabel("section_macinfo", 0);
2190   Asm->SwitchToDataSection(TAI->getDwarfLineSection(), 0);
2191   EmitLabel("section_line", 0);
2192   Asm->SwitchToDataSection(TAI->getDwarfLocSection(), 0);
2193   EmitLabel("section_loc", 0);
2194   Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection(), 0);
2195   EmitLabel("section_pubnames", 0);
2196   Asm->SwitchToDataSection(TAI->getDwarfStrSection(), 0);
2197   EmitLabel("section_str", 0);
2198   Asm->SwitchToDataSection(TAI->getDwarfRangesSection(), 0);
2199   EmitLabel("section_ranges", 0);
2200   Asm->SwitchToTextSection(TAI->getTextSection(), 0);
2201   EmitLabel("text_begin", 0);
2202   Asm->SwitchToDataSection(TAI->getDataSection(), 0);
2203   EmitLabel("data_begin", 0);
2204
2205   // Emit common frame information.
2206   EmitInitialDebugFrame();
2207 }
2208
2209 /// EmitDIE - Recusively Emits a debug information entry.
2210 ///
2211 void Dwarf::EmitDIE(DIE *Die) const {
2212   // Get the abbreviation for this DIE.
2213   unsigned AbbrevNumber = Die->getAbbrevNumber();
2214   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2215   
2216   O << "\n";
2217
2218   // Emit the code (index) for the abbreviation.
2219   EmitULEB128Bytes(AbbrevNumber);
2220   EOL(std::string("Abbrev [" +
2221       utostr(AbbrevNumber) +
2222       "] 0x" + utohexstr(Die->getOffset()) +
2223       ":0x" + utohexstr(Die->getSize()) + " " +
2224       TagString(Abbrev->getTag())));
2225   
2226   const std::vector<DIEValue *> &Values = Die->getValues();
2227   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2228   
2229   // Emit the DIE attribute values.
2230   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2231     unsigned Attr = AbbrevData[i].getAttribute();
2232     unsigned Form = AbbrevData[i].getForm();
2233     assert(Form && "Too many attributes for DIE (check abbreviation)");
2234     
2235     switch (Attr) {
2236     case DW_AT_sibling: {
2237       EmitInt32(Die->SiblingOffset());
2238       break;
2239     }
2240     default: {
2241       // Emit an attribute using the defined form.
2242       Values[i]->EmitValue(*this, Form);
2243       break;
2244     }
2245     }
2246     
2247     EOL(AttributeString(Attr));
2248   }
2249   
2250   // Emit the DIE children if any.
2251   if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2252     const std::vector<DIE *> &Children = Die->getChildren();
2253     
2254     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2255       EmitDIE(Children[j]);
2256     }
2257     
2258     EmitInt8(0); EOL("End Of Children Mark");
2259   }
2260 }
2261
2262 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2263 ///
2264 unsigned Dwarf::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2265   // Get the children.
2266   const std::vector<DIE *> &Children = Die->getChildren();
2267   
2268   // If not last sibling and has children then add sibling offset attribute.
2269   if (!Last && !Children.empty()) Die->AddSiblingOffset();
2270
2271   // Record the abbreviation.
2272   Die->Complete(*this);
2273   
2274   // Get the abbreviation for this DIE.
2275   unsigned AbbrevNumber = Die->getAbbrevNumber();
2276   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2277
2278   // Set DIE offset
2279   Die->setOffset(Offset);
2280   
2281   // Start the size with the size of abbreviation code.
2282   Offset += SizeULEB128(AbbrevNumber);
2283   
2284   const std::vector<DIEValue *> &Values = Die->getValues();
2285   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2286
2287   // Emit the DIE attribute values.
2288   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2289     // Size attribute value.
2290     Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2291   }
2292   
2293   // Emit the DIE children if any.
2294   if (!Children.empty()) {
2295     assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2296            "Children flag not set");
2297     
2298     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2299       Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2300     }
2301     
2302     // End of children marker.
2303     Offset += sizeof(int8_t);
2304   }
2305
2306   Die->setSize(Offset - Die->getOffset());
2307   return Offset;
2308 }
2309
2310 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2311 ///
2312 void Dwarf::SizeAndOffsets() {
2313   
2314   // Process each compile unit.
2315   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2316     CompileUnit *Unit = CompileUnits[i];
2317     if (Unit->hasContent()) {
2318       // Compute size of compile unit header
2319       unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2320                         sizeof(int16_t) + // DWARF version number
2321                         sizeof(int32_t) + // Offset Into Abbrev. Section
2322                         sizeof(int8_t);   // Pointer Size (in bytes)
2323       SizeAndOffsetDie(Unit->getDie(), Offset, (i + 1) == N);
2324     }
2325   }
2326 }
2327
2328 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
2329 /// frame.
2330 void Dwarf::EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
2331                                  std::vector<MachineMove *> &Moves) {
2332   for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
2333     MachineMove *Move = Moves[i];
2334     unsigned LabelID = Move->getLabelID();
2335     
2336     // Throw out move if the label is invalid.
2337     if (LabelID && !DebugInfo->isLabelValid(LabelID)) continue;
2338     
2339     const MachineLocation &Dst = Move->getDestination();
2340     const MachineLocation &Src = Move->getSource();
2341     
2342     // Advance row if new location.
2343     if (BaseLabel && LabelID && BaseLabelID != LabelID) {
2344       EmitInt8(DW_CFA_advance_loc4);
2345       EOL("DW_CFA_advance_loc4");
2346       EmitDifference("loc", LabelID, BaseLabel, BaseLabelID);
2347       EOL("");
2348       
2349       BaseLabelID = LabelID;
2350       BaseLabel = "loc";
2351     }
2352     
2353     int stackGrowth =
2354         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2355           TargetFrameInfo::StackGrowsUp ?
2356             TAI->getAddressSize() : -TAI->getAddressSize();
2357
2358     // If advancing cfa.
2359     if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
2360       if (!Src.isRegister()) {
2361         if (Src.getRegister() == MachineLocation::VirtualFP) {
2362           EmitInt8(DW_CFA_def_cfa_offset);
2363           EOL("DW_CFA_def_cfa_offset");
2364         } else {
2365           EmitInt8(DW_CFA_def_cfa);
2366           EOL("DW_CFA_def_cfa");
2367           
2368           EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
2369           EOL("Register");
2370         }
2371         
2372         int Offset = Src.getOffset() / stackGrowth;
2373         
2374         EmitULEB128Bytes(Offset);
2375         EOL("Offset");
2376       } else {
2377         assert(0 && "Machine move no supported yet.");
2378       }
2379     } else {
2380       unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
2381       int Offset = Dst.getOffset() / stackGrowth;
2382       
2383       if (Offset < 0) {
2384         EmitInt8(DW_CFA_offset_extended_sf);
2385         EOL("DW_CFA_offset_extended_sf");
2386         EmitULEB128Bytes(Reg);
2387         EOL("Reg");
2388         EmitSLEB128Bytes(Offset);
2389         EOL("Offset");
2390       } else if (Reg < 64) {
2391         EmitInt8(DW_CFA_offset + Reg);
2392         EOL("DW_CFA_offset + Reg");
2393         EmitULEB128Bytes(Offset);
2394         EOL("Offset");
2395       } else {
2396         EmitInt8(DW_CFA_offset_extended);
2397         EOL("DW_CFA_offset_extended");
2398         EmitULEB128Bytes(Reg);
2399         EOL("Reg");
2400         EmitULEB128Bytes(Offset);
2401         EOL("Offset");
2402       }
2403     }
2404   }
2405 }
2406
2407 /// EmitDebugInfo - Emit the debug info section.
2408 ///
2409 void Dwarf::EmitDebugInfo() const {
2410   // Start debug info section.
2411   Asm->SwitchToDataSection(TAI->getDwarfInfoSection(), 0);
2412   
2413   // Process each compile unit.
2414   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2415     CompileUnit *Unit = CompileUnits[i];
2416     
2417     if (Unit->hasContent()) {
2418       DIE *Die = Unit->getDie();
2419       // Emit the compile units header.
2420       EmitLabel("info_begin", Unit->getID());
2421       // Emit size of content not including length itself
2422       unsigned ContentSize = Die->getSize() +
2423                              sizeof(int16_t) + // DWARF version number
2424                              sizeof(int32_t) + // Offset Into Abbrev. Section
2425                              sizeof(int8_t);   // Pointer Size (in bytes)
2426                              
2427       EmitInt32(ContentSize);  EOL("Length of Compilation Unit Info");
2428       EmitInt16(DWARF_VERSION); EOL("DWARF version number");
2429       EmitDifference("abbrev_begin", 0, "section_abbrev", 0);
2430       EOL("Offset Into Abbrev. Section");
2431       EmitInt8(TAI->getAddressSize()); EOL("Address Size (in bytes)");
2432     
2433       EmitDIE(Die);
2434       EmitLabel("info_end", Unit->getID());
2435     }
2436     
2437     O << "\n";
2438   }
2439 }
2440
2441 /// EmitAbbreviations - Emit the abbreviation section.
2442 ///
2443 void Dwarf::EmitAbbreviations() const {
2444   // Check to see if it is worth the effort.
2445   if (!Abbreviations.empty()) {
2446     // Start the debug abbrev section.
2447     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection(), 0);
2448     
2449     EmitLabel("abbrev_begin", 0);
2450     
2451     // For each abbrevation.
2452     for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2453       // Get abbreviation data
2454       const DIEAbbrev *Abbrev = Abbreviations[i];
2455       
2456       // Emit the abbrevations code (base 1 index.)
2457       EmitULEB128Bytes(Abbrev->getNumber()); EOL("Abbreviation Code");
2458       
2459       // Emit the abbreviations data.
2460       Abbrev->Emit(*this);
2461   
2462       O << "\n";
2463     }
2464     
2465     EmitLabel("abbrev_end", 0);
2466   
2467     O << "\n";
2468   }
2469 }
2470
2471 /// EmitDebugLines - Emit source line information.
2472 ///
2473 void Dwarf::EmitDebugLines() const {
2474   // Minimum line delta, thus ranging from -10..(255-10).
2475   const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2476   // Maximum line delta, thus ranging from -10..(255-10).
2477   const int MaxLineDelta = 255 + MinLineDelta;
2478
2479   // Start the dwarf line section.
2480   Asm->SwitchToDataSection(TAI->getDwarfLineSection(), 0);
2481   
2482   // Construct the section header.
2483   
2484   EmitDifference("line_end", 0, "line_begin", 0);
2485   EOL("Length of Source Line Info");
2486   EmitLabel("line_begin", 0);
2487   
2488   EmitInt16(DWARF_VERSION); EOL("DWARF version number");
2489   
2490   EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0);
2491   EOL("Prolog Length");
2492   EmitLabel("line_prolog_begin", 0);
2493   
2494   EmitInt8(1); EOL("Minimum Instruction Length");
2495
2496   EmitInt8(1); EOL("Default is_stmt_start flag");
2497
2498   EmitInt8(MinLineDelta);  EOL("Line Base Value (Special Opcodes)");
2499   
2500   EmitInt8(MaxLineDelta); EOL("Line Range Value (Special Opcodes)");
2501
2502   EmitInt8(-MinLineDelta); EOL("Special Opcode Base");
2503   
2504   // Line number standard opcode encodings argument count
2505   EmitInt8(0); EOL("DW_LNS_copy arg count");
2506   EmitInt8(1); EOL("DW_LNS_advance_pc arg count");
2507   EmitInt8(1); EOL("DW_LNS_advance_line arg count");
2508   EmitInt8(1); EOL("DW_LNS_set_file arg count");
2509   EmitInt8(1); EOL("DW_LNS_set_column arg count");
2510   EmitInt8(0); EOL("DW_LNS_negate_stmt arg count");
2511   EmitInt8(0); EOL("DW_LNS_set_basic_block arg count");
2512   EmitInt8(0); EOL("DW_LNS_const_add_pc arg count");
2513   EmitInt8(1); EOL("DW_LNS_fixed_advance_pc arg count");
2514
2515   const UniqueVector<std::string> &Directories = DebugInfo->getDirectories();
2516   const UniqueVector<SourceFileInfo> &SourceFiles = DebugInfo->getSourceFiles();
2517
2518   // Emit directories.
2519   for (unsigned DirectoryID = 1, NDID = Directories.size();
2520                 DirectoryID <= NDID; ++DirectoryID) {
2521     EmitString(Directories[DirectoryID]); EOL("Directory");
2522   }
2523   EmitInt8(0); EOL("End of directories");
2524   
2525   // Emit files.
2526   for (unsigned SourceID = 1, NSID = SourceFiles.size();
2527                SourceID <= NSID; ++SourceID) {
2528     const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2529     EmitString(SourceFile.getName()); EOL("Source");
2530     EmitULEB128Bytes(SourceFile.getDirectoryID());  EOL("Directory #");
2531     EmitULEB128Bytes(0);  EOL("Mod date");
2532     EmitULEB128Bytes(0);  EOL("File size");
2533   }
2534   EmitInt8(0); EOL("End of files");
2535   
2536   EmitLabel("line_prolog_end", 0);
2537   
2538   // A sequence for each text section.
2539   for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2540     // Isolate current sections line info.
2541     const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2542     
2543     if (DwarfVerbose) {
2544       O << "\t"
2545         << TAI->getCommentString() << " "
2546         << "Section "
2547         << SectionMap[j + 1].c_str() << "\n";
2548     }
2549
2550     // Dwarf assumes we start with first line of first source file.
2551     unsigned Source = 1;
2552     unsigned Line = 1;
2553     
2554     // Construct rows of the address, source, line, column matrix.
2555     for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2556       const SourceLineInfo &LineInfo = LineInfos[i];
2557       unsigned LabelID = LineInfo.getLabelID();
2558       
2559       // Source line labels are validated at the MachineDebugInfo level.
2560       
2561       if (DwarfVerbose) {
2562         unsigned SourceID = LineInfo.getSourceID();
2563         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2564         unsigned DirectoryID = SourceFile.getDirectoryID();
2565         O << "\t"
2566           << TAI->getCommentString() << " "
2567           << Directories[DirectoryID]
2568           << SourceFile.getName() << ":"
2569           << LineInfo.getLine() << "\n"; 
2570       }
2571
2572       // Define the line address.
2573       EmitInt8(0); EOL("Extended Op");
2574       EmitInt8(4 + 1); EOL("Op size");
2575       EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
2576       EmitReference("loc",  LabelID); EOL("Location label");
2577       
2578       // If change of source, then switch to the new source.
2579       if (Source != LineInfo.getSourceID()) {
2580         Source = LineInfo.getSourceID();
2581         EmitInt8(DW_LNS_set_file); EOL("DW_LNS_set_file");
2582         EmitULEB128Bytes(Source); EOL("New Source");
2583       }
2584       
2585       // If change of line.
2586       if (Line != LineInfo.getLine()) {
2587         // Determine offset.
2588         int Offset = LineInfo.getLine() - Line;
2589         int Delta = Offset - MinLineDelta;
2590         
2591         // Update line.
2592         Line = LineInfo.getLine();
2593         
2594         // If delta is small enough and in range...
2595         if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2596           // ... then use fast opcode.
2597           EmitInt8(Delta - MinLineDelta); EOL("Line Delta");
2598         } else {
2599           // ... otherwise use long hand.
2600           EmitInt8(DW_LNS_advance_line); EOL("DW_LNS_advance_line");
2601           EmitSLEB128Bytes(Offset); EOL("Line Offset");
2602           EmitInt8(DW_LNS_copy); EOL("DW_LNS_copy");
2603         }
2604       } else {
2605         // Copy the previous row (different address or source)
2606         EmitInt8(DW_LNS_copy); EOL("DW_LNS_copy");
2607       }
2608     }
2609
2610     // Define last address of section.
2611     EmitInt8(0); EOL("Extended Op");
2612     EmitInt8(4 + 1); EOL("Op size");
2613     EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
2614     EmitReference("section_end", j + 1); EOL("Section end label");
2615
2616     // Mark end of matrix.
2617     EmitInt8(0); EOL("DW_LNE_end_sequence");
2618     EmitULEB128Bytes(1);  O << "\n";
2619     EmitInt8(1); O << "\n";
2620   }
2621   
2622   EmitLabel("line_end", 0);
2623   
2624   O << "\n";
2625 }
2626   
2627 /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
2628 ///
2629 void Dwarf::EmitInitialDebugFrame() {
2630   if (TAI->getDwarfRequiresFrameSection())
2631     return;
2632
2633   int stackGrowth =
2634       Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2635         TargetFrameInfo::StackGrowsUp ?
2636       TAI->getAddressSize() : -TAI->getAddressSize();
2637
2638   // Start the dwarf frame section.
2639   Asm->SwitchToDataSection(TAI->getDwarfFrameSection(), 0);
2640
2641   EmitLabel("frame_common", 0);
2642   EmitDifference("frame_common_end", 0,
2643                  "frame_common_begin", 0);
2644   EOL("Length of Common Information Entry");
2645
2646   EmitLabel("frame_common_begin", 0);
2647   EmitInt32(DW_CIE_ID); EOL("CIE Identifier Tag");
2648   EmitInt8(DW_CIE_VERSION); EOL("CIE Version");
2649   EmitString("");  EOL("CIE Augmentation");
2650   EmitULEB128Bytes(1); EOL("CIE Code Alignment Factor");
2651   EmitSLEB128Bytes(stackGrowth); EOL("CIE Data Alignment Factor");   
2652   EmitInt8(RI->getDwarfRegNum(RI->getRARegister())); EOL("CIE RA Column");
2653   
2654   std::vector<MachineMove *> Moves;
2655   RI->getInitialFrameState(Moves);
2656   EmitFrameMoves(NULL, 0, Moves);
2657   for (unsigned i = 0, N = Moves.size(); i < N; ++i) delete Moves[i];
2658
2659   EmitAlign(2);
2660   EmitLabel("frame_common_end", 0);
2661   
2662   O << "\n";
2663 }
2664
2665 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2666 /// section.
2667 void Dwarf::EmitFunctionDebugFrame() {
2668   if (TAI->getDwarfRequiresFrameSection())
2669     return;
2670
2671   // Start the dwarf frame section.
2672   Asm->SwitchToDataSection(TAI->getDwarfFrameSection(), 0);
2673   
2674   EmitDifference("frame_end", SubprogramCount,
2675                  "frame_begin", SubprogramCount);
2676   EOL("Length of Frame Information Entry");
2677   
2678   EmitLabel("frame_begin", SubprogramCount);
2679   
2680   EmitDifference("frame_common", 0, "section_frame", 0);
2681   EOL("FDE CIE offset");
2682
2683   EmitReference("func_begin", SubprogramCount); EOL("FDE initial location");
2684   EmitDifference("func_end", SubprogramCount,
2685                  "func_begin", SubprogramCount);
2686   EOL("FDE address range");
2687   
2688   std::vector<MachineMove *> &Moves = DebugInfo->getFrameMoves();
2689   
2690   EmitFrameMoves("func_begin", SubprogramCount, Moves);
2691   
2692   EmitAlign(2);
2693   EmitLabel("frame_end", SubprogramCount);
2694
2695   O << "\n";
2696 }
2697
2698 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2699 ///
2700 void Dwarf::EmitDebugPubNames() {
2701   // Start the dwarf pubnames section.
2702   Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection(), 0);
2703     
2704   // Process each compile unit.
2705   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2706     CompileUnit *Unit = CompileUnits[i];
2707     
2708     if (Unit->hasContent()) {
2709       EmitDifference("pubnames_end", Unit->getID(),
2710                      "pubnames_begin", Unit->getID());
2711       EOL("Length of Public Names Info");
2712       
2713       EmitLabel("pubnames_begin", Unit->getID());
2714       
2715       EmitInt16(DWARF_VERSION); EOL("DWARF Version");
2716       
2717       EmitDifference("info_begin", Unit->getID(), "section_info", 0);
2718       EOL("Offset of Compilation Unit Info");
2719
2720       EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID());
2721       EOL("Compilation Unit Length");
2722       
2723       std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2724       
2725       for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2726                                                   GE = Globals.end();
2727            GI != GE; ++GI) {
2728         const std::string &Name = GI->first;
2729         DIE * Entity = GI->second;
2730         
2731         EmitInt32(Entity->getOffset()); EOL("DIE offset");
2732         EmitString(Name); EOL("External Name");
2733       }
2734     
2735       EmitInt32(0); EOL("End Mark");
2736       EmitLabel("pubnames_end", Unit->getID());
2737     
2738       O << "\n";
2739     }
2740   }
2741 }
2742
2743 /// EmitDebugStr - Emit visible names into a debug str section.
2744 ///
2745 void Dwarf::EmitDebugStr() {
2746   // Check to see if it is worth the effort.
2747   if (!StringPool.empty()) {
2748     // Start the dwarf str section.
2749     Asm->SwitchToDataSection(TAI->getDwarfStrSection(), 0);
2750     
2751     // For each of strings in the string pool.
2752     for (unsigned StringID = 1, N = StringPool.size();
2753          StringID <= N; ++StringID) {
2754       // Emit a label for reference from debug information entries.
2755       EmitLabel("string", StringID);
2756       // Emit the string itself.
2757       const std::string &String = StringPool[StringID];
2758       EmitString(String); O << "\n";
2759     }
2760   
2761     O << "\n";
2762   }
2763 }
2764
2765 /// EmitDebugLoc - Emit visible names into a debug loc section.
2766 ///
2767 void Dwarf::EmitDebugLoc() {
2768   // Start the dwarf loc section.
2769   Asm->SwitchToDataSection(TAI->getDwarfLocSection(), 0);
2770   
2771   O << "\n";
2772 }
2773
2774 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2775 ///
2776 void Dwarf::EmitDebugARanges() {
2777   // Start the dwarf aranges section.
2778   Asm->SwitchToDataSection(TAI->getDwarfARangesSection(), 0);
2779   
2780   // FIXME - Mock up
2781 #if 0
2782   // Process each compile unit.
2783   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2784     CompileUnit *Unit = CompileUnits[i];
2785     
2786     if (Unit->hasContent()) {
2787       // Don't include size of length
2788       EmitInt32(0x1c); EOL("Length of Address Ranges Info");
2789       
2790       EmitInt16(DWARF_VERSION); EOL("Dwarf Version");
2791       
2792       EmitReference("info_begin", Unit->getID());
2793       EOL("Offset of Compilation Unit Info");
2794
2795       EmitInt8(TAI->getAddressSize()); EOL("Size of Address");
2796
2797       EmitInt8(0); EOL("Size of Segment Descriptor");
2798
2799       EmitInt16(0);  EOL("Pad (1)");
2800       EmitInt16(0);  EOL("Pad (2)");
2801
2802       // Range 1
2803       EmitReference("text_begin", 0); EOL("Address");
2804       EmitDifference("text_end", 0, "text_begin", 0); EOL("Length");
2805
2806       EmitInt32(0); EOL("EOM (1)");
2807       EmitInt32(0); EOL("EOM (2)");
2808       
2809       O << "\n";
2810     }
2811   }
2812 #endif
2813 }
2814
2815 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2816 ///
2817 void Dwarf::EmitDebugRanges() {
2818   // Start the dwarf ranges section.
2819   Asm->SwitchToDataSection(TAI->getDwarfRangesSection(), 0);
2820   
2821   O << "\n";
2822 }
2823
2824 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2825 ///
2826 void Dwarf::EmitDebugMacInfo() {
2827   // Start the dwarf macinfo section.
2828   Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection(), 0);
2829   
2830   O << "\n";
2831 }
2832
2833 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2834 /// header file.
2835 void Dwarf::ConstructCompileUnitDIEs() {
2836   const UniqueVector<CompileUnitDesc *> CUW = DebugInfo->getCompileUnits();
2837   
2838   for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2839     CompileUnit *Unit = NewCompileUnit(CUW[i], i);
2840     CompileUnits.push_back(Unit);
2841   }
2842 }
2843
2844 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible global
2845 /// variables.
2846 void Dwarf::ConstructGlobalDIEs() {
2847   std::vector<GlobalVariableDesc *> GlobalVariables =
2848       DebugInfo->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2849   
2850   for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2851     GlobalVariableDesc *GVD = GlobalVariables[i];
2852     NewGlobalVariable(GVD);
2853   }
2854 }
2855
2856 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2857 /// subprograms.
2858 void Dwarf::ConstructSubprogramDIEs() {
2859   std::vector<SubprogramDesc *> Subprograms =
2860       DebugInfo->getAnchoredDescriptors<SubprogramDesc>(*M);
2861   
2862   for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2863     SubprogramDesc *SPD = Subprograms[i];
2864     NewSubprogram(SPD);
2865   }
2866 }
2867
2868 //===----------------------------------------------------------------------===//
2869 /// Dwarf implemenation.
2870 //
2871   
2872 Dwarf::Dwarf(std::ostream &OS, AsmPrinter *A,
2873   const TargetAsmInfo *T)
2874 : O(OS)
2875 , Asm(A)
2876 , TAI(T)
2877 , TD(Asm->TM.getTargetData())
2878 , RI(Asm->TM.getRegisterInfo())
2879 , M(NULL)
2880 , MF(NULL)
2881 , DebugInfo(NULL)
2882 , didInitial(false)
2883 , shouldEmit(false)
2884 , SubprogramCount(0)
2885 , CompileUnits()
2886 , AbbreviationsSet()
2887 , Abbreviations()
2888 , StringPool()
2889 , DescToUnitMap()
2890 , DescToDieMap()
2891 , SectionMap()
2892 , SectionSourceLines()
2893 {
2894 }
2895 Dwarf::~Dwarf() {
2896   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2897     delete CompileUnits[i];
2898   }
2899 }
2900
2901 /// SetDebugInfo - Set DebugInfo when it's known that pass manager has
2902 /// created it.  Set by the target AsmPrinter.
2903 void Dwarf::SetDebugInfo(MachineDebugInfo *DI) {
2904   // Make sure initial declarations are made.
2905   if (!DebugInfo && DI->hasInfo()) {
2906     DebugInfo = DI;
2907     shouldEmit = true;
2908     
2909     // Emit initial sections
2910     EmitInitial();
2911   
2912     // Create all the compile unit DIEs.
2913     ConstructCompileUnitDIEs();
2914     
2915     // Create DIEs for each of the externally visible global variables.
2916     ConstructGlobalDIEs();
2917
2918     // Create DIEs for each of the externally visible subprograms.
2919     ConstructSubprogramDIEs();
2920     
2921     // Prime section data.
2922     SectionMap.insert(std::string("\t") + TAI->getTextSection());
2923   }
2924 }
2925
2926 /// BeginModule - Emit all Dwarf sections that should come prior to the content.
2927 ///
2928 void Dwarf::BeginModule(Module *M) {
2929   this->M = M;
2930   
2931   if (!ShouldEmitDwarf()) return;
2932   EOL("Dwarf Begin Module");
2933 }
2934
2935 /// EndModule - Emit all Dwarf sections that should come after the content.
2936 ///
2937 void Dwarf::EndModule() {
2938   if (!ShouldEmitDwarf()) return;
2939   EOL("Dwarf End Module");
2940   
2941   // Standard sections final addresses.
2942   Asm->SwitchToTextSection(TAI->getTextSection(), 0);
2943   EmitLabel("text_end", 0);
2944   Asm->SwitchToDataSection(TAI->getDataSection(), 0);
2945   EmitLabel("data_end", 0);
2946   
2947   // End text sections.
2948   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2949     Asm->SwitchToTextSection(SectionMap[i].c_str(), 0);
2950     EmitLabel("section_end", i);
2951   }
2952   
2953   // Compute DIE offsets and sizes.
2954   SizeAndOffsets();
2955   
2956   // Emit all the DIEs into a debug info section
2957   EmitDebugInfo();
2958   
2959   // Corresponding abbreviations into a abbrev section.
2960   EmitAbbreviations();
2961   
2962   // Emit source line correspondence into a debug line section.
2963   EmitDebugLines();
2964   
2965   // Emit info into a debug pubnames section.
2966   EmitDebugPubNames();
2967   
2968   // Emit info into a debug str section.
2969   EmitDebugStr();
2970   
2971   // Emit info into a debug loc section.
2972   EmitDebugLoc();
2973   
2974   // Emit info into a debug aranges section.
2975   EmitDebugARanges();
2976   
2977   // Emit info into a debug ranges section.
2978   EmitDebugRanges();
2979   
2980   // Emit info into a debug macinfo section.
2981   EmitDebugMacInfo();
2982 }
2983
2984 /// BeginFunction - Gather pre-function debug information.  Assumes being 
2985 /// emitted immediately after the function entry point.
2986 void Dwarf::BeginFunction(MachineFunction *MF) {
2987   this->MF = MF;
2988   
2989   if (!ShouldEmitDwarf()) return;
2990   EOL("Dwarf Begin Function");
2991
2992   // Begin accumulating function debug information.
2993   DebugInfo->BeginFunction(MF);
2994   
2995   // Assumes in correct section after the entry point.
2996   EmitLabel("func_begin", ++SubprogramCount);
2997 }
2998
2999 /// EndFunction - Gather and emit post-function debug information.
3000 ///
3001 void Dwarf::EndFunction() {
3002   if (!ShouldEmitDwarf()) return;
3003   EOL("Dwarf End Function");
3004   
3005   // Define end label for subprogram.
3006   EmitLabel("func_end", SubprogramCount);
3007     
3008   // Get function line info.
3009   const std::vector<SourceLineInfo> &LineInfos = DebugInfo->getSourceLines();
3010
3011   if (!LineInfos.empty()) {
3012     // Get section line info.
3013     unsigned ID = SectionMap.insert(Asm->CurrentSection);
3014     if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3015     std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3016     // Append the function info to section info.
3017     SectionLineInfos.insert(SectionLineInfos.end(),
3018                             LineInfos.begin(), LineInfos.end());
3019   }
3020   
3021   // Construct scopes for subprogram.
3022   ConstructRootScope(DebugInfo->getRootScope());
3023   
3024   // Emit function frame information.
3025   EmitFunctionDebugFrame();
3026   
3027   // Reset the line numbers for the next function.
3028   DebugInfo->ClearLineInfo();
3029
3030   // Clear function debug information.
3031   DebugInfo->EndFunction();
3032 }
3033
3034
3035 //===----------------------------------------------------------------------===//
3036 /// DwarfWriter Implementation
3037
3038 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3039                          const TargetAsmInfo *T) {
3040   DW = new Dwarf(OS, A, T);
3041 }
3042
3043 DwarfWriter::~DwarfWriter() {
3044   delete DW;
3045 }
3046
3047 /// SetDebugInfo - Set DebugInfo when it's known that pass manager has
3048 /// created it.  Set by the target AsmPrinter.
3049 void DwarfWriter::SetDebugInfo(MachineDebugInfo *DI) {
3050   DW->SetDebugInfo(DI);
3051 }
3052
3053 /// BeginModule - Emit all Dwarf sections that should come prior to the
3054 /// content.
3055 void DwarfWriter::BeginModule(Module *M) {
3056   DW->BeginModule(M);
3057 }
3058
3059 /// EndModule - Emit all Dwarf sections that should come after the content.
3060 ///
3061 void DwarfWriter::EndModule() {
3062   DW->EndModule();
3063 }
3064
3065 /// BeginFunction - Gather pre-function debug information.  Assumes being 
3066 /// emitted immediately after the function entry point.
3067 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3068   DW->BeginFunction(MF);
3069 }
3070
3071 /// EndFunction - Gather and emit post-function debug information.
3072 ///
3073 void DwarfWriter::EndFunction() {
3074   DW->EndFunction();
3075 }