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