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