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