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