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