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