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