Slip up
[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>debug_<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 << ".debug_" << 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   /// didInitial - Flag to indicate if initial emission has been done.
795   ///
796   bool didInitial;
797   
798   /// shouldEmit - Flag to indicate if debug information should be emitted.
799   ///
800   bool shouldEmit;
801   
802   /// SubprogramCount - The running count of functions being compiled.
803   ///
804   unsigned SubprogramCount;
805   
806   Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
807   : O(OS)
808   , Asm(A)
809   , TAI(T)
810   , TD(Asm->TM.getTargetData())
811   , RI(Asm->TM.getRegisterInfo())
812   , M(NULL)
813   , MF(NULL)
814   , MMI(NULL)
815   , didInitial(false)
816   , shouldEmit(false)
817   , SubprogramCount(0)
818   {
819   }
820
821 public:
822
823   //===--------------------------------------------------------------------===//
824   // Accessors.
825   //
826   AsmPrinter *getAsm() const { return Asm; }
827   MachineModuleInfo *getMMI() const { return MMI; }
828   const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
829
830   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
831   ///
832   bool ShouldEmitDwarf() const { return shouldEmit; }
833
834
835   /// PrintLabelName - Print label name in form used by Dwarf writer.
836   ///
837   void PrintLabelName(DWLabel Label) const {
838     PrintLabelName(Label.Tag, Label.Number);
839   }
840   void PrintLabelName(const char *Tag, unsigned Number) const {
841     O << TAI->getPrivateGlobalPrefix()
842       << ((Tag && *Tag) ? "debug_" : "label_")
843       << Tag;
844     if (Number) O << Number;
845   }
846   
847   /// EmitLabel - Emit location label for internal use by Dwarf.
848   ///
849   void EmitLabel(DWLabel Label) const {
850     EmitLabel(Label.Tag, Label.Number);
851   }
852   void EmitLabel(const char *Tag, unsigned Number) const {
853     PrintLabelName(Tag, Number);
854     O << ":\n";
855   }
856   
857   /// EmitReference - Emit a reference to a label.
858   ///
859   void EmitReference(DWLabel Label, bool IsPCRelative = false) const {
860     EmitReference(Label.Tag, Label.Number, IsPCRelative);
861   }
862   void EmitReference(const char *Tag, unsigned Number,
863                      bool IsPCRelative = false) const {
864     if (TAI->getAddressSize() == sizeof(int32_t))
865       O << TAI->getData32bitsDirective();
866     else
867       O << TAI->getData64bitsDirective();
868       
869     PrintLabelName(Tag, Number);
870     
871     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
872   }
873   void EmitReference(const std::string &Name, bool IsPCRelative = false) const {
874     if (TAI->getAddressSize() == sizeof(int32_t))
875       O << TAI->getData32bitsDirective();
876     else
877       O << TAI->getData64bitsDirective();
878       
879     O << Name;
880     
881     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
882   }
883
884   /// EmitDifference - Emit the difference between two labels.  Some
885   /// assemblers do not behave with absolute expressions with data directives,
886   /// so there is an option (needsSet) to use an intermediary set expression.
887   void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
888                       bool IsSmall = false) const {
889     EmitDifference(LabelHi.Tag, LabelHi.Number,
890                    LabelLo.Tag, LabelLo.Number,
891                    IsSmall);
892   }
893   void EmitDifference(const char *TagHi, unsigned NumberHi,
894                       const char *TagLo, unsigned NumberLo,
895                       bool IsSmall = false) const {
896     if (TAI->needsSet()) {
897       static unsigned SetCounter = 1;
898       
899       O << "\t.set\t";
900       PrintLabelName("set", SetCounter);
901       O << ",";
902       PrintLabelName(TagHi, NumberHi);
903       O << "-";
904       PrintLabelName(TagLo, NumberLo);
905       O << "\n";
906       
907       if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
908         O << TAI->getData32bitsDirective();
909       else
910         O << TAI->getData64bitsDirective();
911         
912       PrintLabelName("set", SetCounter);
913       
914       ++SetCounter;
915     } else {
916       if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
917         O << TAI->getData32bitsDirective();
918       else
919         O << TAI->getData64bitsDirective();
920         
921       PrintLabelName(TagHi, NumberHi);
922       O << "-";
923       PrintLabelName(TagLo, NumberLo);
924     }
925   }
926                       
927   /// EmitFrameMoves - Emit frame instructions to describe the layout of the
928   /// frame.
929   void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
930                                    std::vector<MachineMove> &Moves) {
931     int stackGrowth =
932         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
933           TargetFrameInfo::StackGrowsUp ?
934             TAI->getAddressSize() : -TAI->getAddressSize();
935     bool IsLocal = BaseLabel && strcmp(BaseLabel, "") == 0;
936
937     for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
938       MachineMove &Move = Moves[i];
939       unsigned LabelID = Move.getLabelID();
940       
941       if (LabelID) {
942         LabelID = MMI->MappedLabel(LabelID);
943       
944         // Throw out move if the label is invalid.
945         if (!LabelID) continue;
946       }
947       
948       const MachineLocation &Dst = Move.getDestination();
949       const MachineLocation &Src = Move.getSource();
950       
951       // Advance row if new location.
952       if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
953         Asm->EmitInt8(DW_CFA_advance_loc4);
954         Asm->EOL("DW_CFA_advance_loc4");
955         EmitDifference("", LabelID, BaseLabel, BaseLabelID, true);
956         Asm->EOL("");
957         
958         BaseLabelID = LabelID;
959         BaseLabel = "";
960         IsLocal = true;
961       }
962       
963       // If advancing cfa.
964       if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
965         if (!Src.isRegister()) {
966           if (Src.getRegister() == MachineLocation::VirtualFP) {
967             Asm->EmitInt8(DW_CFA_def_cfa_offset);
968             Asm->EOL("DW_CFA_def_cfa_offset");
969           } else {
970             Asm->EmitInt8(DW_CFA_def_cfa);
971             Asm->EOL("DW_CFA_def_cfa");
972             Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
973             Asm->EOL("Register");
974           }
975           
976           int Offset = -Src.getOffset();
977           
978           Asm->EmitULEB128Bytes(Offset);
979           Asm->EOL("Offset");
980         } else {
981           assert(0 && "Machine move no supported yet.");
982         }
983       } else if (Src.isRegister() &&
984         Src.getRegister() == MachineLocation::VirtualFP) {
985         if (Dst.isRegister()) {
986           Asm->EmitInt8(DW_CFA_def_cfa_register);
987           Asm->EOL("DW_CFA_def_cfa_register");
988           Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister()));
989           Asm->EOL("Register");
990         } else {
991           assert(0 && "Machine move no supported yet.");
992         }
993       } else {
994         unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
995         int Offset = Dst.getOffset() / stackGrowth;
996         
997         if (Offset < 0) {
998           Asm->EmitInt8(DW_CFA_offset_extended_sf);
999           Asm->EOL("DW_CFA_offset_extended_sf");
1000           Asm->EmitULEB128Bytes(Reg);
1001           Asm->EOL("Reg");
1002           Asm->EmitSLEB128Bytes(Offset);
1003           Asm->EOL("Offset");
1004         } else if (Reg < 64) {
1005           Asm->EmitInt8(DW_CFA_offset + Reg);
1006           Asm->EOL("DW_CFA_offset + Reg");
1007           Asm->EmitULEB128Bytes(Offset);
1008           Asm->EOL("Offset");
1009         } else {
1010           Asm->EmitInt8(DW_CFA_offset_extended);
1011           Asm->EOL("DW_CFA_offset_extended");
1012           Asm->EmitULEB128Bytes(Reg);
1013           Asm->EOL("Reg");
1014           Asm->EmitULEB128Bytes(Offset);
1015           Asm->EOL("Offset");
1016         }
1017       }
1018     }
1019   }
1020
1021 };
1022
1023 //===----------------------------------------------------------------------===//
1024 /// DwarfDebug - Emits Dwarf debug directives. 
1025 ///
1026 class DwarfDebug : public Dwarf {
1027
1028 private:
1029   //===--------------------------------------------------------------------===//
1030   // Attributes used to construct specific Dwarf sections.
1031   //
1032   
1033   /// CompileUnits - All the compile units involved in this build.  The index
1034   /// of each entry in this vector corresponds to the sources in MMI.
1035   std::vector<CompileUnit *> CompileUnits;
1036   
1037   /// AbbreviationsSet - Used to uniquely define abbreviations.
1038   ///
1039   FoldingSet<DIEAbbrev> AbbreviationsSet;
1040
1041   /// Abbreviations - A list of all the unique abbreviations in use.
1042   ///
1043   std::vector<DIEAbbrev *> Abbreviations;
1044   
1045   /// ValuesSet - Used to uniquely define values.
1046   ///
1047   FoldingSet<DIEValue> ValuesSet;
1048   
1049   /// Values - A list of all the unique values in use.
1050   ///
1051   std::vector<DIEValue *> Values;
1052   
1053   /// StringPool - A UniqueVector of strings used by indirect references.
1054   ///
1055   UniqueVector<std::string> StringPool;
1056
1057   /// UnitMap - Map debug information descriptor to compile unit.
1058   ///
1059   std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1060   
1061   /// SectionMap - Provides a unique id per text section.
1062   ///
1063   UniqueVector<std::string> SectionMap;
1064   
1065   /// SectionSourceLines - Tracks line numbers per text section.
1066   ///
1067   std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1068
1069
1070 public:
1071
1072   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1073   ///  
1074   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1075     // Profile the node so that we can make it unique.
1076     FoldingSetNodeID ID;
1077     Abbrev.Profile(ID);
1078     
1079     // Check the set for priors.
1080     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1081     
1082     // If it's newly added.
1083     if (InSet == &Abbrev) {
1084       // Add to abbreviation list. 
1085       Abbreviations.push_back(&Abbrev);
1086       // Assign the vector position + 1 as its number.
1087       Abbrev.setNumber(Abbreviations.size());
1088     } else {
1089       // Assign existing abbreviation number.
1090       Abbrev.setNumber(InSet->getNumber());
1091     }
1092   }
1093
1094   /// NewString - Add a string to the constant pool and returns a label.
1095   ///
1096   DWLabel NewString(const std::string &String) {
1097     unsigned StringID = StringPool.insert(String);
1098     return DWLabel("string", StringID);
1099   }
1100   
1101   /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1102   /// entry.
1103   DIEntry *NewDIEntry(DIE *Entry = NULL) {
1104     DIEntry *Value;
1105     
1106     if (Entry) {
1107       FoldingSetNodeID ID;
1108       DIEntry::Profile(ID, Entry);
1109       void *Where;
1110       Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1111       
1112       if (Value) return Value;
1113       
1114       Value = new DIEntry(Entry);
1115       ValuesSet.InsertNode(Value, Where);
1116     } else {
1117       Value = new DIEntry(Entry);
1118     }
1119     
1120     Values.push_back(Value);
1121     return Value;
1122   }
1123   
1124   /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1125   ///
1126   void SetDIEntry(DIEntry *Value, DIE *Entry) {
1127     Value->Entry = Entry;
1128     // Add to values set if not already there.  If it is, we merely have a
1129     // duplicate in the values list (no harm.)
1130     ValuesSet.GetOrInsertNode(Value);
1131   }
1132
1133   /// AddUInt - Add an unsigned integer attribute data and value.
1134   ///
1135   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1136     if (!Form) Form = DIEInteger::BestForm(false, Integer);
1137
1138     FoldingSetNodeID ID;
1139     DIEInteger::Profile(ID, Integer);
1140     void *Where;
1141     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1142     if (!Value) {
1143       Value = new DIEInteger(Integer);
1144       ValuesSet.InsertNode(Value, Where);
1145       Values.push_back(Value);
1146     }
1147   
1148     Die->AddValue(Attribute, Form, Value);
1149   }
1150       
1151   /// AddSInt - Add an signed integer attribute data and value.
1152   ///
1153   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1154     if (!Form) Form = DIEInteger::BestForm(true, Integer);
1155
1156     FoldingSetNodeID ID;
1157     DIEInteger::Profile(ID, (uint64_t)Integer);
1158     void *Where;
1159     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1160     if (!Value) {
1161       Value = new DIEInteger(Integer);
1162       ValuesSet.InsertNode(Value, Where);
1163       Values.push_back(Value);
1164     }
1165   
1166     Die->AddValue(Attribute, Form, Value);
1167   }
1168       
1169   /// AddString - Add a std::string attribute data and value.
1170   ///
1171   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1172                  const std::string &String) {
1173     FoldingSetNodeID ID;
1174     DIEString::Profile(ID, String);
1175     void *Where;
1176     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1177     if (!Value) {
1178       Value = new DIEString(String);
1179       ValuesSet.InsertNode(Value, Where);
1180       Values.push_back(Value);
1181     }
1182   
1183     Die->AddValue(Attribute, Form, Value);
1184   }
1185       
1186   /// AddLabel - Add a Dwarf label attribute data and value.
1187   ///
1188   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1189                      const DWLabel &Label) {
1190     FoldingSetNodeID ID;
1191     DIEDwarfLabel::Profile(ID, Label);
1192     void *Where;
1193     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1194     if (!Value) {
1195       Value = new DIEDwarfLabel(Label);
1196       ValuesSet.InsertNode(Value, Where);
1197       Values.push_back(Value);
1198     }
1199   
1200     Die->AddValue(Attribute, Form, Value);
1201   }
1202       
1203   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1204   ///
1205   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1206                       const std::string &Label) {
1207     FoldingSetNodeID ID;
1208     DIEObjectLabel::Profile(ID, Label);
1209     void *Where;
1210     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1211     if (!Value) {
1212       Value = new DIEObjectLabel(Label);
1213       ValuesSet.InsertNode(Value, Where);
1214       Values.push_back(Value);
1215     }
1216   
1217     Die->AddValue(Attribute, Form, Value);
1218   }
1219       
1220   /// AddDelta - Add a label delta attribute data and value.
1221   ///
1222   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1223                           const DWLabel &Hi, const DWLabel &Lo) {
1224     FoldingSetNodeID ID;
1225     DIEDelta::Profile(ID, Hi, Lo);
1226     void *Where;
1227     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1228     if (!Value) {
1229       Value = new DIEDelta(Hi, Lo);
1230       ValuesSet.InsertNode(Value, Where);
1231       Values.push_back(Value);
1232     }
1233   
1234     Die->AddValue(Attribute, Form, Value);
1235   }
1236       
1237   /// AddDIEntry - Add a DIE attribute data and value.
1238   ///
1239   void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1240     Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1241   }
1242
1243   /// AddBlock - Add block data.
1244   ///
1245   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1246     Block->ComputeSize(*this);
1247     FoldingSetNodeID ID;
1248     Block->Profile(ID);
1249     void *Where;
1250     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1251     if (!Value) {
1252       Value = Block;
1253       ValuesSet.InsertNode(Value, Where);
1254       Values.push_back(Value);
1255     } else {
1256       delete Block;
1257     }
1258   
1259     Die->AddValue(Attribute, Block->BestForm(), Value);
1260   }
1261
1262 private:
1263
1264   /// AddSourceLine - Add location information to specified debug information
1265   /// entry.
1266   void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1267     if (File && Line) {
1268       CompileUnit *FileUnit = FindCompileUnit(File);
1269       unsigned FileID = FileUnit->getID();
1270       AddUInt(Die, DW_AT_decl_file, 0, FileID);
1271       AddUInt(Die, DW_AT_decl_line, 0, Line);
1272     }
1273   }
1274
1275   /// AddAddress - Add an address attribute to a die based on the location
1276   /// provided.
1277   void AddAddress(DIE *Die, unsigned Attribute,
1278                             const MachineLocation &Location) {
1279     unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1280     DIEBlock *Block = new DIEBlock();
1281     
1282     if (Location.isRegister()) {
1283       if (Reg < 32) {
1284         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1285       } else {
1286         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1287         AddUInt(Block, 0, DW_FORM_udata, Reg);
1288       }
1289     } else {
1290       if (Reg < 32) {
1291         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1292       } else {
1293         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1294         AddUInt(Block, 0, DW_FORM_udata, Reg);
1295       }
1296       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1297     }
1298     
1299     AddBlock(Die, Attribute, 0, Block);
1300   }
1301   
1302   /// AddBasicType - Add a new basic type attribute to the specified entity.
1303   ///
1304   void AddBasicType(DIE *Entity, CompileUnit *Unit,
1305                     const std::string &Name,
1306                     unsigned Encoding, unsigned Size) {
1307     DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1308     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1309   }
1310   
1311   /// ConstructBasicType - Construct a new basic type.
1312   ///
1313   DIE *ConstructBasicType(CompileUnit *Unit,
1314                           const std::string &Name,
1315                           unsigned Encoding, unsigned Size) {
1316     DIE Buffer(DW_TAG_base_type);
1317     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1318     AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1319     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1320     return Unit->AddDie(Buffer);
1321   }
1322   
1323   /// AddPointerType - Add a new pointer type attribute to the specified entity.
1324   ///
1325   void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1326     DIE *Die = ConstructPointerType(Unit, Name);
1327     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1328   }
1329   
1330   /// ConstructPointerType - Construct a new pointer type.
1331   ///
1332   DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1333     DIE Buffer(DW_TAG_pointer_type);
1334     AddUInt(&Buffer, DW_AT_byte_size, 0, TAI->getAddressSize());
1335     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1336     return Unit->AddDie(Buffer);
1337   }
1338   
1339   /// AddType - Add a new type attribute to the specified entity.
1340   ///
1341   void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1342     if (!TyDesc) {
1343       AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1344     } else {
1345       // Check for pre-existence.
1346       DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1347       
1348       // If it exists then use the existing value.
1349       if (Slot) {
1350         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1351         return;
1352       }
1353       
1354       if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1355         // FIXME - Not sure why programs and variables are coming through here.
1356         // Short cut for handling subprogram types (not really a TyDesc.)
1357         AddPointerType(Entity, Unit, SubprogramTy->getName());
1358       } else if (GlobalVariableDesc *GlobalTy =
1359                                          dyn_cast<GlobalVariableDesc>(TyDesc)) {
1360         // FIXME - Not sure why programs and variables are coming through here.
1361         // Short cut for handling global variable types (not really a TyDesc.)
1362         AddPointerType(Entity, Unit, GlobalTy->getName());
1363       } else {  
1364         // Set up proxy.
1365         Slot = NewDIEntry();
1366         
1367         // Construct type.
1368         DIE Buffer(DW_TAG_base_type);
1369         ConstructType(Buffer, TyDesc, Unit);
1370         
1371         // Add debug information entry to entity and unit.
1372         DIE *Die = Unit->AddDie(Buffer);
1373         SetDIEntry(Slot, Die);
1374         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1375       }
1376     }
1377   }
1378   
1379   /// ConstructType - Adds all the required attributes to the type.
1380   ///
1381   void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1382     // Get core information.
1383     const std::string &Name = TyDesc->getName();
1384     uint64_t Size = TyDesc->getSize() >> 3;
1385     
1386     if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1387       // Fundamental types like int, float, bool
1388       Buffer.setTag(DW_TAG_base_type);
1389       AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BasicTy->getEncoding());
1390     } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1391       // Fetch tag.
1392       unsigned Tag = DerivedTy->getTag();
1393       // FIXME - Workaround for templates.
1394       if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1395       // Pointers, typedefs et al. 
1396       Buffer.setTag(Tag);
1397       // Map to main type, void will not have a type.
1398       if (TypeDesc *FromTy = DerivedTy->getFromType())
1399         AddType(&Buffer, FromTy, Unit);
1400     } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1401       // Fetch tag.
1402       unsigned Tag = CompTy->getTag();
1403       
1404       // Set tag accordingly.
1405       if (Tag == DW_TAG_vector_type)
1406         Buffer.setTag(DW_TAG_array_type);
1407       else 
1408         Buffer.setTag(Tag);
1409
1410       std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1411       
1412       switch (Tag) {
1413       case DW_TAG_vector_type:
1414         AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1415         // Fall thru
1416       case DW_TAG_array_type: {
1417         // Add element type.
1418         if (TypeDesc *FromTy = CompTy->getFromType())
1419           AddType(&Buffer, FromTy, Unit);
1420         
1421         // Don't emit size attribute.
1422         Size = 0;
1423         
1424         // Construct an anonymous type for index type.
1425         DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1426                                           sizeof(int32_t));
1427       
1428         // Add subranges to array type.
1429         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1430           SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1431           int64_t Lo = SRD->getLo();
1432           int64_t Hi = SRD->getHi();
1433           DIE *Subrange = new DIE(DW_TAG_subrange_type);
1434           
1435           // If a range is available.
1436           if (Lo != Hi) {
1437             AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1438             // Only add low if non-zero.
1439             if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1440             AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1441           }
1442           
1443           Buffer.AddChild(Subrange);
1444         }
1445         break;
1446       }
1447       case DW_TAG_structure_type:
1448       case DW_TAG_union_type: {
1449         // Add elements to structure type.
1450         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1451           DebugInfoDesc *Element = Elements[i];
1452           
1453           if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1454             // Add field or base class.
1455             
1456             unsigned Tag = MemberDesc->getTag();
1457           
1458             // Extract the basic information.
1459             const std::string &Name = MemberDesc->getName();
1460             uint64_t Size = MemberDesc->getSize();
1461             uint64_t Align = MemberDesc->getAlign();
1462             uint64_t Offset = MemberDesc->getOffset();
1463        
1464             // Construct member debug information entry.
1465             DIE *Member = new DIE(Tag);
1466             
1467             // Add name if not "".
1468             if (!Name.empty())
1469               AddString(Member, DW_AT_name, DW_FORM_string, Name);
1470             // Add location if available.
1471             AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1472             
1473             // Most of the time the field info is the same as the members.
1474             uint64_t FieldSize = Size;
1475             uint64_t FieldAlign = Align;
1476             uint64_t FieldOffset = Offset;
1477             
1478             // Set the member type.
1479             TypeDesc *FromTy = MemberDesc->getFromType();
1480             AddType(Member, FromTy, Unit);
1481             
1482             // Walk up typedefs until a real size is found.
1483             while (FromTy) {
1484               if (FromTy->getTag() != DW_TAG_typedef) {
1485                 FieldSize = FromTy->getSize();
1486                 FieldAlign = FromTy->getSize();
1487                 break;
1488               }
1489               
1490               FromTy = dyn_cast<DerivedTypeDesc>(FromTy)->getFromType();
1491             }
1492             
1493             // Unless we have a bit field.
1494             if (Tag == DW_TAG_member && FieldSize != Size) {
1495               // Construct the alignment mask.
1496               uint64_t AlignMask = ~(FieldAlign - 1);
1497               // Determine the high bit + 1 of the declared size.
1498               uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1499               // Work backwards to determine the base offset of the field.
1500               FieldOffset = HiMark - FieldSize;
1501               // Now normalize offset to the field.
1502               Offset -= FieldOffset;
1503               
1504               // Maybe we need to work from the other end.
1505               if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1506               
1507               // Add size and offset.
1508               AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1509               AddUInt(Member, DW_AT_bit_size, 0, Size);
1510               AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1511             }
1512             
1513             // Add computation for offset.
1514             DIEBlock *Block = new DIEBlock();
1515             AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1516             AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1517             AddBlock(Member, DW_AT_data_member_location, 0, Block);
1518
1519             // Add accessibility (public default unless is base class.
1520             if (MemberDesc->isProtected()) {
1521               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1522             } else if (MemberDesc->isPrivate()) {
1523               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1524             } else if (Tag == DW_TAG_inheritance) {
1525               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1526             }
1527             
1528             Buffer.AddChild(Member);
1529           } else if (GlobalVariableDesc *StaticDesc =
1530                                         dyn_cast<GlobalVariableDesc>(Element)) {
1531             // Add static member.
1532             
1533             // Construct member debug information entry.
1534             DIE *Static = new DIE(DW_TAG_variable);
1535             
1536             // Add name and mangled name.
1537             const std::string &Name = StaticDesc->getName();
1538             const std::string &LinkageName = StaticDesc->getLinkageName();
1539             AddString(Static, DW_AT_name, DW_FORM_string, Name);
1540             if (!LinkageName.empty()) {
1541               AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1542                                 LinkageName);
1543             }
1544             
1545             // Add location.
1546             AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1547            
1548             // Add type.
1549             if (TypeDesc *StaticTy = StaticDesc->getType())
1550               AddType(Static, StaticTy, Unit);
1551             
1552             // Add flags.
1553             if (!StaticDesc->isStatic())
1554               AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1555             AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1556             
1557             Buffer.AddChild(Static);
1558           } else if (SubprogramDesc *MethodDesc =
1559                                             dyn_cast<SubprogramDesc>(Element)) {
1560             // Add member function.
1561             
1562             // Construct member debug information entry.
1563             DIE *Method = new DIE(DW_TAG_subprogram);
1564            
1565             // Add name and mangled name.
1566             const std::string &Name = MethodDesc->getName();
1567             const std::string &LinkageName = MethodDesc->getLinkageName();
1568             
1569             AddString(Method, DW_AT_name, DW_FORM_string, Name);            
1570             bool IsCTor = TyDesc->getName() == Name;
1571             
1572             if (!LinkageName.empty()) {
1573               AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1574                                 LinkageName);
1575             }
1576             
1577             // Add location.
1578             AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1579            
1580             // Add type.
1581             if (CompositeTypeDesc *MethodTy =
1582                    dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1583               // Get argument information.
1584               std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1585              
1586               // If not a ctor.
1587               if (!IsCTor) {
1588                 // Add return type.
1589                 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1590               }
1591               
1592               // Add arguments.
1593               for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1594                 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1595                 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1596                 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1597                 Method->AddChild(Arg);
1598               }
1599             }
1600
1601             // Add flags.
1602             if (!MethodDesc->isStatic())
1603               AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1604             AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1605               
1606             Buffer.AddChild(Method);
1607           }
1608         }
1609         break;
1610       }
1611       case DW_TAG_enumeration_type: {
1612         // Add enumerators to enumeration type.
1613         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1614           EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1615           const std::string &Name = ED->getName();
1616           int64_t Value = ED->getValue();
1617           DIE *Enumerator = new DIE(DW_TAG_enumerator);
1618           AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1619           AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1620           Buffer.AddChild(Enumerator);
1621         }
1622
1623         break;
1624       }
1625       case DW_TAG_subroutine_type: {
1626         // Add prototype flag.
1627         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1628         // Add return type.
1629         AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1630         
1631         // Add arguments.
1632         for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1633           DIE *Arg = new DIE(DW_TAG_formal_parameter);
1634           AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1635           Buffer.AddChild(Arg);
1636         }
1637         
1638         break;
1639       }
1640       default: break;
1641       }
1642     }
1643    
1644     // Add size if non-zero (derived types don't have a size.)
1645     if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1646     // Add name if not anonymous or intermediate type.
1647     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1648     // Add source line info if available.
1649     AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1650   }
1651
1652   /// NewCompileUnit - Create new compile unit and it's debug information entry.
1653   ///
1654   CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1655     // Construct debug information entry.
1656     DIE *Die = new DIE(DW_TAG_compile_unit);
1657     AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1658                                                   DWLabel("section_line", 0));
1659     AddString(Die, DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
1660     AddUInt  (Die, DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
1661     AddString(Die, DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
1662     AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
1663     
1664     // Construct compile unit.
1665     CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1666     
1667     // Add Unit to compile unit map.
1668     DescToUnitMap[UnitDesc] = Unit;
1669     
1670     return Unit;
1671   }
1672
1673   /// GetBaseCompileUnit - Get the main compile unit.
1674   ///
1675   CompileUnit *GetBaseCompileUnit() const {
1676     CompileUnit *Unit = CompileUnits[0];
1677     assert(Unit && "Missing compile unit.");
1678     return Unit;
1679   }
1680
1681   /// FindCompileUnit - Get the compile unit for the given descriptor.
1682   ///
1683   CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1684     CompileUnit *Unit = DescToUnitMap[UnitDesc];
1685     assert(Unit && "Missing compile unit.");
1686     return Unit;
1687   }
1688
1689   /// NewGlobalVariable - Add a new global variable DIE.
1690   ///
1691   DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1692     // Get the compile unit context.
1693     CompileUnitDesc *UnitDesc =
1694       static_cast<CompileUnitDesc *>(GVD->getContext());
1695     CompileUnit *Unit = GetBaseCompileUnit();
1696
1697     // Check for pre-existence.
1698     DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1699     if (Slot) return Slot;
1700     
1701     // Get the global variable itself.
1702     GlobalVariable *GV = GVD->getGlobalVariable();
1703
1704     const std::string &Name = GVD->getName();
1705     const std::string &FullName = GVD->getFullName();
1706     const std::string &LinkageName = GVD->getLinkageName();
1707     // Create the global's variable DIE.
1708     DIE *VariableDie = new DIE(DW_TAG_variable);
1709     AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1710     if (!LinkageName.empty()) {
1711       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1712                              LinkageName);
1713     }
1714     AddType(VariableDie, GVD->getType(), Unit);
1715     if (!GVD->isStatic())
1716       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1717     
1718     // Add source line info if available.
1719     AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1720     
1721     // Add address.
1722     DIEBlock *Block = new DIEBlock();
1723     AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1724     AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1725     AddBlock(VariableDie, DW_AT_location, 0, Block);
1726     
1727     // Add to map.
1728     Slot = VariableDie;
1729    
1730     // Add to context owner.
1731     Unit->getDie()->AddChild(VariableDie);
1732     
1733     // Expose as global.
1734     // FIXME - need to check external flag.
1735     Unit->AddGlobal(FullName, VariableDie);
1736     
1737     return VariableDie;
1738   }
1739
1740   /// NewSubprogram - Add a new subprogram DIE.
1741   ///
1742   DIE *NewSubprogram(SubprogramDesc *SPD) {
1743     // Get the compile unit context.
1744     CompileUnitDesc *UnitDesc =
1745       static_cast<CompileUnitDesc *>(SPD->getContext());
1746     CompileUnit *Unit = GetBaseCompileUnit();
1747
1748     // Check for pre-existence.
1749     DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1750     if (Slot) return Slot;
1751     
1752     // Gather the details (simplify add attribute code.)
1753     const std::string &Name = SPD->getName();
1754     const std::string &FullName = SPD->getFullName();
1755     const std::string &LinkageName = SPD->getLinkageName();
1756                                       
1757     DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1758     AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1759     if (!LinkageName.empty()) {
1760       AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1761                                LinkageName);
1762     }
1763     if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1764     if (!SPD->isStatic())
1765       AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1766     AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1767     
1768     // Add source line info if available.
1769     AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1770
1771     // Add to map.
1772     Slot = SubprogramDie;
1773    
1774     // Add to context owner.
1775     Unit->getDie()->AddChild(SubprogramDie);
1776     
1777     // Expose as global.
1778     Unit->AddGlobal(FullName, SubprogramDie);
1779     
1780     return SubprogramDie;
1781   }
1782
1783   /// NewScopeVariable - Create a new scope variable.
1784   ///
1785   DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1786     // Get the descriptor.
1787     VariableDesc *VD = DV->getDesc();
1788
1789     // Translate tag to proper Dwarf tag.  The result variable is dropped for
1790     // now.
1791     unsigned Tag;
1792     switch (VD->getTag()) {
1793     case DW_TAG_return_variable:  return NULL;
1794     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
1795     case DW_TAG_auto_variable:    // fall thru
1796     default:                      Tag = DW_TAG_variable; break;
1797     }
1798
1799     // Define variable debug information entry.
1800     DIE *VariableDie = new DIE(Tag);
1801     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1802
1803     // Add source line info if available.
1804     AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1805     
1806     // Add variable type.
1807     AddType(VariableDie, VD->getType(), Unit); 
1808     
1809     // Add variable address.
1810     MachineLocation Location;
1811     RI->getLocation(*MF, DV->getFrameIndex(), Location);
1812     AddAddress(VariableDie, DW_AT_location, Location);
1813
1814     return VariableDie;
1815   }
1816
1817   /// ConstructScope - Construct the components of a scope.
1818   ///
1819   void ConstructScope(DebugScope *ParentScope,
1820                       unsigned ParentStartID, unsigned ParentEndID,
1821                       DIE *ParentDie, CompileUnit *Unit) {
1822     // Add variables to scope.
1823     std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1824     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1825       DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1826       if (VariableDie) ParentDie->AddChild(VariableDie);
1827     }
1828     
1829     // Add nested scopes.
1830     std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1831     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1832       // Define the Scope debug information entry.
1833       DebugScope *Scope = Scopes[j];
1834       // FIXME - Ignore inlined functions for the time being.
1835       if (!Scope->getParent()) continue;
1836       
1837       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1838       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1839
1840       // Ignore empty scopes.
1841       if (StartID == EndID && StartID != 0) continue;
1842       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1843       
1844       if (StartID == ParentStartID && EndID == ParentEndID) {
1845         // Just add stuff to the parent scope.
1846         ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1847       } else {
1848         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1849         
1850         // Add the scope bounds.
1851         if (StartID) {
1852           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1853                              DWLabel("", StartID));
1854         } else {
1855           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1856                              DWLabel("func_begin", SubprogramCount));
1857         }
1858         if (EndID) {
1859           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1860                              DWLabel("", EndID));
1861         } else {
1862           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1863                              DWLabel("func_end", SubprogramCount));
1864         }
1865                            
1866         // Add the scope contents.
1867         ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1868         ParentDie->AddChild(ScopeDie);
1869       }
1870     }
1871   }
1872
1873   /// ConstructRootScope - Construct the scope for the subprogram.
1874   ///
1875   void ConstructRootScope(DebugScope *RootScope) {
1876     // Exit if there is no root scope.
1877     if (!RootScope) return;
1878     
1879     // Get the subprogram debug information entry. 
1880     SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1881     
1882     // Get the compile unit context.
1883     CompileUnit *Unit = GetBaseCompileUnit();
1884     
1885     // Get the subprogram die.
1886     DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1887     assert(SPDie && "Missing subprogram descriptor");
1888     
1889     // Add the function bounds.
1890     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1891                     DWLabel("func_begin", SubprogramCount));
1892     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1893                     DWLabel("func_end", SubprogramCount));
1894     MachineLocation Location(RI->getFrameRegister(*MF));
1895     AddAddress(SPDie, DW_AT_frame_base, Location);
1896
1897     ConstructScope(RootScope, 0, 0, SPDie, Unit);
1898   }
1899
1900   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1901   /// tools to recognize the object file contains Dwarf information.
1902   void EmitInitial() {
1903     // Check to see if we already emitted intial headers.
1904     if (didInitial) return;
1905     didInitial = true;
1906     
1907     // Dwarf sections base addresses.
1908     if (TAI->getDwarfRequiresFrameSection()) {
1909       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1910       EmitLabel("section_frame", 0);
1911     }
1912     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1913     EmitLabel("section_info", 0);
1914     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1915     EmitLabel("section_abbrev", 0);
1916     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1917     EmitLabel("section_aranges", 0);
1918     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1919     EmitLabel("section_macinfo", 0);
1920     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1921     EmitLabel("section_line", 0);
1922     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1923     EmitLabel("section_loc", 0);
1924     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1925     EmitLabel("section_pubnames", 0);
1926     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1927     EmitLabel("section_str", 0);
1928     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1929     EmitLabel("section_ranges", 0);
1930
1931     Asm->SwitchToTextSection(TAI->getTextSection());
1932     EmitLabel("text_begin", 0);
1933     Asm->SwitchToDataSection(TAI->getDataSection());
1934     EmitLabel("data_begin", 0);
1935
1936     // Emit common frame information.
1937     EmitInitialDebugFrame();
1938   }
1939
1940   /// EmitDIE - Recusively Emits a debug information entry.
1941   ///
1942   void EmitDIE(DIE *Die) const {
1943     // Get the abbreviation for this DIE.
1944     unsigned AbbrevNumber = Die->getAbbrevNumber();
1945     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1946     
1947     Asm->EOL("");
1948
1949     // Emit the code (index) for the abbreviation.
1950     Asm->EmitULEB128Bytes(AbbrevNumber);
1951     Asm->EOL(std::string("Abbrev [" +
1952              utostr(AbbrevNumber) +
1953              "] 0x" + utohexstr(Die->getOffset()) +
1954              ":0x" + utohexstr(Die->getSize()) + " " +
1955              TagString(Abbrev->getTag())));
1956     
1957     const std::vector<DIEValue *> &Values = Die->getValues();
1958     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1959     
1960     // Emit the DIE attribute values.
1961     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1962       unsigned Attr = AbbrevData[i].getAttribute();
1963       unsigned Form = AbbrevData[i].getForm();
1964       assert(Form && "Too many attributes for DIE (check abbreviation)");
1965       
1966       switch (Attr) {
1967       case DW_AT_sibling: {
1968         Asm->EmitInt32(Die->SiblingOffset());
1969         break;
1970       }
1971       default: {
1972         // Emit an attribute using the defined form.
1973         Values[i]->EmitValue(*this, Form);
1974         break;
1975       }
1976       }
1977       
1978       Asm->EOL(AttributeString(Attr));
1979     }
1980     
1981     // Emit the DIE children if any.
1982     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
1983       const std::vector<DIE *> &Children = Die->getChildren();
1984       
1985       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1986         EmitDIE(Children[j]);
1987       }
1988       
1989       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1990     }
1991   }
1992
1993   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1994   ///
1995   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1996     // Get the children.
1997     const std::vector<DIE *> &Children = Die->getChildren();
1998     
1999     // If not last sibling and has children then add sibling offset attribute.
2000     if (!Last && !Children.empty()) Die->AddSiblingOffset();
2001
2002     // Record the abbreviation.
2003     AssignAbbrevNumber(Die->getAbbrev());
2004    
2005     // Get the abbreviation for this DIE.
2006     unsigned AbbrevNumber = Die->getAbbrevNumber();
2007     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2008
2009     // Set DIE offset
2010     Die->setOffset(Offset);
2011     
2012     // Start the size with the size of abbreviation code.
2013     Offset += Asm->SizeULEB128(AbbrevNumber);
2014     
2015     const std::vector<DIEValue *> &Values = Die->getValues();
2016     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2017
2018     // Size the DIE attribute values.
2019     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2020       // Size attribute value.
2021       Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2022     }
2023     
2024     // Size the DIE children if any.
2025     if (!Children.empty()) {
2026       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2027              "Children flag not set");
2028       
2029       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2030         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2031       }
2032       
2033       // End of children marker.
2034       Offset += sizeof(int8_t);
2035     }
2036
2037     Die->setSize(Offset - Die->getOffset());
2038     return Offset;
2039   }
2040
2041   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2042   ///
2043   void SizeAndOffsets() {
2044     // Process base compile unit.
2045     CompileUnit *Unit = GetBaseCompileUnit();
2046     // Compute size of compile unit header
2047     unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2048                       sizeof(int16_t) + // DWARF version number
2049                       sizeof(int32_t) + // Offset Into Abbrev. Section
2050                       sizeof(int8_t);   // Pointer Size (in bytes)
2051     SizeAndOffsetDie(Unit->getDie(), Offset, true);
2052   }
2053
2054   /// EmitDebugInfo - Emit the debug info section.
2055   ///
2056   void EmitDebugInfo() const {
2057     // Start debug info section.
2058     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2059     
2060     CompileUnit *Unit = GetBaseCompileUnit();
2061     DIE *Die = Unit->getDie();
2062     // Emit the compile units header.
2063     EmitLabel("info_begin", Unit->getID());
2064     // Emit size of content not including length itself
2065     unsigned ContentSize = Die->getSize() +
2066                            sizeof(int16_t) + // DWARF version number
2067                            sizeof(int32_t) + // Offset Into Abbrev. Section
2068                            sizeof(int8_t) +  // Pointer Size (in bytes)
2069                            sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2070                            
2071     Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
2072     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2073     EmitDifference("abbrev_begin", 0, "section_abbrev", 0, true);
2074     Asm->EOL("Offset Into Abbrev. Section");
2075     Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Address Size (in bytes)");
2076   
2077     EmitDIE(Die);
2078     // FIXME - extra padding for gdb bug.
2079     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2080     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2081     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2082     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2083     EmitLabel("info_end", Unit->getID());
2084     
2085     Asm->EOL("");
2086   }
2087
2088   /// EmitAbbreviations - Emit the abbreviation section.
2089   ///
2090   void EmitAbbreviations() const {
2091     // Check to see if it is worth the effort.
2092     if (!Abbreviations.empty()) {
2093       // Start the debug abbrev section.
2094       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2095       
2096       EmitLabel("abbrev_begin", 0);
2097       
2098       // For each abbrevation.
2099       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2100         // Get abbreviation data
2101         const DIEAbbrev *Abbrev = Abbreviations[i];
2102         
2103         // Emit the abbrevations code (base 1 index.)
2104         Asm->EmitULEB128Bytes(Abbrev->getNumber());
2105         Asm->EOL("Abbreviation Code");
2106         
2107         // Emit the abbreviations data.
2108         Abbrev->Emit(*this);
2109     
2110         Asm->EOL("");
2111       }
2112       
2113       EmitLabel("abbrev_end", 0);
2114     
2115       Asm->EOL("");
2116     }
2117   }
2118
2119   /// EmitDebugLines - Emit source line information.
2120   ///
2121   void EmitDebugLines() const {
2122     // Minimum line delta, thus ranging from -10..(255-10).
2123     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2124     // Maximum line delta, thus ranging from -10..(255-10).
2125     const int MaxLineDelta = 255 + MinLineDelta;
2126
2127     // Start the dwarf line section.
2128     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2129     
2130     // Construct the section header.
2131     
2132     EmitDifference("line_end", 0, "line_begin", 0, true);
2133     Asm->EOL("Length of Source Line Info");
2134     EmitLabel("line_begin", 0);
2135     
2136     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2137     
2138     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2139     Asm->EOL("Prolog Length");
2140     EmitLabel("line_prolog_begin", 0);
2141     
2142     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2143
2144     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2145
2146     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2147     
2148     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2149
2150     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2151     
2152     // Line number standard opcode encodings argument count
2153     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2154     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2155     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2156     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2157     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2158     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2159     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2160     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2161     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2162
2163     const UniqueVector<std::string> &Directories = MMI->getDirectories();
2164     const UniqueVector<SourceFileInfo>
2165       &SourceFiles = MMI->getSourceFiles();
2166
2167     // Emit directories.
2168     for (unsigned DirectoryID = 1, NDID = Directories.size();
2169                   DirectoryID <= NDID; ++DirectoryID) {
2170       Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2171     }
2172     Asm->EmitInt8(0); Asm->EOL("End of directories");
2173     
2174     // Emit files.
2175     for (unsigned SourceID = 1, NSID = SourceFiles.size();
2176                  SourceID <= NSID; ++SourceID) {
2177       const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2178       Asm->EmitString(SourceFile.getName());
2179       Asm->EOL("Source");
2180       Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2181       Asm->EOL("Directory #");
2182       Asm->EmitULEB128Bytes(0);
2183       Asm->EOL("Mod date");
2184       Asm->EmitULEB128Bytes(0);
2185       Asm->EOL("File size");
2186     }
2187     Asm->EmitInt8(0); Asm->EOL("End of files");
2188     
2189     EmitLabel("line_prolog_end", 0);
2190     
2191     // A sequence for each text section.
2192     for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2193       // Isolate current sections line info.
2194       const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2195       
2196       Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2197
2198       // Dwarf assumes we start with first line of first source file.
2199       unsigned Source = 1;
2200       unsigned Line = 1;
2201       
2202       // Construct rows of the address, source, line, column matrix.
2203       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2204         const SourceLineInfo &LineInfo = LineInfos[i];
2205         unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2206         if (!LabelID) continue;
2207         
2208         unsigned SourceID = LineInfo.getSourceID();
2209         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2210         unsigned DirectoryID = SourceFile.getDirectoryID();
2211         Asm->EOL(Directories[DirectoryID]
2212           + SourceFile.getName()
2213           + ":"
2214           + utostr_32(LineInfo.getLine()));
2215
2216         // Define the line address.
2217         Asm->EmitInt8(0); Asm->EOL("Extended Op");
2218         Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2219         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2220         EmitReference("",  LabelID); Asm->EOL("Location label");
2221         
2222         // If change of source, then switch to the new source.
2223         if (Source != LineInfo.getSourceID()) {
2224           Source = LineInfo.getSourceID();
2225           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2226           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2227         }
2228         
2229         // If change of line.
2230         if (Line != LineInfo.getLine()) {
2231           // Determine offset.
2232           int Offset = LineInfo.getLine() - Line;
2233           int Delta = Offset - MinLineDelta;
2234           
2235           // Update line.
2236           Line = LineInfo.getLine();
2237           
2238           // If delta is small enough and in range...
2239           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2240             // ... then use fast opcode.
2241             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2242           } else {
2243             // ... otherwise use long hand.
2244             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2245             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2246             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2247           }
2248         } else {
2249           // Copy the previous row (different address or source)
2250           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2251         }
2252       }
2253
2254       // Define last address of section.
2255       Asm->EmitInt8(0); Asm->EOL("Extended Op");
2256       Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2257       Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2258       EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2259
2260       // Mark end of matrix.
2261       Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2262       Asm->EmitULEB128Bytes(1); Asm->EOL("");
2263       Asm->EmitInt8(1); Asm->EOL("");
2264     }
2265     
2266     EmitLabel("line_end", 0);
2267     
2268     Asm->EOL("");
2269   }
2270     
2271   /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
2272   ///
2273   void EmitInitialDebugFrame() {
2274     if (!TAI->getDwarfRequiresFrameSection())
2275       return;
2276
2277     int stackGrowth =
2278         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2279           TargetFrameInfo::StackGrowsUp ?
2280         TAI->getAddressSize() : -TAI->getAddressSize();
2281
2282     // Start the dwarf frame section.
2283     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2284
2285     EmitLabel("frame_common", 0);
2286     EmitDifference("frame_common_end", 0,
2287                    "frame_common_begin", 0, true);
2288     Asm->EOL("Length of Common Information Entry");
2289
2290     EmitLabel("frame_common_begin", 0);
2291     Asm->EmitInt32((int)DW_CIE_ID);
2292     Asm->EOL("CIE Identifier Tag");
2293     Asm->EmitInt8(DW_CIE_VERSION);
2294     Asm->EOL("CIE Version");
2295     Asm->EmitString("");
2296     Asm->EOL("CIE Augmentation");
2297     Asm->EmitULEB128Bytes(1);
2298     Asm->EOL("CIE Code Alignment Factor");
2299     Asm->EmitSLEB128Bytes(stackGrowth);
2300     Asm->EOL("CIE Data Alignment Factor");   
2301     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2302     Asm->EOL("CIE RA Column");
2303     
2304     std::vector<MachineMove> Moves;
2305     RI->getInitialFrameState(Moves);
2306     EmitFrameMoves(NULL, 0, Moves);
2307
2308     Asm->EmitAlignment(2);
2309     EmitLabel("frame_common_end", 0);
2310     
2311     Asm->EOL("");
2312   }
2313
2314   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2315   /// section.
2316   void EmitFunctionDebugFrame() {
2317     if (!TAI->getDwarfRequiresFrameSection())
2318       return;
2319        
2320     // Start the dwarf frame section.
2321     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2322     
2323     EmitDifference("frame_end", SubprogramCount,
2324                    "frame_begin", SubprogramCount, true);
2325     Asm->EOL("Length of Frame Information Entry");
2326     
2327     EmitLabel("frame_begin", SubprogramCount);
2328     
2329     EmitDifference("frame_common_begin", 0, "section_frame", 0, true);
2330     Asm->EOL("FDE CIE offset");
2331
2332     EmitReference("func_begin", SubprogramCount);
2333     Asm->EOL("FDE initial location");
2334     EmitDifference("func_end", SubprogramCount,
2335                    "func_begin", SubprogramCount);
2336     Asm->EOL("FDE address range");
2337     
2338     std::vector<MachineMove> &Moves = MMI->getFrameMoves();
2339     
2340     EmitFrameMoves("func_begin", SubprogramCount, Moves);
2341     
2342     Asm->EmitAlignment(2);
2343     EmitLabel("frame_end", SubprogramCount);
2344
2345     Asm->EOL("");
2346   }
2347
2348   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2349   ///
2350   void EmitDebugPubNames() {
2351     // Start the dwarf pubnames section.
2352     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2353       
2354     CompileUnit *Unit = GetBaseCompileUnit(); 
2355  
2356     EmitDifference("pubnames_end", Unit->getID(),
2357                    "pubnames_begin", Unit->getID(), true);
2358     Asm->EOL("Length of Public Names Info");
2359     
2360     EmitLabel("pubnames_begin", Unit->getID());
2361     
2362     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2363     
2364     EmitDifference("info_begin", Unit->getID(), "section_info", 0, true);
2365     Asm->EOL("Offset of Compilation Unit Info");
2366
2367     EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2368     Asm->EOL("Compilation Unit Length");
2369     
2370     std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2371     
2372     for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2373                                                 GE = Globals.end();
2374          GI != GE; ++GI) {
2375       const std::string &Name = GI->first;
2376       DIE * Entity = GI->second;
2377       
2378       Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2379       Asm->EmitString(Name); Asm->EOL("External Name");
2380     }
2381   
2382     Asm->EmitInt32(0); Asm->EOL("End Mark");
2383     EmitLabel("pubnames_end", Unit->getID());
2384   
2385     Asm->EOL("");
2386   }
2387
2388   /// EmitDebugStr - Emit visible names into a debug str section.
2389   ///
2390   void EmitDebugStr() {
2391     // Check to see if it is worth the effort.
2392     if (!StringPool.empty()) {
2393       // Start the dwarf str section.
2394       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2395       
2396       // For each of strings in the string pool.
2397       for (unsigned StringID = 1, N = StringPool.size();
2398            StringID <= N; ++StringID) {
2399         // Emit a label for reference from debug information entries.
2400         EmitLabel("string", StringID);
2401         // Emit the string itself.
2402         const std::string &String = StringPool[StringID];
2403         Asm->EmitString(String); Asm->EOL("");
2404       }
2405     
2406       Asm->EOL("");
2407     }
2408   }
2409
2410   /// EmitDebugLoc - Emit visible names into a debug loc section.
2411   ///
2412   void EmitDebugLoc() {
2413     // Start the dwarf loc section.
2414     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2415     
2416     Asm->EOL("");
2417   }
2418
2419   /// EmitDebugARanges - Emit visible names into a debug aranges section.
2420   ///
2421   void EmitDebugARanges() {
2422     // Start the dwarf aranges section.
2423     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2424     
2425     // FIXME - Mock up
2426   #if 0
2427     CompileUnit *Unit = GetBaseCompileUnit(); 
2428       
2429     // Don't include size of length
2430     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2431     
2432     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2433     
2434     EmitReference("info_begin", Unit->getID());
2435     Asm->EOL("Offset of Compilation Unit Info");
2436
2437     Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Size of Address");
2438
2439     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2440
2441     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
2442     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
2443
2444     // Range 1
2445     EmitReference("text_begin", 0); Asm->EOL("Address");
2446     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2447
2448     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2449     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2450     
2451     Asm->EOL("");
2452   #endif
2453   }
2454
2455   /// EmitDebugRanges - Emit visible names into a debug ranges section.
2456   ///
2457   void EmitDebugRanges() {
2458     // Start the dwarf ranges section.
2459     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2460     
2461     Asm->EOL("");
2462   }
2463
2464   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2465   ///
2466   void EmitDebugMacInfo() {
2467     // Start the dwarf macinfo section.
2468     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2469     
2470     Asm->EOL("");
2471   }
2472
2473   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2474   /// header file.
2475   void ConstructCompileUnitDIEs() {
2476     const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2477     
2478     for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2479       unsigned ID = MMI->RecordSource(CUW[i]);
2480       CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2481       CompileUnits.push_back(Unit);
2482     }
2483   }
2484
2485   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2486   /// global variables.
2487   void ConstructGlobalDIEs() {
2488     std::vector<GlobalVariableDesc *> GlobalVariables =
2489         MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2490     
2491     for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2492       GlobalVariableDesc *GVD = GlobalVariables[i];
2493       NewGlobalVariable(GVD);
2494     }
2495   }
2496
2497   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2498   /// subprograms.
2499   void ConstructSubprogramDIEs() {
2500     std::vector<SubprogramDesc *> Subprograms =
2501         MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2502     
2503     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2504       SubprogramDesc *SPD = Subprograms[i];
2505       NewSubprogram(SPD);
2506     }
2507   }
2508
2509 public:
2510   //===--------------------------------------------------------------------===//
2511   // Main entry points.
2512   //
2513   DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2514   : Dwarf(OS, A, T)
2515   , CompileUnits()
2516   , AbbreviationsSet(InitAbbreviationsSetSize)
2517   , Abbreviations()
2518   , ValuesSet(InitValuesSetSize)
2519   , Values()
2520   , StringPool()
2521   , DescToUnitMap()
2522   , SectionMap()
2523   , SectionSourceLines()
2524   {
2525   }
2526   virtual ~DwarfDebug() {
2527     for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2528       delete CompileUnits[i];
2529     for (unsigned j = 0, M = Values.size(); j < M; ++j)
2530       delete Values[j];
2531   }
2532
2533   /// SetModuleInfo - Set machine module information when it's known that pass
2534   /// manager has created it.  Set by the target AsmPrinter.
2535   void SetModuleInfo(MachineModuleInfo *mmi) {
2536     // Make sure initial declarations are made.
2537     if (!MMI && mmi->hasDebugInfo()) {
2538       MMI = mmi;
2539       shouldEmit = true;
2540       
2541       // Emit initial sections
2542       EmitInitial();
2543     
2544       // Create all the compile unit DIEs.
2545       ConstructCompileUnitDIEs();
2546       
2547       // Create DIEs for each of the externally visible global variables.
2548       ConstructGlobalDIEs();
2549
2550       // Create DIEs for each of the externally visible subprograms.
2551       ConstructSubprogramDIEs();
2552       
2553       // Prime section data.
2554       SectionMap.insert(TAI->getTextSection());
2555     }
2556   }
2557
2558   /// BeginModule - Emit all Dwarf sections that should come prior to the
2559   /// content.
2560   void BeginModule(Module *M) {
2561     this->M = M;
2562     
2563     if (!ShouldEmitDwarf()) return;
2564   }
2565
2566   /// EndModule - Emit all Dwarf sections that should come after the content.
2567   ///
2568   void EndModule() {
2569     if (!ShouldEmitDwarf()) return;
2570     
2571     // Standard sections final addresses.
2572     Asm->SwitchToTextSection(TAI->getTextSection());
2573     EmitLabel("text_end", 0);
2574     Asm->SwitchToDataSection(TAI->getDataSection());
2575     EmitLabel("data_end", 0);
2576     
2577     // End text sections.
2578     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2579       Asm->SwitchToTextSection(SectionMap[i].c_str());
2580       EmitLabel("section_end", i);
2581     }
2582     
2583     // Compute DIE offsets and sizes.
2584     SizeAndOffsets();
2585     
2586     // Emit all the DIEs into a debug info section
2587     EmitDebugInfo();
2588     
2589     // Corresponding abbreviations into a abbrev section.
2590     EmitAbbreviations();
2591     
2592     // Emit source line correspondence into a debug line section.
2593     EmitDebugLines();
2594     
2595     // Emit info into a debug pubnames section.
2596     EmitDebugPubNames();
2597     
2598     // Emit info into a debug str section.
2599     EmitDebugStr();
2600     
2601     // Emit info into a debug loc section.
2602     EmitDebugLoc();
2603     
2604     // Emit info into a debug aranges section.
2605     EmitDebugARanges();
2606     
2607     // Emit info into a debug ranges section.
2608     EmitDebugRanges();
2609     
2610     // Emit info into a debug macinfo section.
2611     EmitDebugMacInfo();
2612   }
2613
2614   /// BeginFunction - Gather pre-function debug information.  Assumes being 
2615   /// emitted immediately after the function entry point.
2616   void BeginFunction(MachineFunction *MF) {
2617     this->MF = MF;
2618     
2619     if (!ShouldEmitDwarf()) return;
2620
2621     // Begin accumulating function debug information.
2622     MMI->BeginFunction(MF);
2623     
2624     // Assumes in correct section after the entry point.
2625     EmitLabel("func_begin", ++SubprogramCount);
2626   }
2627   
2628   /// EndFunction - Gather and emit post-function debug information.
2629   ///
2630   void EndFunction() {
2631     if (!ShouldEmitDwarf()) return;
2632     
2633     // Define end label for subprogram.
2634     EmitLabel("func_end", SubprogramCount);
2635       
2636     // Get function line info.
2637     const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2638
2639     if (!LineInfos.empty()) {
2640       // Get section line info.
2641       unsigned ID = SectionMap.insert(Asm->CurrentSection);
2642       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2643       std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2644       // Append the function info to section info.
2645       SectionLineInfos.insert(SectionLineInfos.end(),
2646                               LineInfos.begin(), LineInfos.end());
2647     }
2648     
2649     // Construct scopes for subprogram.
2650     ConstructRootScope(MMI->getRootScope());
2651     
2652     // Emit function frame information.
2653     EmitFunctionDebugFrame();
2654   }
2655 };
2656
2657 //===----------------------------------------------------------------------===//
2658 /// DwarfException - Emits Dwarf exception handling directives. 
2659 ///
2660 class DwarfException : public Dwarf  {
2661
2662 private:
2663
2664   /// EmitInitial - Emit initial exception information.
2665   ///
2666   void EmitInitial() {
2667     int stackGrowth =
2668         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2669           TargetFrameInfo::StackGrowsUp ?
2670         TAI->getAddressSize() : -TAI->getAddressSize();
2671
2672     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2673     O << "EH_frame:\n";
2674     EmitLabel("section_eh_frame", 0);
2675
2676     EmitLabel("eh_frame_common", 0);
2677     EmitDifference("eh_frame_common_end", 0,
2678                    "eh_frame_common_begin", 0, true);
2679     Asm->EOL("Length of Common Information Entry");
2680
2681     EmitLabel("eh_frame_common_begin", 0);
2682     Asm->EmitInt32((int)0);
2683     Asm->EOL("CIE Identifier Tag");
2684     Asm->EmitInt8(DW_CIE_VERSION);
2685     Asm->EOL("CIE Version");
2686     Asm->EmitString("zR");
2687     Asm->EOL("CIE Augmentation");
2688     Asm->EmitULEB128Bytes(1);
2689     Asm->EOL("CIE Code Alignment Factor");
2690     Asm->EmitSLEB128Bytes(stackGrowth);
2691     Asm->EOL("CIE Data Alignment Factor");   
2692     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2693     Asm->EOL("CIE RA Column");
2694     Asm->EmitULEB128Bytes(1);
2695     Asm->EOL("Augmentation Size");
2696     Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2697     Asm->EOL("FDE Encoding (pcrel)");
2698     
2699     std::vector<MachineMove> Moves;
2700     RI->getInitialFrameState(Moves);
2701     EmitFrameMoves(NULL, 0, Moves);
2702
2703     Asm->EmitAlignment(2);
2704     EmitLabel("eh_frame_common_end", 0);
2705     
2706     Asm->EOL("");
2707     
2708   }
2709   
2710   
2711   /// EmitEHFrame - Emit initial exception information.
2712   ///
2713   void EmitEHFrame() {
2714     EmitDifference("eh_frame_end", SubprogramCount,
2715                    "eh_frame_begin", SubprogramCount, true);
2716     Asm->EOL("Length of Frame Information Entry");
2717     
2718     EmitLabel("eh_frame_begin", SubprogramCount);
2719     
2720     EmitDifference("eh_frame_begin", SubprogramCount,
2721                    "section_eh_frame", 0, true);
2722     Asm->EOL("FDE CIE offset");
2723
2724     EmitReference("eh_func_begin", SubprogramCount, true);
2725     Asm->EOL("FDE initial location");
2726     EmitDifference("eh_func_end", SubprogramCount,
2727                    "eh_func_begin", SubprogramCount);
2728     Asm->EOL("FDE address range");
2729     
2730     Asm->EmitULEB128Bytes(0);
2731     Asm->EOL("Augmentation size");
2732     
2733     std::vector<MachineMove> &Moves = MMI->getFrameMoves();
2734     
2735     EmitFrameMoves("eh_func_begin", SubprogramCount, Moves);
2736     
2737     Asm->EmitAlignment(2);
2738     EmitLabel("eh_frame_end", SubprogramCount);
2739   }
2740
2741 public:
2742   //===--------------------------------------------------------------------===//
2743   // Main entry points.
2744   //
2745   DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2746   : Dwarf(OS, A, T)
2747   {}
2748   
2749   virtual ~DwarfException() {}
2750
2751   /// SetModuleInfo - Set machine module information when it's known that pass
2752   /// manager has created it.  Set by the target AsmPrinter.
2753   void SetModuleInfo(MachineModuleInfo *mmi) {
2754 #if 1  // Not ready for prime time.
2755     return;
2756 #endif
2757     // Make sure initial declarations are made.
2758     if (!MMI && ExceptionHandling && TAI->getSupportsExceptionHandling()) {
2759       MMI = mmi;
2760       shouldEmit = true;
2761       
2762       EmitInitial();
2763     }
2764   }
2765
2766   /// BeginModule - Emit all exception information that should come prior to the
2767   /// content.
2768   void BeginModule(Module *M) {
2769     this->M = M;
2770     
2771     if (!ShouldEmitDwarf()) return;
2772   }
2773
2774   /// EndModule - Emit all exception information that should come after the
2775   /// content.
2776   void EndModule() {
2777     if (!ShouldEmitDwarf()) return;
2778   }
2779
2780   /// BeginFunction - Gather pre-function exception information.  Assumes being 
2781   /// emitted immediately after the function entry point.
2782   void BeginFunction(MachineFunction *MF) {
2783     this->MF = MF;
2784     
2785     if (!ShouldEmitDwarf()) return;
2786     
2787     // Assumes in correct section after the entry point.
2788     EmitLabel("eh_func_begin", ++SubprogramCount);
2789   }
2790
2791   /// EndFunction - Gather and emit post-function exception information.
2792   ///
2793   void EndFunction() {
2794     if (!ShouldEmitDwarf()) return;
2795
2796     EmitLabel("eh_func_end", SubprogramCount);
2797
2798     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2799
2800     if (const char *GlobalDirective = TAI->getGlobalDirective())
2801       O << GlobalDirective << getAsm()->CurrentFnName << ".eh\n";
2802      
2803     if (0) {
2804       O << getAsm()->CurrentFnName << ".eh = 0\n";
2805     } else {
2806       O << getAsm()->CurrentFnName << ".eh:\n";
2807       EmitEHFrame();
2808     }
2809     
2810     if (const char *UsedDirective = TAI->getUsedDirective())
2811       O << UsedDirective << getAsm()->CurrentFnName << ".eh\n\n";
2812   }
2813 };
2814
2815 } // End of namespace llvm
2816
2817 //===----------------------------------------------------------------------===//
2818
2819 /// Emit - Print the abbreviation using the specified Dwarf writer.
2820 ///
2821 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
2822   // Emit its Dwarf tag type.
2823   DD.getAsm()->EmitULEB128Bytes(Tag);
2824   DD.getAsm()->EOL(TagString(Tag));
2825   
2826   // Emit whether it has children DIEs.
2827   DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
2828   DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
2829   
2830   // For each attribute description.
2831   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
2832     const DIEAbbrevData &AttrData = Data[i];
2833     
2834     // Emit attribute type.
2835     DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
2836     DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
2837     
2838     // Emit form type.
2839     DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
2840     DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
2841   }
2842
2843   // Mark end of abbreviation.
2844   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
2845   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
2846 }
2847
2848 #ifndef NDEBUG
2849 void DIEAbbrev::print(std::ostream &O) {
2850   O << "Abbreviation @"
2851     << std::hex << (intptr_t)this << std::dec
2852     << "  "
2853     << TagString(Tag)
2854     << " "
2855     << ChildrenString(ChildrenFlag)
2856     << "\n";
2857   
2858   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
2859     O << "  "
2860       << AttributeString(Data[i].getAttribute())
2861       << "  "
2862       << FormEncodingString(Data[i].getForm())
2863       << "\n";
2864   }
2865 }
2866 void DIEAbbrev::dump() { print(cerr); }
2867 #endif
2868
2869 //===----------------------------------------------------------------------===//
2870
2871 #ifndef NDEBUG
2872 void DIEValue::dump() {
2873   print(cerr);
2874 }
2875 #endif
2876
2877 //===----------------------------------------------------------------------===//
2878
2879 /// EmitValue - Emit integer of appropriate size.
2880 ///
2881 void DIEInteger::EmitValue(const DwarfDebug &DD, unsigned Form) const {
2882   switch (Form) {
2883   case DW_FORM_flag:  // Fall thru
2884   case DW_FORM_ref1:  // Fall thru
2885   case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer);         break;
2886   case DW_FORM_ref2:  // Fall thru
2887   case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer);        break;
2888   case DW_FORM_ref4:  // Fall thru
2889   case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer);        break;
2890   case DW_FORM_ref8:  // Fall thru
2891   case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer);        break;
2892   case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
2893   case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
2894   default: assert(0 && "DIE Value form not supported yet");   break;
2895   }
2896 }
2897
2898 /// SizeOf - Determine size of integer value in bytes.
2899 ///
2900 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
2901   switch (Form) {
2902   case DW_FORM_flag:  // Fall thru
2903   case DW_FORM_ref1:  // Fall thru
2904   case DW_FORM_data1: return sizeof(int8_t);
2905   case DW_FORM_ref2:  // Fall thru
2906   case DW_FORM_data2: return sizeof(int16_t);
2907   case DW_FORM_ref4:  // Fall thru
2908   case DW_FORM_data4: return sizeof(int32_t);
2909   case DW_FORM_ref8:  // Fall thru
2910   case DW_FORM_data8: return sizeof(int64_t);
2911   case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
2912   case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
2913   default: assert(0 && "DIE Value form not supported yet"); break;
2914   }
2915   return 0;
2916 }
2917
2918 //===----------------------------------------------------------------------===//
2919
2920 /// EmitValue - Emit string value.
2921 ///
2922 void DIEString::EmitValue(const DwarfDebug &DD, unsigned Form) const {
2923   DD.getAsm()->EmitString(String);
2924 }
2925
2926 //===----------------------------------------------------------------------===//
2927
2928 /// EmitValue - Emit label value.
2929 ///
2930 void DIEDwarfLabel::EmitValue(const DwarfDebug &DD, unsigned Form) const {
2931   DD.EmitReference(Label);
2932 }
2933
2934 /// SizeOf - Determine size of label value in bytes.
2935 ///
2936 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
2937   return DD.getTargetAsmInfo()->getAddressSize();
2938 }
2939
2940 //===----------------------------------------------------------------------===//
2941
2942 /// EmitValue - Emit label value.
2943 ///
2944 void DIEObjectLabel::EmitValue(const DwarfDebug &DD, unsigned Form) const {
2945   DD.EmitReference(Label);
2946 }
2947
2948 /// SizeOf - Determine size of label value in bytes.
2949 ///
2950 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
2951   return DD.getTargetAsmInfo()->getAddressSize();
2952 }
2953     
2954 //===----------------------------------------------------------------------===//
2955
2956 /// EmitValue - Emit delta value.
2957 ///
2958 void DIEDelta::EmitValue(const DwarfDebug &DD, unsigned Form) const {
2959   bool IsSmall = Form == DW_FORM_data4;
2960   DD.EmitDifference(LabelHi, LabelLo, IsSmall);
2961 }
2962
2963 /// SizeOf - Determine size of delta value in bytes.
2964 ///
2965 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
2966   if (Form == DW_FORM_data4) return 4;
2967   return DD.getTargetAsmInfo()->getAddressSize();
2968 }
2969
2970 //===----------------------------------------------------------------------===//
2971
2972 /// EmitValue - Emit debug information entry offset.
2973 ///
2974 void DIEntry::EmitValue(const DwarfDebug &DD, unsigned Form) const {
2975   DD.getAsm()->EmitInt32(Entry->getOffset());
2976 }
2977     
2978 //===----------------------------------------------------------------------===//
2979
2980 /// ComputeSize - calculate the size of the block.
2981 ///
2982 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
2983   if (!Size) {
2984     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2985     
2986     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2987       Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
2988     }
2989   }
2990   return Size;
2991 }
2992
2993 /// EmitValue - Emit block data.
2994 ///
2995 void DIEBlock::EmitValue(const DwarfDebug &DD, unsigned Form) const {
2996   switch (Form) {
2997   case DW_FORM_block1: DD.getAsm()->EmitInt8(Size);         break;
2998   case DW_FORM_block2: DD.getAsm()->EmitInt16(Size);        break;
2999   case DW_FORM_block4: DD.getAsm()->EmitInt32(Size);        break;
3000   case DW_FORM_block:  DD.getAsm()->EmitULEB128Bytes(Size); break;
3001   default: assert(0 && "Improper form for block");          break;
3002   }
3003   
3004   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3005
3006   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3007     DD.getAsm()->EOL("");
3008     Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3009   }
3010 }
3011
3012 /// SizeOf - Determine size of block data in bytes.
3013 ///
3014 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3015   switch (Form) {
3016   case DW_FORM_block1: return Size + sizeof(int8_t);
3017   case DW_FORM_block2: return Size + sizeof(int16_t);
3018   case DW_FORM_block4: return Size + sizeof(int32_t);
3019   case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3020   default: assert(0 && "Improper form for block"); break;
3021   }
3022   return 0;
3023 }
3024
3025 //===----------------------------------------------------------------------===//
3026 /// DIE Implementation
3027
3028 DIE::~DIE() {
3029   for (unsigned i = 0, N = Children.size(); i < N; ++i)
3030     delete Children[i];
3031 }
3032   
3033 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3034 ///
3035 void DIE::AddSiblingOffset() {
3036   DIEInteger *DI = new DIEInteger(0);
3037   Values.insert(Values.begin(), DI);
3038   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3039 }
3040
3041 /// Profile - Used to gather unique data for the value folding set.
3042 ///
3043 void DIE::Profile(FoldingSetNodeID &ID) {
3044   Abbrev.Profile(ID);
3045   
3046   for (unsigned i = 0, N = Children.size(); i < N; ++i)
3047     ID.AddPointer(Children[i]);
3048
3049   for (unsigned j = 0, M = Values.size(); j < M; ++j)
3050     ID.AddPointer(Values[j]);
3051 }
3052
3053 #ifndef NDEBUG
3054 void DIE::print(std::ostream &O, unsigned IncIndent) {
3055   static unsigned IndentCount = 0;
3056   IndentCount += IncIndent;
3057   const std::string Indent(IndentCount, ' ');
3058   bool isBlock = Abbrev.getTag() == 0;
3059   
3060   if (!isBlock) {
3061     O << Indent
3062       << "Die: "
3063       << "0x" << std::hex << (intptr_t)this << std::dec
3064       << ", Offset: " << Offset
3065       << ", Size: " << Size
3066       << "\n"; 
3067     
3068     O << Indent
3069       << TagString(Abbrev.getTag())
3070       << " "
3071       << ChildrenString(Abbrev.getChildrenFlag());
3072   } else {
3073     O << "Size: " << Size;
3074   }
3075   O << "\n";
3076
3077   const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3078   
3079   IndentCount += 2;
3080   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3081     O << Indent;
3082     if (!isBlock) {
3083       O << AttributeString(Data[i].getAttribute());
3084     } else {
3085       O << "Blk[" << i << "]";
3086     }
3087     O <<  "  "
3088       << FormEncodingString(Data[i].getForm())
3089       << " ";
3090     Values[i]->print(O);
3091     O << "\n";
3092   }
3093   IndentCount -= 2;
3094
3095   for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3096     Children[j]->print(O, 4);
3097   }
3098   
3099   if (!isBlock) O << "\n";
3100   IndentCount -= IncIndent;
3101 }
3102
3103 void DIE::dump() {
3104   print(cerr);
3105 }
3106 #endif
3107
3108 //===----------------------------------------------------------------------===//
3109 /// DwarfWriter Implementation
3110 ///
3111
3112 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3113                          const TargetAsmInfo *T) {
3114   DE = new DwarfException(OS, A, T);
3115   DD = new DwarfDebug(OS, A, T);
3116 }
3117
3118 DwarfWriter::~DwarfWriter() {
3119   delete DE;
3120   delete DD;
3121 }
3122
3123 /// SetModuleInfo - Set machine module info when it's known that pass manager
3124 /// has created it.  Set by the target AsmPrinter.
3125 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3126   DD->SetModuleInfo(MMI);
3127   DE->SetModuleInfo(MMI);
3128 }
3129
3130 /// BeginModule - Emit all Dwarf sections that should come prior to the
3131 /// content.
3132 void DwarfWriter::BeginModule(Module *M) {
3133   DE->BeginModule(M);
3134   DD->BeginModule(M);
3135 }
3136
3137 /// EndModule - Emit all Dwarf sections that should come after the content.
3138 ///
3139 void DwarfWriter::EndModule() {
3140   DE->EndModule();
3141   DD->EndModule();
3142 }
3143
3144 /// BeginFunction - Gather pre-function debug information.  Assumes being 
3145 /// emitted immediately after the function entry point.
3146 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3147   DE->BeginFunction(MF);
3148   DD->BeginFunction(MF);
3149 }
3150
3151 /// EndFunction - Gather and emit post-function debug information.
3152 ///
3153 void DwarfWriter::EndFunction() {
3154   DD->EndFunction();
3155   DE->EndFunction();
3156   
3157   if (MachineModuleInfo *MMI = DD->getMMI()) {
3158     // Clear function debug information.
3159     MMI->EndFunction();
3160   }
3161 }