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