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