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