Foundation for call frame information.
[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/StringExtras.h"
17 #include "llvm/Module.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/MachineDebugInfo.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineLocation.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Mangler.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28
29 #include <iostream>
30
31 using namespace llvm;
32 using namespace llvm::dwarf;
33
34 static cl::opt<bool>
35 DwarfVerbose("dwarf-verbose", cl::Hidden,
36                                 cl::desc("Add comments to Dwarf directives."));
37
38 namespace llvm {
39
40 //===----------------------------------------------------------------------===//
41 // Forward declarations.
42 //
43 class DIE;
44
45 //===----------------------------------------------------------------------===//
46 // CompileUnit - This dwarf writer support class manages information associate
47 // with a source file.
48 class CompileUnit {
49 private:
50   CompileUnitDesc *Desc;                // Compile unit debug descriptor.
51   unsigned ID;                          // File ID for source.
52   DIE *Die;                             // Compile unit debug information entry.
53   std::map<std::string, DIE *> Globals; // A map of globally visible named
54                                         // entities for this unit.
55   std::map<DebugInfoDesc *, DIE *> DescToDieMap;
56                                         // Tracks the mapping of unit level
57                                         // debug informaton descriptors to debug
58                                         // information entries.
59
60 public:
61   CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
62   : Desc(CUD)
63   , ID(I)
64   , Die(D)
65   , Globals()
66   , DescToDieMap()
67   {}
68   
69   ~CompileUnit();
70   
71   // Accessors.
72   CompileUnitDesc *getDesc() const { return Desc; }
73   unsigned getID()           const { return ID; }
74   DIE* getDie()              const { return Die; }
75   std::map<std::string, DIE *> &getGlobals() { return Globals; }
76   
77   /// hasContent - Return true if this compile unit has something to write out.
78   ///
79   bool hasContent() const;
80   
81   /// AddGlobal - Add a new global entity to the compile unit.
82   ///
83   void AddGlobal(const std::string &Name, DIE *Die);
84   
85   /// getDieMapSlotFor - Returns the debug information entry map slot for the
86   /// specified debug descriptor.
87   DIE *&getDieMapSlotFor(DebugInfoDesc *DD) {
88     return DescToDieMap[DD];
89   }
90 };
91
92 //===----------------------------------------------------------------------===//
93 // DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
94 // Dwarf abbreviation.
95 class DIEAbbrevData {
96 private:
97   unsigned Attribute;                 // Dwarf attribute code.
98   unsigned Form;                      // Dwarf form code.
99   
100 public:
101   DIEAbbrevData(unsigned A, unsigned F)
102   : Attribute(A)
103   , Form(F)
104   {}
105   
106   // Accessors.
107   unsigned getAttribute() const { return Attribute; }
108   unsigned getForm()      const { return Form; }
109   
110   /// operator== - Used by DIEAbbrev to locate entry.
111   ///
112   bool operator==(const DIEAbbrevData &DAD) const {
113     return Attribute == DAD.Attribute && Form == DAD.Form;
114   }
115
116   /// operator!= - Used by DIEAbbrev to locate entry.
117   ///
118   bool operator!=(const DIEAbbrevData &DAD) const {
119     return Attribute != DAD.Attribute || Form != DAD.Form;
120   }
121   
122   /// operator< - Used by DIEAbbrev to locate entry.
123   ///
124   bool operator<(const DIEAbbrevData &DAD) const {
125     return Attribute < DAD.Attribute ||
126           (Attribute == DAD.Attribute && Form < DAD.Form);
127   }
128 };
129
130 //===----------------------------------------------------------------------===//
131 // DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
132 // information object.
133 class DIEAbbrev {
134 private:
135   unsigned Tag;                       // Dwarf tag code.
136   unsigned ChildrenFlag;              // Dwarf children flag.
137   std::vector<DIEAbbrevData> Data;    // Raw data bytes for abbreviation.
138
139 public:
140
141   DIEAbbrev(unsigned T, unsigned C)
142   : Tag(T)
143   , ChildrenFlag(C)
144   , Data()
145   {}
146   ~DIEAbbrev() {}
147   
148   // Accessors.
149   unsigned getTag()                           const { return Tag; }
150   unsigned getChildrenFlag()                  const { return ChildrenFlag; }
151   const std::vector<DIEAbbrevData> &getData() const { return Data; }
152   void setChildrenFlag(unsigned CF)                 { ChildrenFlag = CF; }
153
154   /// operator== - Used by UniqueVector to locate entry.
155   ///
156   bool operator==(const DIEAbbrev &DA) const;
157
158   /// operator< - Used by UniqueVector to locate entry.
159   ///
160   bool operator<(const DIEAbbrev &DA) const;
161
162   /// AddAttribute - Adds another set of attribute information to the
163   /// abbreviation.
164   void AddAttribute(unsigned Attribute, unsigned Form) {
165     Data.push_back(DIEAbbrevData(Attribute, Form));
166   }
167   
168   /// AddFirstAttribute - Adds a set of attribute information to the front
169   /// of the abbreviation.
170   void AddFirstAttribute(unsigned Attribute, unsigned Form) {
171     Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
172   }
173   
174   /// Emit - Print the abbreviation using the specified Dwarf writer.
175   ///
176   void Emit(const DwarfWriter &DW) const; 
177       
178 #ifndef NDEBUG
179   void print(std::ostream &O);
180   void dump();
181 #endif
182 };
183
184 //===----------------------------------------------------------------------===//
185 // DIEValue - A debug information entry value.
186 //
187 class DIEValue {
188 public:
189   enum {
190     isInteger,
191     isString,
192     isLabel,
193     isAsIsLabel,
194     isDelta,
195     isEntry,
196     isBlock
197   };
198   
199   unsigned Type;                      // Type of the value
200   
201   DIEValue(unsigned T) : Type(T) {}
202   virtual ~DIEValue() {}
203   
204   // Implement isa/cast/dyncast.
205   static bool classof(const DIEValue *) { return true; }
206   
207   /// EmitValue - Emit value via the Dwarf writer.
208   ///
209   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const = 0;
210   
211   /// SizeOf - Return the size of a value in bytes.
212   ///
213   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const = 0;
214 };
215
216 //===----------------------------------------------------------------------===//
217 // DWInteger - An integer value DIE.
218 // 
219 class DIEInteger : public DIEValue {
220 private:
221   uint64_t Integer;
222   
223 public:
224   DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
225
226   // Implement isa/cast/dyncast.
227   static bool classof(const DIEInteger *) { return true; }
228   static bool classof(const DIEValue *I)  { return I->Type == isInteger; }
229   
230   /// BestForm - Choose the best form for integer.
231   ///
232   unsigned BestForm(bool IsSigned);
233
234   /// EmitValue - Emit integer of appropriate size.
235   ///
236   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
237   
238   /// SizeOf - Determine size of integer value in bytes.
239   ///
240   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
241 };
242
243 //===----------------------------------------------------------------------===//
244 // DIEString - A string value DIE.
245 // 
246 struct DIEString : public DIEValue {
247   const std::string String;
248   
249   DIEString(const std::string &S) : DIEValue(isString), String(S) {}
250
251   // Implement isa/cast/dyncast.
252   static bool classof(const DIEString *) { return true; }
253   static bool classof(const DIEValue *S) { return S->Type == isString; }
254   
255   /// EmitValue - Emit string value.
256   ///
257   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
258   
259   /// SizeOf - Determine size of string value in bytes.
260   ///
261   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
262 };
263
264 //===----------------------------------------------------------------------===//
265 // DIEDwarfLabel - A Dwarf internal label expression DIE.
266 //
267 struct DIEDwarfLabel : public DIEValue {
268   const DWLabel Label;
269   
270   DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
271
272   // Implement isa/cast/dyncast.
273   static bool classof(const DIEDwarfLabel *)  { return true; }
274   static bool classof(const DIEValue *L) { return L->Type == isLabel; }
275   
276   /// EmitValue - Emit label value.
277   ///
278   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
279   
280   /// SizeOf - Determine size of label value in bytes.
281   ///
282   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
283 };
284
285
286 //===----------------------------------------------------------------------===//
287 // DIEObjectLabel - A label to an object in code or data.
288 //
289 struct DIEObjectLabel : public DIEValue {
290   const std::string Label;
291   
292   DIEObjectLabel(const std::string &L) : DIEValue(isAsIsLabel), Label(L) {}
293
294   // Implement isa/cast/dyncast.
295   static bool classof(const DIEObjectLabel *) { return true; }
296   static bool classof(const DIEValue *L)    { return L->Type == isAsIsLabel; }
297   
298   /// EmitValue - Emit label value.
299   ///
300   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
301   
302   /// SizeOf - Determine size of label value in bytes.
303   ///
304   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
305 };
306
307 //===----------------------------------------------------------------------===//
308 // DIEDelta - A simple label difference DIE.
309 // 
310 struct DIEDelta : public DIEValue {
311   const DWLabel LabelHi;
312   const DWLabel LabelLo;
313   
314   DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
315   : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
316
317   // Implement isa/cast/dyncast.
318   static bool classof(const DIEDelta *)  { return true; }
319   static bool classof(const DIEValue *D) { return D->Type == isDelta; }
320   
321   /// EmitValue - Emit delta value.
322   ///
323   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
324   
325   /// SizeOf - Determine size of delta value in bytes.
326   ///
327   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
328 };
329
330 //===----------------------------------------------------------------------===//
331 // DIEntry - A pointer to a debug information entry.
332 // 
333 struct DIEntry : public DIEValue {
334   DIE *Entry;
335   
336   DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
337
338   // Implement isa/cast/dyncast.
339   static bool classof(const DIEntry *)   { return true; }
340   static bool classof(const DIEValue *E) { return E->Type == isEntry; }
341   
342   /// EmitValue - Emit debug information entry offset.
343   ///
344   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
345   
346   /// SizeOf - Determine size of debug information entry in bytes.
347   ///
348   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
349 };
350
351 //===----------------------------------------------------------------------===//
352 // DIEBlock - A block of values.  Primarily used for location expressions.
353 //
354 struct DIEBlock : public DIEValue {
355   unsigned Size;                        // Size in bytes excluding size header.
356   std::vector<unsigned> Forms;          // Data forms.
357   std::vector<DIEValue *> Values;       // Block values.
358   
359   DIEBlock()
360   : DIEValue(isBlock)
361   , Size(0)
362   , Forms()
363   , Values()
364   {}
365   ~DIEBlock();
366
367   // Implement isa/cast/dyncast.
368   static bool classof(const DIEBlock *)  { return true; }
369   static bool classof(const DIEValue *E) { return E->Type == isBlock; }
370   
371   /// ComputeSize - calculate the size of the block.
372   ///
373   unsigned ComputeSize(DwarfWriter &DW);
374   
375   /// BestForm - Choose the best form for data.
376   ///
377   unsigned BestForm();
378
379   /// EmitValue - Emit block data.
380   ///
381   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
382   
383   /// SizeOf - Determine size of block data in bytes.
384   ///
385   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
386
387   /// AddUInt - Add an unsigned integer value.
388   ///
389   void AddUInt(unsigned Form, uint64_t Integer);
390
391   /// AddSInt - Add an signed integer value.
392   ///
393   void AddSInt(unsigned Form, int64_t Integer);
394       
395   /// AddString - Add a std::string value.
396   ///
397   void AddString(unsigned Form, const std::string &String);
398       
399   /// AddLabel - Add a Dwarf label value.
400   ///
401   void AddLabel(unsigned Form, const DWLabel &Label);
402       
403   /// AddObjectLabel - Add a non-Dwarf label value.
404   ///
405   void AddObjectLabel(unsigned Form, const std::string &Label);
406       
407   /// AddDelta - Add a label delta value.
408   ///
409   void AddDelta(unsigned Form, const DWLabel &Hi, const DWLabel &Lo);
410       
411   /// AddDIEntry - Add a DIE value.
412   ///
413   void AddDIEntry(unsigned Form, DIE *Entry);
414
415 };
416
417 //===----------------------------------------------------------------------===//
418 // DIE - A structured debug information entry.  Has an abbreviation which
419 // describes it's organization.
420 class DIE {
421 private:
422   DIEAbbrev *Abbrev;                    // Temporary buffer for abbreviation.
423   unsigned AbbrevID;                    // Decribing abbreviation ID.
424   unsigned Offset;                      // Offset in debug info section.
425   unsigned Size;                        // Size of instance + children.
426   std::vector<DIE *> Children;          // Children DIEs.
427   std::vector<DIEValue *> Values;       // Attributes values.
428   
429 public:
430   DIE(unsigned Tag);
431   ~DIE();
432   
433   // Accessors.
434   unsigned   getAbbrevID()                   const { return AbbrevID; }
435   unsigned   getOffset()                     const { return Offset; }
436   unsigned   getSize()                       const { return Size; }
437   const std::vector<DIE *> &getChildren()    const { return Children; }
438   const std::vector<DIEValue *> &getValues() const { return Values; }
439   void setOffset(unsigned O)                 { Offset = O; }
440   void setSize(unsigned S)                   { Size = S; }
441   
442   /// SiblingOffset - Return the offset of the debug information entry's
443   /// sibling.
444   unsigned SiblingOffset() const { return Offset + Size; }
445   
446   /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
447   ///
448   void AddSiblingOffset();
449
450   /// AddUInt - Add an unsigned integer attribute data and value.
451   ///
452   void AddUInt(unsigned Attribute, unsigned Form, uint64_t Integer);
453
454   /// AddSInt - Add an signed integer attribute data and value.
455   ///
456   void AddSInt(unsigned Attribute, unsigned Form, int64_t Integer);
457       
458   /// AddString - Add a std::string attribute data and value.
459   ///
460   void AddString(unsigned Attribute, unsigned Form,
461                  const std::string &String);
462       
463   /// AddLabel - Add a Dwarf label attribute data and value.
464   ///
465   void AddLabel(unsigned Attribute, unsigned Form, const DWLabel &Label);
466       
467   /// AddObjectLabel - Add a non-Dwarf label attribute data and value.
468   ///
469   void AddObjectLabel(unsigned Attribute, unsigned Form,
470                       const std::string &Label);
471       
472   /// AddDelta - Add a label delta attribute data and value.
473   ///
474   void AddDelta(unsigned Attribute, unsigned Form,
475                 const DWLabel &Hi, const DWLabel &Lo);
476       
477   /// AddDIEntry - Add a DIE attribute data and value.
478   ///
479   void AddDIEntry(unsigned Attribute, unsigned Form, DIE *Entry);
480
481   /// AddBlock - Add block data.
482   ///
483   void AddBlock(unsigned Attribute, unsigned Form, DIEBlock *Block);
484
485   /// Complete - Indicate that all attributes have been added and
486   /// ready to get an abbreviation ID.
487   ///
488   void Complete(DwarfWriter &DW);
489   
490   /// AddChild - Add a child to the DIE.
491   void AddChild(DIE *Child);
492 };
493
494 } // End of namespace llvm
495
496 //===----------------------------------------------------------------------===//
497
498 CompileUnit::~CompileUnit() {
499   delete Die;
500 }
501
502 /// hasContent - Return true if this compile unit has something to write out.
503 ///
504 bool CompileUnit::hasContent() const {
505   return !Die->getChildren().empty();
506 }
507
508 /// AddGlobal - Add a new global entity to the compile unit.
509 ///
510 void CompileUnit::AddGlobal(const std::string &Name, DIE *Die) {
511   Globals[Name] = Die;
512 }
513
514 //===----------------------------------------------------------------------===//
515
516 /// operator== - Used by UniqueVector to locate entry.
517 ///
518 bool DIEAbbrev::operator==(const DIEAbbrev &DA) const {
519   if (Tag != DA.Tag) return false;
520   if (ChildrenFlag != DA.ChildrenFlag) return false;
521   if (Data.size() != DA.Data.size()) return false;
522   
523   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
524     if (Data[i] != DA.Data[i]) return false;
525   }
526   
527   return true;
528 }
529
530 /// operator< - Used by UniqueVector to locate entry.
531 ///
532 bool DIEAbbrev::operator<(const DIEAbbrev &DA) const {
533   if (Tag != DA.Tag) return Tag < DA.Tag;
534   if (ChildrenFlag != DA.ChildrenFlag) return ChildrenFlag < DA.ChildrenFlag;
535   if (Data.size() != DA.Data.size()) return Data.size() < DA.Data.size();
536   
537   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
538     if (Data[i] != DA.Data[i]) return Data[i] < DA.Data[i];
539   }
540   
541   return false;
542 }
543     
544 /// Emit - Print the abbreviation using the specified Dwarf writer.
545 ///
546 void DIEAbbrev::Emit(const DwarfWriter &DW) const {
547   // Emit its Dwarf tag type.
548   DW.EmitULEB128Bytes(Tag);
549   DW.EOL(TagString(Tag));
550   
551   // Emit whether it has children DIEs.
552   DW.EmitULEB128Bytes(ChildrenFlag);
553   DW.EOL(ChildrenString(ChildrenFlag));
554   
555   // For each attribute description.
556   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
557     const DIEAbbrevData &AttrData = Data[i];
558     
559     // Emit attribute type.
560     DW.EmitULEB128Bytes(AttrData.getAttribute());
561     DW.EOL(AttributeString(AttrData.getAttribute()));
562     
563     // Emit form type.
564     DW.EmitULEB128Bytes(AttrData.getForm());
565     DW.EOL(FormEncodingString(AttrData.getForm()));
566   }
567
568   // Mark end of abbreviation.
569   DW.EmitULEB128Bytes(0); DW.EOL("EOM(1)");
570   DW.EmitULEB128Bytes(0); DW.EOL("EOM(2)");
571 }
572
573 #ifndef NDEBUG
574   void DIEAbbrev::print(std::ostream &O) {
575     O << "Abbreviation @"
576       << std::hex << (intptr_t)this << std::dec
577       << "  "
578       << TagString(Tag)
579       << " "
580       << ChildrenString(ChildrenFlag)
581       << "\n";
582     
583     for (unsigned i = 0, N = Data.size(); i < N; ++i) {
584       O << "  "
585         << AttributeString(Data[i].getAttribute())
586         << "  "
587         << FormEncodingString(Data[i].getForm())
588         << "\n";
589     }
590   }
591   void DIEAbbrev::dump() { print(std::cerr); }
592 #endif
593
594 //===----------------------------------------------------------------------===//
595
596 /// BestForm - Choose the best form for integer.
597 ///
598 unsigned DIEInteger::BestForm(bool IsSigned) {
599   if (IsSigned) {
600     if ((char)Integer == (signed)Integer)   return DW_FORM_data1;
601     if ((short)Integer == (signed)Integer)  return DW_FORM_data2;
602     if ((int)Integer == (signed)Integer)    return DW_FORM_data4;
603   } else {
604     if ((unsigned char)Integer == Integer)  return DW_FORM_data1;
605     if ((unsigned short)Integer == Integer) return DW_FORM_data2;
606     if ((unsigned int)Integer == Integer)   return DW_FORM_data4;
607   }
608   return DW_FORM_data8;
609 }
610     
611 /// EmitValue - Emit integer of appropriate size.
612 ///
613 void DIEInteger::EmitValue(const DwarfWriter &DW, unsigned Form) const {
614   switch (Form) {
615   case DW_FORM_flag:  // Fall thru
616   case DW_FORM_ref1:  // Fall thru
617   case DW_FORM_data1: DW.EmitInt8(Integer);         break;
618   case DW_FORM_ref2:  // Fall thru
619   case DW_FORM_data2: DW.EmitInt16(Integer);        break;
620   case DW_FORM_ref4:  // Fall thru
621   case DW_FORM_data4: DW.EmitInt32(Integer);        break;
622   case DW_FORM_ref8:  // Fall thru
623   case DW_FORM_data8: DW.EmitInt64(Integer);        break;
624   case DW_FORM_udata: DW.EmitULEB128Bytes(Integer); break;
625   case DW_FORM_sdata: DW.EmitSLEB128Bytes(Integer); break;
626   default: assert(0 && "DIE Value form not supported yet"); break;
627   }
628 }
629
630 /// SizeOf - Determine size of integer value in bytes.
631 ///
632 unsigned DIEInteger::SizeOf(const DwarfWriter &DW, unsigned Form) const {
633   switch (Form) {
634   case DW_FORM_flag:  // Fall thru
635   case DW_FORM_ref1:  // Fall thru
636   case DW_FORM_data1: return sizeof(int8_t);
637   case DW_FORM_ref2:  // Fall thru
638   case DW_FORM_data2: return sizeof(int16_t);
639   case DW_FORM_ref4:  // Fall thru
640   case DW_FORM_data4: return sizeof(int32_t);
641   case DW_FORM_ref8:  // Fall thru
642   case DW_FORM_data8: return sizeof(int64_t);
643   case DW_FORM_udata: return DW.SizeULEB128(Integer);
644   case DW_FORM_sdata: return DW.SizeSLEB128(Integer);
645   default: assert(0 && "DIE Value form not supported yet"); break;
646   }
647   return 0;
648 }
649
650 //===----------------------------------------------------------------------===//
651
652 /// EmitValue - Emit string value.
653 ///
654 void DIEString::EmitValue(const DwarfWriter &DW, unsigned Form) const {
655   DW.EmitString(String);
656 }
657
658 /// SizeOf - Determine size of string value in bytes.
659 ///
660 unsigned DIEString::SizeOf(const DwarfWriter &DW, unsigned Form) const {
661   return String.size() + sizeof(char); // sizeof('\0');
662 }
663
664 //===----------------------------------------------------------------------===//
665
666 /// EmitValue - Emit label value.
667 ///
668 void DIEDwarfLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
669   DW.EmitReference(Label);
670 }
671
672 /// SizeOf - Determine size of label value in bytes.
673 ///
674 unsigned DIEDwarfLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
675   return DW.getAddressSize();
676 }
677     
678 //===----------------------------------------------------------------------===//
679
680 /// EmitValue - Emit label value.
681 ///
682 void DIEObjectLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
683   DW.EmitReference(Label);
684 }
685
686 /// SizeOf - Determine size of label value in bytes.
687 ///
688 unsigned DIEObjectLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
689   return DW.getAddressSize();
690 }
691     
692 //===----------------------------------------------------------------------===//
693
694 /// EmitValue - Emit delta value.
695 ///
696 void DIEDelta::EmitValue(const DwarfWriter &DW, unsigned Form) const {
697   DW.EmitDifference(LabelHi, LabelLo);
698 }
699
700 /// SizeOf - Determine size of delta value in bytes.
701 ///
702 unsigned DIEDelta::SizeOf(const DwarfWriter &DW, unsigned Form) const {
703   return DW.getAddressSize();
704 }
705
706 //===----------------------------------------------------------------------===//
707 /// EmitValue - Emit debug information entry offset.
708 ///
709 void DIEntry::EmitValue(const DwarfWriter &DW, unsigned Form) const {
710   DW.EmitInt32(Entry->getOffset());
711 }
712
713 /// SizeOf - Determine size of debug information entry value in bytes.
714 ///
715 unsigned DIEntry::SizeOf(const DwarfWriter &DW, unsigned Form) const {
716   return sizeof(int32_t);
717 }
718     
719 //===----------------------------------------------------------------------===//
720
721 DIEBlock::~DIEBlock() {
722   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
723     delete Values[i];
724   }
725 }
726
727 /// ComputeSize - calculate the size of the block.
728 ///
729 unsigned DIEBlock::ComputeSize(DwarfWriter &DW) {
730   Size = 0;
731   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
732     Size += Values[i]->SizeOf(DW, Forms[i]);
733   }
734   return Size;
735 }
736
737 /// BestForm - Choose the best form for data.
738 ///
739 unsigned DIEBlock::BestForm() {
740   if ((unsigned char)Size == Size)  return DW_FORM_block1;
741   if ((unsigned short)Size == Size) return DW_FORM_block2;
742   if ((unsigned int)Size == Size)   return DW_FORM_block4;
743   return DW_FORM_block;
744 }
745
746 /// EmitValue - Emit block data.
747 ///
748 void DIEBlock::EmitValue(const DwarfWriter &DW, unsigned Form) const {
749   switch (Form) {
750   case DW_FORM_block1: DW.EmitInt8(Size);         break;
751   case DW_FORM_block2: DW.EmitInt16(Size);        break;
752   case DW_FORM_block4: DW.EmitInt32(Size);        break;
753   case DW_FORM_block:  DW.EmitULEB128Bytes(Size); break;
754   default: assert(0 && "Improper form for block"); break;
755   }
756   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
757     DW.EOL("");
758     Values[i]->EmitValue(DW, Forms[i]);
759   }
760 }
761
762 /// SizeOf - Determine size of block data in bytes.
763 ///
764 unsigned DIEBlock::SizeOf(const DwarfWriter &DW, unsigned Form) const {
765   switch (Form) {
766   case DW_FORM_block1: return Size + sizeof(int8_t);
767   case DW_FORM_block2: return Size + sizeof(int16_t);
768   case DW_FORM_block4: return Size + sizeof(int32_t);
769   case DW_FORM_block: return Size + DW.SizeULEB128(Size);
770   default: assert(0 && "Improper form for block"); break;
771   }
772   return 0;
773 }
774
775 /// AddUInt - Add an unsigned integer value.
776 ///
777 void DIEBlock::AddUInt(unsigned Form, uint64_t Integer) {
778   DIEInteger *DI = new DIEInteger(Integer);
779   Values.push_back(DI);
780   if (Form == 0) Form = DI->BestForm(false);
781   Forms.push_back(Form);
782 }
783
784 /// AddSInt - Add an signed integer value.
785 ///
786 void DIEBlock::AddSInt(unsigned Form, int64_t Integer) {
787   DIEInteger *DI = new DIEInteger(Integer);
788   Values.push_back(DI);
789   if (Form == 0) Form = DI->BestForm(true);
790   Forms.push_back(Form);
791 }
792     
793 /// AddString - Add a std::string value.
794 ///
795 void DIEBlock::AddString(unsigned Form, const std::string &String) {
796   Values.push_back(new DIEString(String));
797   Forms.push_back(Form);
798 }
799     
800 /// AddLabel - Add a Dwarf label value.
801 ///
802 void DIEBlock::AddLabel(unsigned Form, const DWLabel &Label) {
803   Values.push_back(new DIEDwarfLabel(Label));
804   Forms.push_back(Form);
805 }
806     
807 /// AddObjectLabel - Add a non-Dwarf label value.
808 ///
809 void DIEBlock::AddObjectLabel(unsigned Form, const std::string &Label) {
810   Values.push_back(new DIEObjectLabel(Label));
811   Forms.push_back(Form);
812 }
813     
814 /// AddDelta - Add a label delta value.
815 ///
816 void DIEBlock::AddDelta(unsigned Form, const DWLabel &Hi, const DWLabel &Lo) {
817   Values.push_back(new DIEDelta(Hi, Lo));
818   Forms.push_back(Form);
819 }
820     
821 /// AddDIEntry - Add a DIE value.
822 ///
823 void DIEBlock::AddDIEntry(unsigned Form, DIE *Entry) {
824   Values.push_back(new DIEntry(Entry));
825   Forms.push_back(Form);
826 }
827
828 //===----------------------------------------------------------------------===//
829
830 DIE::DIE(unsigned Tag)
831 : Abbrev(new DIEAbbrev(Tag, DW_CHILDREN_no))
832 , AbbrevID(0)
833 , Offset(0)
834 , Size(0)
835 , Children()
836 , Values()
837 {}
838
839 DIE::~DIE() {
840   if (Abbrev) delete Abbrev;
841   
842   for (unsigned i = 0, N = Children.size(); i < N; ++i) {
843     delete Children[i];
844   }
845
846   for (unsigned j = 0, M = Values.size(); j < M; ++j) {
847     delete Values[j];
848   }
849 }
850     
851 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
852 ///
853 void DIE::AddSiblingOffset() {
854   DIEInteger *DI = new DIEInteger(0);
855   Values.insert(Values.begin(), DI);
856   Abbrev->AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
857 }
858
859 /// AddUInt - Add an unsigned integer attribute data and value.
860 ///
861 void DIE::AddUInt(unsigned Attribute, unsigned Form, uint64_t Integer) {
862   DIEInteger *DI = new DIEInteger(Integer);
863   Values.push_back(DI);
864   if (!Form) Form = DI->BestForm(false);
865   Abbrev->AddAttribute(Attribute, Form);
866 }
867     
868 /// AddSInt - Add an signed integer attribute data and value.
869 ///
870 void DIE::AddSInt(unsigned Attribute, unsigned Form, int64_t Integer) {
871   DIEInteger *DI = new DIEInteger(Integer);
872   Values.push_back(DI);
873   if (!Form) Form = DI->BestForm(true);
874   Abbrev->AddAttribute(Attribute, Form);
875 }
876     
877 /// AddString - Add a std::string attribute data and value.
878 ///
879 void DIE::AddString(unsigned Attribute, unsigned Form,
880                     const std::string &String) {
881   Values.push_back(new DIEString(String));
882   Abbrev->AddAttribute(Attribute, Form);
883 }
884     
885 /// AddLabel - Add a Dwarf label attribute data and value.
886 ///
887 void DIE::AddLabel(unsigned Attribute, unsigned Form,
888                    const DWLabel &Label) {
889   Values.push_back(new DIEDwarfLabel(Label));
890   Abbrev->AddAttribute(Attribute, Form);
891 }
892     
893 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
894 ///
895 void DIE::AddObjectLabel(unsigned Attribute, unsigned Form,
896                          const std::string &Label) {
897   Values.push_back(new DIEObjectLabel(Label));
898   Abbrev->AddAttribute(Attribute, Form);
899 }
900     
901 /// AddDelta - Add a label delta attribute data and value.
902 ///
903 void DIE::AddDelta(unsigned Attribute, unsigned Form,
904                    const DWLabel &Hi, const DWLabel &Lo) {
905   Values.push_back(new DIEDelta(Hi, Lo));
906   Abbrev->AddAttribute(Attribute, Form);
907 }
908     
909 /// AddDIEntry - Add a DIE attribute data and value.
910 ///
911 void DIE::AddDIEntry(unsigned Attribute, unsigned Form, DIE *Entry) {
912   Values.push_back(new DIEntry(Entry));
913   Abbrev->AddAttribute(Attribute, Form);
914 }
915
916 /// AddBlock - Add block data.
917 ///
918 void DIE::AddBlock(unsigned Attribute, unsigned Form, DIEBlock *Block) {
919   assert(Block->Size && "Block size has not been computed");
920   Values.push_back(Block);
921   if (!Form) Form = Block->BestForm();
922   Abbrev->AddAttribute(Attribute, Form);
923 }
924
925 /// Complete - Indicate that all attributes have been added and ready to get an
926 /// abbreviation ID.
927 void DIE::Complete(DwarfWriter &DW) {
928   AbbrevID = DW.NewAbbreviation(Abbrev);
929   delete Abbrev;
930   Abbrev = NULL;
931 }
932
933 /// AddChild - Add a child to the DIE.
934 ///
935 void DIE::AddChild(DIE *Child) {
936   assert(Abbrev && "Adding children without an abbreviation");
937   Abbrev->setChildrenFlag(DW_CHILDREN_yes);
938   Children.push_back(Child);
939 }
940
941 //===----------------------------------------------------------------------===//
942
943 /// DWContext
944
945 //===----------------------------------------------------------------------===//
946
947 /// PrintHex - Print a value as a hexidecimal value.
948 ///
949 void DwarfWriter::PrintHex(int Value) const { 
950   O << "0x" << std::hex << Value << std::dec;
951 }
952
953 /// EOL - Print a newline character to asm stream.  If a comment is present
954 /// then it will be printed first.  Comments should not contain '\n'.
955 void DwarfWriter::EOL(const std::string &Comment) const {
956   if (DwarfVerbose && !Comment.empty()) {
957     O << "\t"
958       << Asm->CommentString
959       << " "
960       << Comment;
961   }
962   O << "\n";
963 }
964
965 /// EmitAlign - Print a align directive.
966 ///
967 void DwarfWriter::EmitAlign(unsigned Alignment) const {
968   O << Asm->AlignDirective << Alignment << "\n";
969 }
970
971 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
972 /// unsigned leb128 value.
973 void DwarfWriter::EmitULEB128Bytes(unsigned Value) const {
974   if (hasLEB128) {
975     O << "\t.uleb128\t"
976       << Value;
977   } else {
978     O << Asm->Data8bitsDirective;
979     PrintULEB128(Value);
980   }
981 }
982
983 /// EmitSLEB128Bytes - Emit an assembler byte data directive to compose a
984 /// signed leb128 value.
985 void DwarfWriter::EmitSLEB128Bytes(int Value) const {
986   if (hasLEB128) {
987     O << "\t.sleb128\t"
988       << Value;
989   } else {
990     O << Asm->Data8bitsDirective;
991     PrintSLEB128(Value);
992   }
993 }
994
995 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
996 /// representing an unsigned leb128 value.
997 void DwarfWriter::PrintULEB128(unsigned Value) const {
998   do {
999     unsigned Byte = Value & 0x7f;
1000     Value >>= 7;
1001     if (Value) Byte |= 0x80;
1002     PrintHex(Byte);
1003     if (Value) O << ", ";
1004   } while (Value);
1005 }
1006
1007 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
1008 /// value.
1009 unsigned DwarfWriter::SizeULEB128(unsigned Value) {
1010   unsigned Size = 0;
1011   do {
1012     Value >>= 7;
1013     Size += sizeof(int8_t);
1014   } while (Value);
1015   return Size;
1016 }
1017
1018 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
1019 /// representing a signed leb128 value.
1020 void DwarfWriter::PrintSLEB128(int Value) const {
1021   int Sign = Value >> (8 * sizeof(Value) - 1);
1022   bool IsMore;
1023   
1024   do {
1025     unsigned Byte = Value & 0x7f;
1026     Value >>= 7;
1027     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
1028     if (IsMore) Byte |= 0x80;
1029     PrintHex(Byte);
1030     if (IsMore) O << ", ";
1031   } while (IsMore);
1032 }
1033
1034 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
1035 /// value.
1036 unsigned DwarfWriter::SizeSLEB128(int Value) {
1037   unsigned Size = 0;
1038   int Sign = Value >> (8 * sizeof(Value) - 1);
1039   bool IsMore;
1040   
1041   do {
1042     unsigned Byte = Value & 0x7f;
1043     Value >>= 7;
1044     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
1045     Size += sizeof(int8_t);
1046   } while (IsMore);
1047   return Size;
1048 }
1049
1050 /// EmitInt8 - Emit a byte directive and value.
1051 ///
1052 void DwarfWriter::EmitInt8(int Value) const {
1053   O << Asm->Data8bitsDirective;
1054   PrintHex(Value & 0xFF);
1055 }
1056
1057 /// EmitInt16 - Emit a short directive and value.
1058 ///
1059 void DwarfWriter::EmitInt16(int Value) const {
1060   O << Asm->Data16bitsDirective;
1061   PrintHex(Value & 0xFFFF);
1062 }
1063
1064 /// EmitInt32 - Emit a long directive and value.
1065 ///
1066 void DwarfWriter::EmitInt32(int Value) const {
1067   O << Asm->Data32bitsDirective;
1068   PrintHex(Value);
1069 }
1070
1071 /// EmitInt64 - Emit a long long directive and value.
1072 ///
1073 void DwarfWriter::EmitInt64(uint64_t Value) const {
1074   if (Asm->Data64bitsDirective) {
1075     O << Asm->Data64bitsDirective << "0x" << std::hex << Value << std::dec;
1076   } else {
1077     if (TD.isBigEndian()) {
1078       EmitInt32(unsigned(Value >> 32)); O << "\n";
1079       EmitInt32(unsigned(Value));
1080     } else {
1081       EmitInt32(unsigned(Value)); O << "\n";
1082       EmitInt32(unsigned(Value >> 32));
1083     }
1084   }
1085 }
1086
1087 /// EmitString - Emit a string with quotes and a null terminator.
1088 /// Special characters are emitted properly. (Eg. '\t')
1089 void DwarfWriter::EmitString(const std::string &String) const {
1090   O << Asm->AsciiDirective
1091     << "\"";
1092   for (unsigned i = 0, N = String.size(); i < N; ++i) {
1093     unsigned char C = String[i];
1094     
1095     if (!isascii(C) || iscntrl(C)) {
1096       switch(C) {
1097       case '\b': O << "\\b"; break;
1098       case '\f': O << "\\f"; break;
1099       case '\n': O << "\\n"; break;
1100       case '\r': O << "\\r"; break;
1101       case '\t': O << "\\t"; break;
1102       default:
1103         O << '\\';
1104         O << char('0' + (C >> 6));
1105         O << char('0' + (C >> 3));
1106         O << char('0' + (C >> 0));
1107         break;
1108       }
1109     } else if (C == '\"') {
1110       O << "\\\"";
1111     } else if (C == '\'') {
1112       O << "\\\'";
1113     } else {
1114      O << C;
1115     }
1116   }
1117   O << "\\0\"";
1118 }
1119
1120 /// PrintLabelName - Print label name in form used by Dwarf writer.
1121 ///
1122 void DwarfWriter::PrintLabelName(const char *Tag, unsigned Number) const {
1123   O << Asm->PrivateGlobalPrefix
1124     << "debug_"
1125     << Tag;
1126   if (Number) O << Number;
1127 }
1128
1129 /// EmitLabel - Emit location label for internal use by Dwarf.
1130 ///
1131 void DwarfWriter::EmitLabel(const char *Tag, unsigned Number) const {
1132   PrintLabelName(Tag, Number);
1133   O << ":\n";
1134 }
1135
1136 /// EmitReference - Emit a reference to a label.
1137 ///
1138 void DwarfWriter::EmitReference(const char *Tag, unsigned Number) const {
1139   if (AddressSize == 4)
1140     O << Asm->Data32bitsDirective;
1141   else
1142     O << Asm->Data64bitsDirective;
1143     
1144   PrintLabelName(Tag, Number);
1145 }
1146 void DwarfWriter::EmitReference(const std::string &Name) const {
1147   if (AddressSize == 4)
1148     O << Asm->Data32bitsDirective;
1149   else
1150     O << Asm->Data64bitsDirective;
1151     
1152   O << Name;
1153 }
1154
1155 /// EmitDifference - Emit an label difference as sizeof(pointer) value.  Some
1156 /// assemblers do not accept absolute expressions with data directives, so there 
1157 /// is an option (needsSet) to use an intermediary 'set' expression.
1158 void DwarfWriter::EmitDifference(const char *TagHi, unsigned NumberHi,
1159                                  const char *TagLo, unsigned NumberLo) const {
1160   if (needsSet) {
1161     static unsigned SetCounter = 0;
1162     
1163     O << "\t.set\t";
1164     PrintLabelName("set", SetCounter);
1165     O << ",";
1166     PrintLabelName(TagHi, NumberHi);
1167     O << "-";
1168     PrintLabelName(TagLo, NumberLo);
1169     O << "\n";
1170     
1171     if (AddressSize == sizeof(int32_t))
1172       O << Asm->Data32bitsDirective;
1173     else
1174       O << Asm->Data64bitsDirective;
1175       
1176     PrintLabelName("set", SetCounter);
1177     
1178     ++SetCounter;
1179   } else {
1180     if (AddressSize == sizeof(int32_t))
1181       O << Asm->Data32bitsDirective;
1182     else
1183       O << Asm->Data64bitsDirective;
1184       
1185     PrintLabelName(TagHi, NumberHi);
1186     O << "-";
1187     PrintLabelName(TagLo, NumberLo);
1188   }
1189 }
1190
1191 /// NewAbbreviation - Add the abbreviation to the Abbreviation vector.
1192 ///  
1193 unsigned DwarfWriter::NewAbbreviation(DIEAbbrev *Abbrev) {
1194   return Abbreviations.insert(*Abbrev);
1195 }
1196
1197 /// NewString - Add a string to the constant pool and returns a label.
1198 ///
1199 DWLabel DwarfWriter::NewString(const std::string &String) {
1200   unsigned StringID = StringPool.insert(String);
1201   return DWLabel("string", StringID);
1202 }
1203
1204 /// AddSourceLine - Add location information to specified debug information
1205 /// entry.
1206 void DwarfWriter::AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1207   if (File && Line) {
1208     CompileUnit *FileUnit = FindCompileUnit(File);
1209     unsigned FileID = FileUnit->getID();
1210     Die->AddUInt(DW_AT_decl_file, 0, FileID);
1211     Die->AddUInt(DW_AT_decl_line, 0, Line);
1212   }
1213 }
1214
1215 /// AddAddress - Add an address attribute to a die based on the location
1216 /// provided.
1217 void DwarfWriter::AddAddress(DIE *Die, unsigned Attribute,
1218                              const MachineLocation &Location) {
1219   DIEBlock *Block = new DIEBlock();
1220   if (Location.isRegister()) {
1221     Block->AddUInt(DW_FORM_data1,
1222                    DW_OP_reg0 + RI->getDwarfRegNum(Location.getRegister()));
1223   } else {
1224     Block->AddUInt(DW_FORM_data1,
1225                    DW_OP_breg0 + RI->getDwarfRegNum(Location.getRegister()));
1226     Block->AddUInt(DW_FORM_sdata, Location.getOffset());
1227   }
1228   Block->ComputeSize(*this);
1229   Die->AddBlock(Attribute, 0, Block);
1230 }
1231
1232 /// getDieMapSlotFor - Returns the debug information entry map slot for the
1233 /// specified debug descriptor.
1234 DIE *&DwarfWriter::getDieMapSlotFor(DebugInfoDesc *DD) {
1235   return DescToDieMap[DD];
1236 }
1237                                  
1238 /// NewType - Create a new type DIE.
1239 ///
1240 DIE *DwarfWriter::NewType(DIE *Context, TypeDesc *TyDesc, CompileUnit *Unit) {
1241   if (!TyDesc) {
1242     // FIXME - Hack for missing types
1243     DIE *Die = new DIE(DW_TAG_base_type);
1244     Die->AddUInt(DW_AT_byte_size, 0, 4);
1245     Die->AddUInt(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1246     Unit->getDie()->AddChild(Die);
1247     return Die;
1248   }
1249   
1250   // FIXME - Should handle other contexts that compile units.
1251
1252   // Check for pre-existence.
1253   DIE *&Slot = Unit->getDieMapSlotFor(TyDesc);
1254   if (Slot) return Slot;
1255
1256   // Get core information.
1257   const std::string &Name = TyDesc->getName();
1258   uint64_t Size = TyDesc->getSize() >> 3;
1259   
1260   DIE *Ty = NULL;
1261   
1262   if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1263     // Fundamental types like int, float, bool
1264     Slot = Ty = new DIE(DW_TAG_base_type);
1265     unsigned Encoding = BasicTy->getEncoding();
1266     Ty->AddUInt  (DW_AT_encoding,  DW_FORM_data1, Encoding);
1267   } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1268     // Create specific DIE.
1269     Slot = Ty = new DIE(DerivedTy->getTag());
1270     
1271     // Map to main type, void will not have a type.
1272     if (TypeDesc *FromTy = DerivedTy->getFromType()) {
1273       Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1274                      NewType(Context, FromTy, Unit));
1275     }
1276   } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)) {
1277     // Create specific DIE.
1278     Slot = Ty = new DIE(CompTy->getTag());
1279     std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1280     
1281     switch (CompTy->getTag()) {
1282     case DW_TAG_array_type: {
1283       // Add element type.
1284       if (TypeDesc *FromTy = CompTy->getFromType()) {
1285         Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1286                        NewType(Context, FromTy, Unit));
1287       }
1288       // Don't emit size attribute.
1289       Size = 0;
1290       
1291       // Construct an anonymous type for index type.
1292       DIE *IndexTy = new DIE(DW_TAG_base_type);
1293       IndexTy->AddUInt(DW_AT_byte_size, 0, 4);
1294       IndexTy->AddUInt(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1295       // Add to context.
1296       Context->AddChild(IndexTy);
1297     
1298       // Add subranges to array type.
1299       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1300         SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1301         int64_t Lo = SRD->getLo();
1302         int64_t Hi = SRD->getHi();
1303         DIE *Subrange = new DIE(DW_TAG_subrange_type);
1304         
1305         // If a range is available.
1306         if (Lo != Hi) {
1307           Subrange->AddDIEntry(DW_AT_type, DW_FORM_ref4, IndexTy);
1308           // Only add low if non-zero.
1309           if (Lo) Subrange->AddSInt(DW_AT_lower_bound, 0, Lo);
1310           Subrange->AddSInt(DW_AT_upper_bound, 0, Hi);
1311         }
1312         Ty->AddChild(Subrange);
1313       }
1314       
1315       break;
1316     }
1317     case DW_TAG_structure_type:
1318     case DW_TAG_union_type: {
1319       // FIXME - this is just the basics.
1320       // Add elements to structure type.
1321       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1322         DerivedTypeDesc *MemberDesc = cast<DerivedTypeDesc>(Elements[i]);
1323         
1324         // Extract the basic information.
1325         const std::string &Name = MemberDesc->getName();
1326         TypeDesc *MemTy = MemberDesc->getFromType();
1327         uint64_t Size = MemberDesc->getSize();
1328         uint64_t Align = MemberDesc->getAlign();
1329         uint64_t Offset = MemberDesc->getOffset();
1330    
1331         // Construct member debug information entry.
1332         DIE *Member = new DIE(DW_TAG_member);
1333         
1334         // Add name if not "".
1335         if (!Name.empty()) Member->AddString(DW_AT_name, DW_FORM_string, Name);
1336         // Add location if available.
1337         AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1338         
1339         // Most of the time the field info is the same as the members.
1340         uint64_t FieldSize = Size;
1341         uint64_t FieldAlign = Align;
1342         uint64_t FieldOffset = Offset;
1343         
1344         if (TypeDesc *FromTy = MemberDesc->getFromType()) {
1345           Member->AddDIEntry(DW_AT_type, DW_FORM_ref4,
1346                              NewType(Context, FromTy, Unit));
1347           FieldSize = FromTy->getSize();
1348           FieldAlign = FromTy->getSize();
1349         }
1350         
1351         // Unless we have a bit field.
1352         if (FieldSize != Size) {
1353           // Construct the alignment mask.
1354           uint64_t AlignMask = ~(FieldAlign - 1);
1355           // Determine the high bit + 1 of the declared size.
1356           uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1357           // Work backwards to determine the base offset of the field.
1358           FieldOffset = HiMark - FieldSize;
1359           // Now normalize offset to the field.
1360           Offset -= FieldOffset;
1361           
1362           // Maybe we need to work from the other end.
1363           if (TD.isLittleEndian()) Offset = FieldSize - (Offset + Size);
1364           
1365           Member->AddUInt(DW_AT_byte_size, 0, FieldSize >> 3);
1366           Member->AddUInt(DW_AT_bit_size, 0, Size);
1367           Member->AddUInt(DW_AT_bit_offset, 0, Offset);
1368         }
1369         
1370         // Add computation for offset.
1371         DIEBlock *Block = new DIEBlock();
1372         Block->AddUInt(DW_FORM_data1, DW_OP_plus_uconst);
1373         Block->AddUInt(DW_FORM_udata, FieldOffset >> 3);
1374         Block->ComputeSize(*this);
1375         Member->AddBlock(DW_AT_data_member_location, 0, Block);
1376         
1377         Ty->AddChild(Member);
1378       }
1379       break;
1380     }
1381     case DW_TAG_enumeration_type: {
1382       // Add enumerators to enumeration type.
1383       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1384         EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1385         const std::string &Name = ED->getName();
1386         int64_t Value = ED->getValue();
1387         DIE *Enumerator = new DIE(DW_TAG_enumerator);
1388         Enumerator->AddString(DW_AT_name, DW_FORM_string, Name);
1389         Enumerator->AddSInt(DW_AT_const_value, DW_FORM_sdata, Value);
1390         Ty->AddChild(Enumerator);
1391       }
1392
1393       break;
1394     }
1395     default: break;
1396     }
1397   }
1398   
1399   assert(Ty && "Type not supported yet");
1400  
1401   // Add size if non-zero (derived types don't have a size.)
1402   if (Size) Ty->AddUInt(DW_AT_byte_size, 0, Size);
1403   // Add name if not anonymous or intermediate type.
1404   if (!Name.empty()) Ty->AddString(DW_AT_name, DW_FORM_string, Name);
1405   // Add source line info if available.
1406   AddSourceLine(Ty, TyDesc->getFile(), TyDesc->getLine());
1407
1408   // Add to context owner.
1409   Context->AddChild(Ty);
1410   
1411   return Slot;
1412 }
1413
1414 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1415 ///
1416 CompileUnit *DwarfWriter::NewCompileUnit(CompileUnitDesc *UnitDesc,
1417                                          unsigned ID) {
1418   // Construct debug information entry.
1419   DIE *Die = new DIE(DW_TAG_compile_unit);
1420   Die->AddLabel (DW_AT_stmt_list, DW_FORM_data4,  DWLabel("line", 0));
1421   Die->AddLabel (DW_AT_high_pc,   DW_FORM_addr,   DWLabel("text_end", 0));
1422   Die->AddLabel (DW_AT_low_pc,    DW_FORM_addr,   DWLabel("text_begin", 0));
1423   Die->AddString(DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
1424   Die->AddUInt  (DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
1425   Die->AddString(DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
1426   Die->AddString(DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
1427   
1428   // Add debug information entry to descriptor map.
1429   DIE *&Slot = getDieMapSlotFor(UnitDesc);
1430   Slot = Die;
1431   
1432   // Construct compile unit.
1433   CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1434   
1435   // Add Unit to compile unit map.
1436   DescToUnitMap[UnitDesc] = Unit;
1437   
1438   return Unit;
1439 }
1440
1441 /// FindCompileUnit - Get the compile unit for the given descriptor.
1442 ///
1443 CompileUnit *DwarfWriter::FindCompileUnit(CompileUnitDesc *UnitDesc) {
1444   CompileUnit *Unit = DescToUnitMap[UnitDesc];
1445   assert(Unit && "Missing compile unit.");
1446   return Unit;
1447 }
1448
1449 /// NewGlobalVariable - Add a new global variable DIE.
1450 ///
1451 DIE *DwarfWriter::NewGlobalVariable(GlobalVariableDesc *GVD) {
1452   // Get the compile unit context.
1453   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(GVD->getContext());
1454   CompileUnit *Unit = FindCompileUnit(UnitDesc);
1455
1456   // Check for pre-existence.
1457   DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1458   if (Slot) return Slot;
1459   
1460   // Get the global variable itself.
1461   GlobalVariable *GV = GVD->getGlobalVariable();
1462   // Generate the mangled name.
1463   std::string MangledName = Asm->Mang->getValueName(GV);
1464
1465   // Gather the details (simplify add attribute code.)
1466   const std::string &Name = GVD->getName();
1467   
1468   // Get the global's type.
1469   DIE *Type = NewType(Unit->getDie(), GVD->getType(), Unit); 
1470
1471   // Create the globale variable DIE.
1472   DIE *VariableDie = new DIE(DW_TAG_variable);
1473   VariableDie->AddString     (DW_AT_name,      DW_FORM_string, Name);
1474   VariableDie->AddDIEntry    (DW_AT_type,      DW_FORM_ref4,   Type);
1475   VariableDie->AddUInt       (DW_AT_external,  DW_FORM_flag,   1);
1476   
1477   // Add source line info if available.
1478   AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1479
1480   // Add address.
1481   DIEBlock *Block = new DIEBlock();
1482   Block->AddUInt(DW_FORM_data1, DW_OP_addr);
1483   Block->AddObjectLabel(DW_FORM_udata, MangledName);
1484   Block->ComputeSize(*this);
1485   VariableDie->AddBlock(DW_AT_location,  0, Block);
1486   
1487   // Add to map.
1488   Slot = VariableDie;
1489  
1490   // Add to context owner.
1491   Unit->getDie()->AddChild(VariableDie);
1492   
1493   // Expose as global.
1494   // FIXME - need to check external flag.
1495   Unit->AddGlobal(Name, VariableDie);
1496   
1497   return VariableDie;
1498 }
1499
1500 /// NewSubprogram - Add a new subprogram DIE.
1501 ///
1502 DIE *DwarfWriter::NewSubprogram(SubprogramDesc *SPD) {
1503   // Get the compile unit context.
1504   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
1505   CompileUnit *Unit = FindCompileUnit(UnitDesc);
1506
1507   // Check for pre-existence.
1508   DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1509   if (Slot) return Slot;
1510   
1511   // Gather the details (simplify add attribute code.)
1512   const std::string &Name = SPD->getName();
1513   DIE *Type = NewType(Unit->getDie(), SPD->getType(), Unit); 
1514   unsigned IsExternal = SPD->isStatic() ? 0 : 1;
1515                                     
1516   DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1517   SubprogramDie->AddString     (DW_AT_name,      DW_FORM_string, Name);
1518   if (Type) {
1519     SubprogramDie->AddDIEntry    (DW_AT_type,      DW_FORM_ref4,   Type);
1520   }
1521   SubprogramDie->AddUInt       (DW_AT_external,    DW_FORM_flag,   IsExternal);
1522   SubprogramDie->AddUInt       (DW_AT_prototyped,  DW_FORM_flag,   1);
1523   
1524   // Add source line info if available.
1525   AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1526
1527   // Add to map.
1528   Slot = SubprogramDie;
1529  
1530   // Add to context owner.
1531   Unit->getDie()->AddChild(SubprogramDie);
1532   
1533   // Expose as global.
1534   Unit->AddGlobal(Name, SubprogramDie);
1535   
1536   return SubprogramDie;
1537 }
1538
1539 /// NewScopeVariable - Create a new scope variable.
1540 ///
1541 DIE *DwarfWriter::NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1542   // Get the descriptor.
1543   VariableDesc *VD = DV->getDesc();
1544
1545   // Translate tag to proper Dwarf tag.  The result variable is dropped for now.
1546   unsigned Tag;
1547   switch (VD->getTag()) {
1548   case DW_TAG_return_variable:  return NULL;
1549   case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
1550   case DW_TAG_auto_variable:    // fall thru
1551   default:                      Tag = DW_TAG_variable; break;
1552   }
1553
1554   // Define variable debug information entry.
1555   DIE *VariableDie = new DIE(Tag);
1556   VariableDie->AddString(DW_AT_name, DW_FORM_string, VD->getName());
1557
1558   // Add source line info if available.
1559   AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1560   
1561   // Add variable type.
1562   DIE *Type = NewType(Unit->getDie(), VD->getType(), Unit); 
1563   VariableDie->AddDIEntry(DW_AT_type, DW_FORM_ref4, Type);
1564   
1565   // Add variable address.
1566   MachineLocation Location;
1567   RI->getLocation(*MF, DV->getFrameIndex(), Location);
1568   AddAddress(VariableDie, DW_AT_location, Location);
1569   
1570   return VariableDie;
1571 }
1572
1573 /// ConstructScope - Construct the components of a scope.
1574 ///
1575 void DwarfWriter::ConstructScope(DebugScope *ParentScope,
1576                                  DIE *ParentDie, CompileUnit *Unit) {
1577   // Add variables to scope.
1578   std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1579   for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1580     DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1581     if (VariableDie) ParentDie->AddChild(VariableDie);
1582   }
1583   
1584   // Add nested scopes.
1585   std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1586   for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1587     // Define the Scope debug information entry.
1588     DebugScope *Scope = Scopes[j];
1589     // FIXME - Ignore inlined functions for the time being.
1590     if (Scope->getParent()) continue;
1591     
1592     DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1593     
1594     // Add the scope bounds.
1595     if (unsigned StartID = Scope->getStartLabelID()) {
1596       ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
1597                          DWLabel("loc", StartID));
1598     } else {
1599       ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
1600                          DWLabel("func_begin", SubprogramCount));
1601     }
1602     if (unsigned EndID = Scope->getEndLabelID()) {
1603       ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
1604                          DWLabel("loc", EndID));
1605     } else {
1606       ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
1607                          DWLabel("func_end", SubprogramCount));
1608     }
1609                        
1610     // Add the scope contents.
1611     ConstructScope(Scope, ScopeDie, Unit);
1612     ParentDie->AddChild(ScopeDie);
1613   }
1614 }
1615
1616 /// ConstructRootScope - Construct the scope for the subprogram.
1617 ///
1618 void DwarfWriter::ConstructRootScope(DebugScope *RootScope) {
1619   // Exit if there is no root scope.
1620   if (!RootScope) return;
1621   
1622   // Get the subprogram debug information entry. 
1623   SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1624   
1625   // Get the compile unit context.
1626   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
1627   CompileUnit *Unit = FindCompileUnit(UnitDesc);
1628   
1629   // Generate the mangled name.
1630   std::string MangledName = Asm->Mang->getValueName(MF->getFunction());
1631   
1632   // Get the subprogram die.
1633   DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1634   assert(SPDie && "Missing subprogram descriptor");
1635   
1636   // Add the function bounds.
1637   SPDie->AddObjectLabel(DW_AT_low_pc, DW_FORM_addr, MangledName);
1638   SPDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
1639                   DWLabel("func_end", SubprogramCount));
1640   MachineLocation Location(RI->getFrameRegister(*MF));
1641   AddAddress(SPDie, DW_AT_frame_base, Location);
1642                   
1643   ConstructScope(RootScope, SPDie, Unit);
1644 }
1645
1646 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1647 /// tools to recognize the object file contains Dwarf information.
1648 ///
1649 void DwarfWriter::EmitInitial() const {
1650   // Dwarf sections base addresses.
1651   Asm->SwitchSection(DwarfFrameSection, 0);
1652   EmitLabel("section_frame", 0);
1653   Asm->SwitchSection(DwarfInfoSection, 0);
1654   EmitLabel("section_info", 0);
1655   EmitLabel("info", 0);
1656   Asm->SwitchSection(DwarfAbbrevSection, 0);
1657   EmitLabel("section_abbrev", 0);
1658   EmitLabel("abbrev", 0);
1659   Asm->SwitchSection(DwarfARangesSection, 0);
1660   EmitLabel("section_aranges", 0);
1661   Asm->SwitchSection(DwarfMacInfoSection, 0);
1662   EmitLabel("section_macinfo", 0);
1663   Asm->SwitchSection(DwarfLineSection, 0);
1664   EmitLabel("section_line", 0);
1665   EmitLabel("line", 0);
1666   Asm->SwitchSection(DwarfLocSection, 0);
1667   EmitLabel("section_loc", 0);
1668   Asm->SwitchSection(DwarfPubNamesSection, 0);
1669   EmitLabel("section_pubnames", 0);
1670   Asm->SwitchSection(DwarfStrSection, 0);
1671   EmitLabel("section_str", 0);
1672   Asm->SwitchSection(DwarfRangesSection, 0);
1673   EmitLabel("section_ranges", 0);
1674
1675   Asm->SwitchSection(TextSection, 0);
1676   EmitLabel("text_begin", 0);
1677   Asm->SwitchSection(DataSection, 0);
1678   EmitLabel("data_begin", 0);
1679 }
1680
1681 /// EmitDIE - Recusively Emits a debug information entry.
1682 ///
1683 void DwarfWriter::EmitDIE(DIE *Die) const {
1684   // Get the abbreviation for this DIE.
1685   unsigned AbbrevID = Die->getAbbrevID();
1686   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1687   
1688   O << "\n";
1689
1690   // Emit the code (index) for the abbreviation.
1691   EmitULEB128Bytes(AbbrevID);
1692   EOL(std::string("Abbrev [" +
1693       utostr(AbbrevID) +
1694       "] 0x" + utohexstr(Die->getOffset()) +
1695       ":0x" + utohexstr(Die->getSize()) + " " +
1696       TagString(Abbrev.getTag())));
1697   
1698   const std::vector<DIEValue *> &Values = Die->getValues();
1699   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1700   
1701   // Emit the DIE attribute values.
1702   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1703     unsigned Attr = AbbrevData[i].getAttribute();
1704     unsigned Form = AbbrevData[i].getForm();
1705     assert(Form && "Too many attributes for DIE (check abbreviation)");
1706     
1707     switch (Attr) {
1708     case DW_AT_sibling: {
1709       EmitInt32(Die->SiblingOffset());
1710       break;
1711     }
1712     default: {
1713       // Emit an attribute using the defined form.
1714       Values[i]->EmitValue(*this, Form);
1715       break;
1716     }
1717     }
1718     
1719     EOL(AttributeString(Attr));
1720   }
1721   
1722   // Emit the DIE children if any.
1723   if (Abbrev.getChildrenFlag() == DW_CHILDREN_yes) {
1724     const std::vector<DIE *> &Children = Die->getChildren();
1725     
1726     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1727       EmitDIE(Children[j]);
1728     }
1729     
1730     EmitInt8(0); EOL("End Of Children Mark");
1731   }
1732 }
1733
1734 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1735 ///
1736 unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1737   // Get the children.
1738   const std::vector<DIE *> &Children = Die->getChildren();
1739   
1740   // If not last sibling and has children then add sibling offset attribute.
1741   if (!Last && !Children.empty()) Die->AddSiblingOffset();
1742
1743   // Record the abbreviation.
1744   Die->Complete(*this);
1745   
1746   // Get the abbreviation for this DIE.
1747   unsigned AbbrevID = Die->getAbbrevID();
1748   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1749
1750   // Set DIE offset
1751   Die->setOffset(Offset);
1752   
1753   // Start the size with the size of abbreviation code.
1754   Offset += SizeULEB128(AbbrevID);
1755   
1756   const std::vector<DIEValue *> &Values = Die->getValues();
1757   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1758
1759   // Emit the DIE attribute values.
1760   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1761     // Size attribute value.
1762     Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
1763   }
1764   
1765   // Emit the DIE children if any.
1766   if (!Children.empty()) {
1767     assert(Abbrev.getChildrenFlag() == DW_CHILDREN_yes &&
1768            "Children flag not set");
1769     
1770     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1771       Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1772     }
1773     
1774     // End of children marker.
1775     Offset += sizeof(int8_t);
1776   }
1777
1778   Die->setSize(Offset - Die->getOffset());
1779   return Offset;
1780 }
1781
1782 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1783 ///
1784 void DwarfWriter::SizeAndOffsets() {
1785   
1786   // Process each compile unit.
1787   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
1788     CompileUnit *Unit = CompileUnits[i];
1789     if (Unit->hasContent()) {
1790       // Compute size of compile unit header
1791       unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
1792                         sizeof(int16_t) + // DWARF version number
1793                         sizeof(int32_t) + // Offset Into Abbrev. Section
1794                         sizeof(int8_t);   // Pointer Size (in bytes)
1795       SizeAndOffsetDie(Unit->getDie(), Offset, (i + 1) == N);
1796     }
1797   }
1798 }
1799
1800 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1801 /// frame.
1802 void DwarfWriter::EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1803                                  std::vector<MachineMove *> &Moves) {
1804   for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1805     MachineMove *Move = Moves[i];
1806     unsigned LabelID = Move->getLabelID();
1807     const MachineLocation &Dst = Move->getDestination();
1808     const MachineLocation &Src = Move->getSource();
1809     
1810     // Advance row if new location.
1811     if (BaseLabel && LabelID && BaseLabelID != LabelID) {
1812       EmitULEB128Bytes(DW_CFA_advance_loc4);
1813       EOL("DW_CFA_advance_loc4");
1814       EmitDifference("loc", LabelID, BaseLabel, BaseLabelID);
1815       EOL("");
1816       
1817       BaseLabelID = LabelID;
1818       BaseLabel = "loc";
1819     }
1820     
1821     // If advancing cfa.
1822     if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1823       if (!Src.isRegister()) {
1824         if (Src.getRegister() == MachineLocation::VirtualFP) {
1825           EmitULEB128Bytes(DW_CFA_def_cfa_offset);
1826           EOL("DW_CFA_def_cfa_offset");
1827         } else {
1828           EmitULEB128Bytes(DW_CFA_def_cfa);
1829           EOL("DW_CFA_def_cfa");
1830           
1831           EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
1832           EOL("Register");
1833         }
1834           
1835         EmitULEB128Bytes(Src.getOffset() / RI->getStackDirection());
1836         EOL("Offset");
1837       } else {
1838       }
1839     } else {
1840     }
1841   }
1842 }
1843
1844 /// EmitDebugInfo - Emit the debug info section.
1845 ///
1846 void DwarfWriter::EmitDebugInfo() const {
1847   // Start debug info section.
1848   Asm->SwitchSection(DwarfInfoSection, 0);
1849   
1850   // Process each compile unit.
1851   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
1852     CompileUnit *Unit = CompileUnits[i];
1853     
1854     if (Unit->hasContent()) {
1855       DIE *Die = Unit->getDie();
1856       // Emit the compile units header.
1857       EmitLabel("info_begin", Unit->getID());
1858       // Emit size of content not including length itself
1859       unsigned ContentSize = Die->getSize() +
1860                              sizeof(int16_t) + // DWARF version number
1861                              sizeof(int32_t) + // Offset Into Abbrev. Section
1862                              sizeof(int8_t);   // Pointer Size (in bytes)
1863                              
1864       EmitInt32(ContentSize);  EOL("Length of Compilation Unit Info");
1865       EmitInt16(DWARF_VERSION); EOL("DWARF version number");
1866       EmitReference("abbrev_begin", 0); EOL("Offset Into Abbrev. Section");
1867       EmitInt8(AddressSize); EOL("Address Size (in bytes)");
1868     
1869       EmitDIE(Die);
1870       EmitLabel("info_end", Unit->getID());
1871     }
1872     
1873     O << "\n";
1874   }
1875 }
1876
1877 /// EmitAbbreviations - Emit the abbreviation section.
1878 ///
1879 void DwarfWriter::EmitAbbreviations() const {
1880   // Check to see if it is worth the effort.
1881   if (!Abbreviations.empty()) {
1882     // Start the debug abbrev section.
1883     Asm->SwitchSection(DwarfAbbrevSection, 0);
1884     
1885     EmitLabel("abbrev_begin", 0);
1886     
1887     // For each abbrevation.
1888     for (unsigned AbbrevID = 1, NAID = Abbreviations.size();
1889                   AbbrevID <= NAID; ++AbbrevID) {
1890       // Get abbreviation data
1891       const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1892       
1893       // Emit the abbrevations code (base 1 index.)
1894       EmitULEB128Bytes(AbbrevID); EOL("Abbreviation Code");
1895       
1896       // Emit the abbreviations data.
1897       Abbrev.Emit(*this);
1898   
1899       O << "\n";
1900     }
1901     
1902     EmitLabel("abbrev_end", 0);
1903   
1904     O << "\n";
1905   }
1906 }
1907
1908 /// EmitDebugLines - Emit source line information.
1909 ///
1910 void DwarfWriter::EmitDebugLines() const {
1911   // Minimum line delta, thus ranging from -10..(255-10).
1912   const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
1913   // Maximum line delta, thus ranging from -10..(255-10).
1914   const int MaxLineDelta = 255 + MinLineDelta;
1915
1916   // Start the dwarf line section.
1917   Asm->SwitchSection(DwarfLineSection, 0);
1918   
1919   // Construct the section header.
1920   
1921   EmitDifference("line_end", 0, "line_begin", 0);
1922   EOL("Length of Source Line Info");
1923   EmitLabel("line_begin", 0);
1924   
1925   EmitInt16(DWARF_VERSION); EOL("DWARF version number");
1926   
1927   EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0);
1928   EOL("Prolog Length");
1929   EmitLabel("line_prolog_begin", 0);
1930   
1931   EmitInt8(1); EOL("Minimum Instruction Length");
1932
1933   EmitInt8(1); EOL("Default is_stmt_start flag");
1934
1935   EmitInt8(MinLineDelta);  EOL("Line Base Value (Special Opcodes)");
1936   
1937   EmitInt8(MaxLineDelta); EOL("Line Range Value (Special Opcodes)");
1938
1939   EmitInt8(-MinLineDelta); EOL("Special Opcode Base");
1940   
1941   // Line number standard opcode encodings argument count
1942   EmitInt8(0); EOL("DW_LNS_copy arg count");
1943   EmitInt8(1); EOL("DW_LNS_advance_pc arg count");
1944   EmitInt8(1); EOL("DW_LNS_advance_line arg count");
1945   EmitInt8(1); EOL("DW_LNS_set_file arg count");
1946   EmitInt8(1); EOL("DW_LNS_set_column arg count");
1947   EmitInt8(0); EOL("DW_LNS_negate_stmt arg count");
1948   EmitInt8(0); EOL("DW_LNS_set_basic_block arg count");
1949   EmitInt8(0); EOL("DW_LNS_const_add_pc arg count");
1950   EmitInt8(1); EOL("DW_LNS_fixed_advance_pc arg count");
1951
1952   const UniqueVector<std::string> &Directories = DebugInfo->getDirectories();
1953   const UniqueVector<SourceFileInfo> &SourceFiles = DebugInfo->getSourceFiles();
1954
1955   // Emit directories.
1956   for (unsigned DirectoryID = 1, NDID = Directories.size();
1957                 DirectoryID <= NDID; ++DirectoryID) {
1958     EmitString(Directories[DirectoryID]); EOL("Directory");
1959   }
1960   EmitInt8(0); EOL("End of directories");
1961   
1962   // Emit files.
1963   for (unsigned SourceID = 1, NSID = SourceFiles.size();
1964                SourceID <= NSID; ++SourceID) {
1965     const SourceFileInfo &SourceFile = SourceFiles[SourceID];
1966     EmitString(SourceFile.getName()); EOL("Source");
1967     EmitULEB128Bytes(SourceFile.getDirectoryID());  EOL("Directory #");
1968     EmitULEB128Bytes(0);  EOL("Mod date");
1969     EmitULEB128Bytes(0);  EOL("File size");
1970   }
1971   EmitInt8(0); EOL("End of files");
1972   
1973   EmitLabel("line_prolog_end", 0);
1974   
1975   // Emit line information
1976   const std::vector<SourceLineInfo *> &LineInfos = DebugInfo->getSourceLines();
1977   
1978   // Dwarf assumes we start with first line of first source file.
1979   unsigned Source = 1;
1980   unsigned Line = 1;
1981   
1982   // Construct rows of the address, source, line, column matrix.
1983   for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1984     SourceLineInfo *LineInfo = LineInfos[i];
1985     
1986     if (DwarfVerbose) {
1987       unsigned SourceID = LineInfo->getSourceID();
1988       const SourceFileInfo &SourceFile = SourceFiles[SourceID];
1989       unsigned DirectoryID = SourceFile.getDirectoryID();
1990       O << "\t"
1991         << Asm->CommentString << " "
1992         << Directories[DirectoryID]
1993         << SourceFile.getName() << ":"
1994         << LineInfo->getLine() << "\n"; 
1995     }
1996
1997     // Define the line address.
1998     EmitInt8(0); EOL("Extended Op");
1999     EmitInt8(4 + 1); EOL("Op size");
2000     EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
2001     EmitReference("loc",  LineInfo->getLabelID()); EOL("Location label");
2002     
2003     // If change of source, then switch to the new source.
2004     if (Source != LineInfo->getSourceID()) {
2005       Source = LineInfo->getSourceID();
2006       EmitInt8(DW_LNS_set_file); EOL("DW_LNS_set_file");
2007       EmitULEB128Bytes(Source); EOL("New Source");
2008     }
2009     
2010     // If change of line.
2011     if (Line != LineInfo->getLine()) {
2012       // Determine offset.
2013       int Offset = LineInfo->getLine() - Line;
2014       int Delta = Offset - MinLineDelta;
2015       
2016       // Update line.
2017       Line = LineInfo->getLine();
2018       
2019       // If delta is small enough and in range...
2020       if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2021         // ... then use fast opcode.
2022         EmitInt8(Delta - MinLineDelta); EOL("Line Delta");
2023       } else {
2024         // ... otherwise use long hand.
2025         EmitInt8(DW_LNS_advance_line); EOL("DW_LNS_advance_line");
2026         EmitSLEB128Bytes(Offset); EOL("Line Offset");
2027         EmitInt8(DW_LNS_copy); EOL("DW_LNS_copy");
2028       }
2029     } else {
2030       // Copy the previous row (different address or source)
2031       EmitInt8(DW_LNS_copy); EOL("DW_LNS_copy");
2032     }
2033   }
2034
2035   // Define last address.
2036   EmitInt8(0); EOL("Extended Op");
2037   EmitInt8(4 + 1); EOL("Op size");
2038   EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
2039   EmitReference("text_end", 0); EOL("Location label");
2040
2041   // Mark end of matrix.
2042   EmitInt8(0); EOL("DW_LNE_end_sequence");
2043   EmitULEB128Bytes(1);  O << "\n";
2044   EmitInt8(1); O << "\n";
2045   
2046   EmitLabel("line_end", 0);
2047   
2048   O << "\n";
2049 }
2050   
2051 /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
2052 ///
2053 void DwarfWriter::EmitInitialDebugFrame() {
2054   // Start the dwarf frame section.
2055   Asm->SwitchSection(DwarfFrameSection, 0);
2056
2057   EmitDifference("frame_common_end", 0,
2058                  "frame_common_begin", 0);
2059   EOL("Length of Common Information Entry");
2060
2061   EmitLabel("frame_common_begin", 0);
2062   EmitInt32(DW_CIE_ID); EOL("CIE Identifier Tag");
2063   EmitInt8(DW_CIE_VERSION); EOL("CIE Version");
2064   EmitString("");  EOL("CIE Augmentation");
2065   EmitULEB128Bytes(1); EOL("CIE Code Alignment Factor");
2066   EmitSLEB128Bytes(RI->getStackDirection()); EOL("CIE Data Alignment Factor");   
2067   EmitInt8(RI->getDwarfRegNum(RI->getRARegister())); EOL("CIE RA Column");
2068   
2069   std::vector<MachineMove *> Moves;
2070   RI->getInitialFrameState(Moves);
2071   EmitFrameMoves(NULL, 0, Moves);
2072   for (unsigned i = 0, N = Moves.size(); i < N; ++i) delete Moves[i];
2073
2074   EmitAlign(2);
2075   EmitLabel("frame_common_end", 0);
2076   
2077   O << "\n";
2078 }
2079
2080 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2081 /// section.
2082 void DwarfWriter::EmitFunctionDebugFrame() {
2083   // Start the dwarf frame section.
2084   Asm->SwitchSection(DwarfFrameSection, 0);
2085   
2086   EmitDifference("frame_end", SubprogramCount,
2087                  "frame_begin", SubprogramCount);
2088   EOL("Length of Frame Information Entry");
2089   
2090   EmitLabel("frame_begin", SubprogramCount);
2091   
2092   EmitReference("section_frame", 0); EOL("FDE CIE offset");
2093
2094   EmitReference("func_begin", SubprogramCount); EOL("FDE initial location");
2095   EmitDifference("func_end", SubprogramCount,
2096                  "func_begin", SubprogramCount);
2097   EOL("FDE address range");
2098   
2099   std::vector<MachineMove *> &Moves = DebugInfo->getFrameMoves();
2100   
2101   EmitFrameMoves("func_begin", SubprogramCount, Moves);
2102   
2103   EmitAlign(2);
2104   EmitLabel("frame_end", SubprogramCount);
2105
2106   O << "\n";
2107 }
2108
2109 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2110 ///
2111 void DwarfWriter::EmitDebugPubNames() {
2112   // Start the dwarf pubnames section.
2113   Asm->SwitchSection(DwarfPubNamesSection, 0);
2114     
2115   // Process each compile unit.
2116   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2117     CompileUnit *Unit = CompileUnits[i];
2118     
2119     if (Unit->hasContent()) {
2120       EmitDifference("pubnames_end", Unit->getID(),
2121                      "pubnames_begin", Unit->getID());
2122       EOL("Length of Public Names Info");
2123       
2124       EmitLabel("pubnames_begin", Unit->getID());
2125       
2126       EmitInt16(DWARF_VERSION); EOL("DWARF Version");
2127       
2128       EmitReference("info_begin", Unit->getID());
2129       EOL("Offset of Compilation Unit Info");
2130
2131       EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID());
2132       EOL("Compilation Unit Length");
2133       
2134       std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2135       
2136       for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2137                                                   GE = Globals.end();
2138            GI != GE; ++GI) {
2139         const std::string &Name = GI->first;
2140         DIE * Entity = GI->second;
2141         
2142         EmitInt32(Entity->getOffset()); EOL("DIE offset");
2143         EmitString(Name); EOL("External Name");
2144       }
2145     
2146       EmitInt32(0); EOL("End Mark");
2147       EmitLabel("pubnames_end", Unit->getID());
2148     
2149       O << "\n";
2150     }
2151   }
2152 }
2153
2154 /// EmitDebugStr - Emit visible names into a debug str section.
2155 ///
2156 void DwarfWriter::EmitDebugStr() {
2157   // Check to see if it is worth the effort.
2158   if (!StringPool.empty()) {
2159     // Start the dwarf str section.
2160     Asm->SwitchSection(DwarfStrSection, 0);
2161     
2162     // For each of strings in the string pool.
2163     for (unsigned StringID = 1, N = StringPool.size();
2164          StringID <= N; ++StringID) {
2165       // Emit a label for reference from debug information entries.
2166       EmitLabel("string", StringID);
2167       // Emit the string itself.
2168       const std::string &String = StringPool[StringID];
2169       EmitString(String); O << "\n";
2170     }
2171   
2172     O << "\n";
2173   }
2174 }
2175
2176 /// EmitDebugLoc - Emit visible names into a debug loc section.
2177 ///
2178 void DwarfWriter::EmitDebugLoc() {
2179   // Start the dwarf loc section.
2180   Asm->SwitchSection(DwarfLocSection, 0);
2181   
2182   O << "\n";
2183 }
2184
2185 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2186 ///
2187 void DwarfWriter::EmitDebugARanges() {
2188   // Start the dwarf aranges section.
2189   Asm->SwitchSection(DwarfARangesSection, 0);
2190   
2191   // FIXME - Mock up
2192 #if 0
2193   // Process each compile unit.
2194   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2195     CompileUnit *Unit = CompileUnits[i];
2196     
2197     if (Unit->hasContent()) {
2198       // Don't include size of length
2199       EmitInt32(0x1c); EOL("Length of Address Ranges Info");
2200       
2201       EmitInt16(DWARF_VERSION); EOL("Dwarf Version");
2202       
2203       EmitReference("info_begin", Unit->getID());
2204       EOL("Offset of Compilation Unit Info");
2205
2206       EmitInt8(AddressSize); EOL("Size of Address");
2207
2208       EmitInt8(0); EOL("Size of Segment Descriptor");
2209
2210       EmitInt16(0);  EOL("Pad (1)");
2211       EmitInt16(0);  EOL("Pad (2)");
2212
2213       // Range 1
2214       EmitReference("text_begin", 0); EOL("Address");
2215       EmitDifference("text_end", 0, "text_begin", 0); EOL("Length");
2216
2217       EmitInt32(0); EOL("EOM (1)");
2218       EmitInt32(0); EOL("EOM (2)");
2219       
2220       O << "\n";
2221     }
2222   }
2223 #endif
2224 }
2225
2226 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2227 ///
2228 void DwarfWriter::EmitDebugRanges() {
2229   // Start the dwarf ranges section.
2230   Asm->SwitchSection(DwarfRangesSection, 0);
2231   
2232   O << "\n";
2233 }
2234
2235 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2236 ///
2237 void DwarfWriter::EmitDebugMacInfo() {
2238   // Start the dwarf macinfo section.
2239   Asm->SwitchSection(DwarfMacInfoSection, 0);
2240   
2241   O << "\n";
2242 }
2243
2244 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2245 /// header file.
2246 void DwarfWriter::ConstructCompileUnitDIEs() {
2247   const UniqueVector<CompileUnitDesc *> CUW = DebugInfo->getCompileUnits();
2248   
2249   for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2250     CompileUnit *Unit = NewCompileUnit(CUW[i], i);
2251     CompileUnits.push_back(Unit);
2252   }
2253 }
2254
2255 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible global
2256 /// variables.
2257 void DwarfWriter::ConstructGlobalDIEs() {
2258   std::vector<GlobalVariableDesc *> GlobalVariables =
2259       DebugInfo->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2260   
2261   for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2262     GlobalVariableDesc *GVD = GlobalVariables[i];
2263     NewGlobalVariable(GVD);
2264   }
2265 }
2266
2267 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2268 /// subprograms.
2269 void DwarfWriter::ConstructSubprogramDIEs() {
2270   std::vector<SubprogramDesc *> Subprograms =
2271       DebugInfo->getAnchoredDescriptors<SubprogramDesc>(*M);
2272   
2273   for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2274     SubprogramDesc *SPD = Subprograms[i];
2275     NewSubprogram(SPD);
2276   }
2277 }
2278
2279 /// ShouldEmitDwarf - Determine if Dwarf declarations should be made.
2280 ///
2281 bool DwarfWriter::ShouldEmitDwarf() {
2282   // Check if debug info is present.
2283   if (!DebugInfo || !DebugInfo->hasInfo()) return false;
2284   
2285   // Make sure initial declarations are made.
2286   if (!didInitial) {
2287     EmitInitial();
2288   
2289     // Emit common frame information.
2290     EmitInitialDebugFrame();
2291   
2292     // Create all the compile unit DIEs.
2293     ConstructCompileUnitDIEs();
2294     
2295     // Create DIEs for each of the externally visible global variables.
2296     ConstructGlobalDIEs();
2297
2298     // Create DIEs for each of the externally visible subprograms.
2299     ConstructSubprogramDIEs();
2300
2301     didInitial = true;
2302   }
2303   
2304   // Okay to emit.
2305   return true;
2306 }
2307
2308 //===----------------------------------------------------------------------===//
2309 // Main entry points.
2310 //
2311   
2312 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A)
2313 : O(OS)
2314 , Asm(A)
2315 , TD(Asm->TM.getTargetData())
2316 , RI(Asm->TM.getRegisterInfo())
2317 , M(NULL)
2318 , MF(NULL)
2319 , DebugInfo(NULL)
2320 , didInitial(false)
2321 , SubprogramCount(0)
2322 , CompileUnits()
2323 , Abbreviations()
2324 , StringPool()
2325 , DescToUnitMap()
2326 , DescToDieMap()
2327 , TypeToDieMap()
2328 , AddressSize(sizeof(int32_t))
2329 , hasLEB128(false)
2330 , hasDotLoc(false)
2331 , hasDotFile(false)
2332 , needsSet(false)
2333 , DwarfAbbrevSection(".debug_abbrev")
2334 , DwarfInfoSection(".debug_info")
2335 , DwarfLineSection(".debug_line")
2336 , DwarfFrameSection(".debug_frame")
2337 , DwarfPubNamesSection(".debug_pubnames")
2338 , DwarfPubTypesSection(".debug_pubtypes")
2339 , DwarfStrSection(".debug_str")
2340 , DwarfLocSection(".debug_loc")
2341 , DwarfARangesSection(".debug_aranges")
2342 , DwarfRangesSection(".debug_ranges")
2343 , DwarfMacInfoSection(".debug_macinfo")
2344 , TextSection(".text")
2345 , DataSection(".data")
2346 {}
2347 DwarfWriter::~DwarfWriter() {
2348   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2349     delete CompileUnits[i];
2350   }
2351 }
2352
2353 /// SetDebugInfo - Set DebugInfo when it's known that pass manager has
2354 /// created it.  Set by the target AsmPrinter.
2355 void DwarfWriter::SetDebugInfo(MachineDebugInfo *DI) {
2356   DebugInfo = DI;
2357 }
2358
2359 /// BeginModule - Emit all Dwarf sections that should come prior to the content.
2360 ///
2361 void DwarfWriter::BeginModule(Module *M) {
2362   this->M = M;
2363   
2364   if (!ShouldEmitDwarf()) return;
2365   EOL("Dwarf Begin Module");
2366 }
2367
2368 /// EndModule - Emit all Dwarf sections that should come after the content.
2369 ///
2370 void DwarfWriter::EndModule() {
2371   if (!ShouldEmitDwarf()) return;
2372   EOL("Dwarf End Module");
2373   
2374   // Standard sections final addresses.
2375   Asm->SwitchSection(TextSection, 0);
2376   EmitLabel("text_end", 0);
2377   Asm->SwitchSection(DataSection, 0);
2378   EmitLabel("data_end", 0);
2379   
2380   // Compute DIE offsets and sizes.
2381   SizeAndOffsets();
2382   
2383   // Emit all the DIEs into a debug info section
2384   EmitDebugInfo();
2385   
2386   // Corresponding abbreviations into a abbrev section.
2387   EmitAbbreviations();
2388   
2389   // Emit source line correspondence into a debug line section.
2390   EmitDebugLines();
2391   
2392   // Emit info into a debug pubnames section.
2393   EmitDebugPubNames();
2394   
2395   // Emit info into a debug str section.
2396   EmitDebugStr();
2397   
2398   // Emit info into a debug loc section.
2399   EmitDebugLoc();
2400   
2401   // Emit info into a debug aranges section.
2402   EmitDebugARanges();
2403   
2404   // Emit info into a debug ranges section.
2405   EmitDebugRanges();
2406   
2407   // Emit info into a debug macinfo section.
2408   EmitDebugMacInfo();
2409 }
2410
2411 /// BeginFunction - Gather pre-function debug information.
2412 ///
2413 void DwarfWriter::BeginFunction(MachineFunction *MF) {
2414   this->MF = MF;
2415   
2416   // Begin accumulating function debug information.
2417   DebugInfo->BeginFunction(MF);
2418   
2419   if (!ShouldEmitDwarf()) return;
2420   EOL("Dwarf Begin Function");
2421   
2422   // Define begin label for subprogram.
2423   Asm->SwitchSection(TextSection, 0);
2424   EmitLabel("func_begin", ++SubprogramCount);
2425 }
2426
2427 /// EndFunction - Gather and emit post-function debug information.
2428 ///
2429 void DwarfWriter::EndFunction() {
2430   if (!ShouldEmitDwarf()) return;
2431   EOL("Dwarf End Function");
2432   
2433   // Define end label for subprogram.
2434   Asm->SwitchSection(TextSection, 0);
2435   EmitLabel("func_end", SubprogramCount);
2436   
2437   // Construct scopes for subprogram.
2438   ConstructRootScope(DebugInfo->getRootScope());
2439   
2440   // Emit function frame information.
2441   EmitFunctionDebugFrame();
2442   
2443   // Clear function debug information.
2444   DebugInfo->EndFunction();
2445 }