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