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