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