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