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