1. Remove dwarf-verbose option (now asm-verbose.)
[oota-llvm.git] / lib / CodeGen / DwarfWriter.cpp
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/DwarfWriter.h"
15
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/UniqueVector.h"
19 #include "llvm/Module.h"
20 #include "llvm/Type.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineDebugInfo.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineLocation.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/DataTypes.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/MRegisterInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34 #include <ostream>
35 #include <string>
36 using namespace llvm;
37 using namespace llvm::dwarf;
38
39 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 Dwarf &DW) 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 Dwarf &DW, unsigned Form) const = 0;
317   
318   /// SizeOf - Return the size of a value in bytes.
319   ///
320   virtual unsigned SizeOf(const Dwarf &DW, 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 Dwarf &DW, unsigned Form) const;
367   
368   /// SizeOf - Determine size of integer value in bytes.
369   ///
370   virtual unsigned SizeOf(const Dwarf &DW, 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 Dwarf &DW, unsigned Form) const;
404   
405   /// SizeOf - Determine size of string value in bytes.
406   ///
407   virtual unsigned SizeOf(const Dwarf &DW, 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 Dwarf &DW, unsigned Form) const;
443   
444   /// SizeOf - Determine size of label value in bytes.
445   ///
446   virtual unsigned SizeOf(const Dwarf &DW, 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 Dwarf &DW, unsigned Form) const;
481   
482   /// SizeOf - Determine size of label value in bytes.
483   ///
484   virtual unsigned SizeOf(const Dwarf &DW, 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 Dwarf &DW, unsigned Form) const;
519   
520   /// SizeOf - Determine size of delta value in bytes.
521   ///
522   virtual unsigned SizeOf(const Dwarf &DW, 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 Dwarf &DW, unsigned Form) const;
561   
562   /// SizeOf - Determine size of debug information entry in bytes.
563   ///
564   virtual unsigned SizeOf(const Dwarf &DW, 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(Dwarf &DW);
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 Dwarf &DW, unsigned Form) const;
626   
627   /// SizeOf - Determine size of block data in bytes.
628   ///
629   virtual unsigned SizeOf(const Dwarf &DW, 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 *DD) {
724     return DescToDieMap[DD];
725   }
726   
727   /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
728   /// specified debug descriptor.
729   DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DD) {
730     return DescToDIEntryMap[DD];
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 Dwarf debug and exception handling directives. 
754 ///
755 class Dwarf {
756
757 private:
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   /// DebugInfo - Collected debug information.
790   ///
791   MachineDebugInfo *DebugInfo;
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   //===--------------------------------------------------------------------===//
806   // Attributes used to construct specific Dwarf sections.
807   //
808   
809   /// CompileUnits - All the compile units involved in this build.  The index
810   /// of each entry in this vector corresponds to the sources in DebugInfo.
811   std::vector<CompileUnit *> CompileUnits;
812   
813   /// AbbreviationsSet - Used to uniquely define abbreviations.
814   ///
815   FoldingSet<DIEAbbrev> AbbreviationsSet;
816
817   /// Abbreviations - A list of all the unique abbreviations in use.
818   ///
819   std::vector<DIEAbbrev *> Abbreviations;
820   
821   /// ValuesSet - Used to uniquely define values.
822   ///
823   FoldingSet<DIEValue> ValuesSet;
824   
825   /// Values - A list of all the unique values in use.
826   ///
827   std::vector<DIEValue *> Values;
828   
829   /// StringPool - A UniqueVector of strings used by indirect references.
830   ///
831   UniqueVector<std::string> StringPool;
832
833   /// UnitMap - Map debug information descriptor to compile unit.
834   ///
835   std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
836   
837   /// SectionMap - Provides a unique id per text section.
838   ///
839   UniqueVector<std::string> SectionMap;
840   
841   /// SectionSourceLines - Tracks line numbers per text section.
842   ///
843   std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
844
845
846 public:
847
848   //===--------------------------------------------------------------------===//
849   // Accessors.
850   //
851   AsmPrinter *getAsm() const { return Asm; }
852
853   /// PrintLabelName - Print label name in form used by Dwarf writer.
854   ///
855   void PrintLabelName(DWLabel Label) const {
856     PrintLabelName(Label.Tag, Label.Number);
857   }
858   void PrintLabelName(const char *Tag, unsigned Number) const {
859     O << TAI->getPrivateGlobalPrefix()
860       << "debug_"
861       << Tag;
862     if (Number) O << Number;
863   }
864   
865   /// EmitLabel - Emit location label for internal use by Dwarf.
866   ///
867   void EmitLabel(DWLabel Label) const {
868     EmitLabel(Label.Tag, Label.Number);
869   }
870   void EmitLabel(const char *Tag, unsigned Number) const {
871     PrintLabelName(Tag, Number);
872     O << ":\n";
873   }
874   
875   /// EmitReference - Emit a reference to a label.
876   ///
877   void EmitReference(DWLabel Label) const {
878     EmitReference(Label.Tag, Label.Number);
879   }
880   void EmitReference(const char *Tag, unsigned Number) const {
881     if (TAI->getAddressSize() == 4)
882       O << TAI->getData32bitsDirective();
883     else
884       O << TAI->getData64bitsDirective();
885       
886     PrintLabelName(Tag, Number);
887   }
888   void EmitReference(const std::string &Name) const {
889     if (TAI->getAddressSize() == 4)
890       O << TAI->getData32bitsDirective();
891     else
892       O << TAI->getData64bitsDirective();
893       
894     O << Name;
895   }
896
897   /// EmitDifference - Emit the difference between two labels.  Some
898   /// assemblers do not behave with absolute expressions with data directives,
899   /// so there is an option (needsSet) to use an intermediary set expression.
900   void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
901                       bool IsSmall = false) const {
902     EmitDifference(LabelHi.Tag, LabelHi.Number,
903                    LabelLo.Tag, LabelLo.Number,
904                    IsSmall);
905   }
906   void EmitDifference(const char *TagHi, unsigned NumberHi,
907                       const char *TagLo, unsigned NumberLo,
908                       bool IsSmall = false) const {
909     if (TAI->needsSet()) {
910       static unsigned SetCounter = 0;
911       
912       O << "\t.set\t";
913       PrintLabelName("set", SetCounter);
914       O << ",";
915       PrintLabelName(TagHi, NumberHi);
916       O << "-";
917       PrintLabelName(TagLo, NumberLo);
918       O << "\n";
919       
920       if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
921         O << TAI->getData32bitsDirective();
922       else
923         O << TAI->getData64bitsDirective();
924         
925       PrintLabelName("set", SetCounter);
926       
927       ++SetCounter;
928     } else {
929       if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
930         O << TAI->getData32bitsDirective();
931       else
932         O << TAI->getData64bitsDirective();
933         
934       PrintLabelName(TagHi, NumberHi);
935       O << "-";
936       PrintLabelName(TagLo, NumberLo);
937     }
938   }
939                       
940   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
941   ///  
942   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
943     // Profile the node so that we can make it unique.
944     FoldingSetNodeID ID;
945     Abbrev.Profile(ID);
946     
947     // Check the set for priors.
948     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
949     
950     // If it's newly added.
951     if (InSet == &Abbrev) {
952       // Add to abbreviation list. 
953       Abbreviations.push_back(&Abbrev);
954       // Assign the vector position + 1 as its number.
955       Abbrev.setNumber(Abbreviations.size());
956     } else {
957       // Assign existing abbreviation number.
958       Abbrev.setNumber(InSet->getNumber());
959     }
960   }
961
962   /// NewString - Add a string to the constant pool and returns a label.
963   ///
964   DWLabel NewString(const std::string &String) {
965     unsigned StringID = StringPool.insert(String);
966     return DWLabel("string", StringID);
967   }
968   
969   /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
970   /// entry.
971   DIEntry *NewDIEntry(DIE *Entry = NULL) {
972     DIEntry *Value;
973     
974     if (Entry) {
975       FoldingSetNodeID ID;
976       DIEntry::Profile(ID, Entry);
977       void *Where;
978       Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
979       
980       if (Value) return Value;
981       
982       Value = new DIEntry(Entry);
983       ValuesSet.InsertNode(Value, Where);
984     } else {
985       Value = new DIEntry(Entry);
986     }
987     
988     Values.push_back(Value);
989     return Value;
990   }
991   
992   /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
993   ///
994   void SetDIEntry(DIEntry *Value, DIE *Entry) {
995     Value->Entry = Entry;
996     // Add to values set if not already there.  If it is, we merely have a
997     // duplicate in the values list (no harm.)
998     ValuesSet.GetOrInsertNode(Value);
999   }
1000
1001   /// AddUInt - Add an unsigned integer attribute data and value.
1002   ///
1003   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1004     if (!Form) Form = DIEInteger::BestForm(false, Integer);
1005
1006     FoldingSetNodeID ID;
1007     DIEInteger::Profile(ID, Integer);
1008     void *Where;
1009     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1010     if (!Value) {
1011       Value = new DIEInteger(Integer);
1012       ValuesSet.InsertNode(Value, Where);
1013       Values.push_back(Value);
1014     }
1015   
1016     Die->AddValue(Attribute, Form, Value);
1017   }
1018       
1019   /// AddSInt - Add an signed integer attribute data and value.
1020   ///
1021   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1022     if (!Form) Form = DIEInteger::BestForm(true, Integer);
1023
1024     FoldingSetNodeID ID;
1025     DIEInteger::Profile(ID, (uint64_t)Integer);
1026     void *Where;
1027     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1028     if (!Value) {
1029       Value = new DIEInteger(Integer);
1030       ValuesSet.InsertNode(Value, Where);
1031       Values.push_back(Value);
1032     }
1033   
1034     Die->AddValue(Attribute, Form, Value);
1035   }
1036       
1037   /// AddString - Add a std::string attribute data and value.
1038   ///
1039   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1040                  const std::string &String) {
1041     FoldingSetNodeID ID;
1042     DIEString::Profile(ID, String);
1043     void *Where;
1044     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1045     if (!Value) {
1046       Value = new DIEString(String);
1047       ValuesSet.InsertNode(Value, Where);
1048       Values.push_back(Value);
1049     }
1050   
1051     Die->AddValue(Attribute, Form, Value);
1052   }
1053       
1054   /// AddLabel - Add a Dwarf label attribute data and value.
1055   ///
1056   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1057                      const DWLabel &Label) {
1058     FoldingSetNodeID ID;
1059     DIEDwarfLabel::Profile(ID, Label);
1060     void *Where;
1061     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1062     if (!Value) {
1063       Value = new DIEDwarfLabel(Label);
1064       ValuesSet.InsertNode(Value, Where);
1065       Values.push_back(Value);
1066     }
1067   
1068     Die->AddValue(Attribute, Form, Value);
1069   }
1070       
1071   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1072   ///
1073   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1074                       const std::string &Label) {
1075     FoldingSetNodeID ID;
1076     DIEObjectLabel::Profile(ID, Label);
1077     void *Where;
1078     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1079     if (!Value) {
1080       Value = new DIEObjectLabel(Label);
1081       ValuesSet.InsertNode(Value, Where);
1082       Values.push_back(Value);
1083     }
1084   
1085     Die->AddValue(Attribute, Form, Value);
1086   }
1087       
1088   /// AddDelta - Add a label delta attribute data and value.
1089   ///
1090   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1091                           const DWLabel &Hi, const DWLabel &Lo) {
1092     FoldingSetNodeID ID;
1093     DIEDelta::Profile(ID, Hi, Lo);
1094     void *Where;
1095     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1096     if (!Value) {
1097       Value = new DIEDelta(Hi, Lo);
1098       ValuesSet.InsertNode(Value, Where);
1099       Values.push_back(Value);
1100     }
1101   
1102     Die->AddValue(Attribute, Form, Value);
1103   }
1104       
1105   /// AddDIEntry - Add a DIE attribute data and value.
1106   ///
1107   void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1108     Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1109   }
1110
1111   /// AddBlock - Add block data.
1112   ///
1113   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1114     Block->ComputeSize(*this);
1115     FoldingSetNodeID ID;
1116     Block->Profile(ID);
1117     void *Where;
1118     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1119     if (!Value) {
1120       Value = Block;
1121       ValuesSet.InsertNode(Value, Where);
1122       Values.push_back(Value);
1123     } else {
1124       delete Block;
1125     }
1126   
1127     Die->AddValue(Attribute, Block->BestForm(), Value);
1128   }
1129
1130 private:
1131
1132   /// AddSourceLine - Add location information to specified debug information
1133   /// entry.
1134   void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1135     if (File && Line) {
1136       CompileUnit *FileUnit = FindCompileUnit(File);
1137       unsigned FileID = FileUnit->getID();
1138       AddUInt(Die, DW_AT_decl_file, 0, FileID);
1139       AddUInt(Die, DW_AT_decl_line, 0, Line);
1140     }
1141   }
1142
1143   /// AddAddress - Add an address attribute to a die based on the location
1144   /// provided.
1145   void AddAddress(DIE *Die, unsigned Attribute,
1146                             const MachineLocation &Location) {
1147     unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1148     DIEBlock *Block = new DIEBlock();
1149     
1150     if (Location.isRegister()) {
1151       if (Reg < 32) {
1152         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1153       } else {
1154         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1155         AddUInt(Block, 0, DW_FORM_udata, Reg);
1156       }
1157     } else {
1158       if (Reg < 32) {
1159         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1160       } else {
1161         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1162         AddUInt(Block, 0, DW_FORM_udata, Reg);
1163       }
1164       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1165     }
1166     
1167     AddBlock(Die, Attribute, 0, Block);
1168   }
1169   
1170   /// AddBasicType - Add a new basic type attribute to the specified entity.
1171   ///
1172   void AddBasicType(DIE *Entity, CompileUnit *Unit,
1173                     const std::string &Name,
1174                     unsigned Encoding, unsigned Size) {
1175     DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1176     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1177   }
1178   
1179   /// ConstructBasicType - Construct a new basic type.
1180   ///
1181   DIE *ConstructBasicType(CompileUnit *Unit,
1182                           const std::string &Name,
1183                           unsigned Encoding, unsigned Size) {
1184     DIE Buffer(DW_TAG_base_type);
1185     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1186     AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1187     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1188     return Unit->AddDie(Buffer);
1189   }
1190   
1191   /// AddPointerType - Add a new pointer type attribute to the specified entity.
1192   ///
1193   void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1194     DIE *Die = ConstructPointerType(Unit, Name);
1195     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1196   }
1197   
1198   /// ConstructPointerType - Construct a new pointer type.
1199   ///
1200   DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1201     DIE Buffer(DW_TAG_pointer_type);
1202     AddUInt(&Buffer, DW_AT_byte_size, 0, TAI->getAddressSize());
1203     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1204     return Unit->AddDie(Buffer);
1205   }
1206   
1207   /// AddType - Add a new type attribute to the specified entity.
1208   ///
1209   void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1210     if (!TyDesc) {
1211       AddBasicType(Entity, Unit, "", DW_ATE_signed, 4);
1212     } else {
1213       // Check for pre-existence.
1214       DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1215       
1216       // If it exists then use the existing value.
1217       if (Slot) {
1218         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1219         return;
1220       }
1221       
1222       if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1223         // FIXME - Not sure why programs and variables are coming through here.
1224         // Short cut for handling subprogram types (not really a TyDesc.)
1225         AddPointerType(Entity, Unit, SubprogramTy->getName());
1226       } else if (GlobalVariableDesc *GlobalTy =
1227                                          dyn_cast<GlobalVariableDesc>(TyDesc)) {
1228         // FIXME - Not sure why programs and variables are coming through here.
1229         // Short cut for handling global variable types (not really a TyDesc.)
1230         AddPointerType(Entity, Unit, GlobalTy->getName());
1231       } else {  
1232         // Set up proxy.
1233         Slot = NewDIEntry();
1234         
1235         // Construct type.
1236         DIE Buffer(DW_TAG_base_type);
1237         ConstructType(Buffer, TyDesc, Unit);
1238         
1239         // Add debug information entry to entity and unit.
1240         DIE *Die = Unit->AddDie(Buffer);
1241         SetDIEntry(Slot, Die);
1242         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1243       }
1244     }
1245   }
1246   
1247   /// ConstructType - Adds all the required attributes to the type.
1248   ///
1249   void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1250     // Get core information.
1251     const std::string &Name = TyDesc->getName();
1252     uint64_t Size = TyDesc->getSize() >> 3;
1253     
1254     if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1255       // Fundamental types like int, float, bool
1256       Buffer.setTag(DW_TAG_base_type);
1257       AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BasicTy->getEncoding());
1258     } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1259       // Fetch tag.
1260       unsigned Tag = DerivedTy->getTag();
1261       // FIXME - Workaround for templates.
1262       if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1263       // Pointers, typedefs et al. 
1264       Buffer.setTag(Tag);
1265       // Map to main type, void will not have a type.
1266       if (TypeDesc *FromTy = DerivedTy->getFromType())
1267         AddType(&Buffer, FromTy, Unit);
1268     } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1269       // Fetch tag.
1270       unsigned Tag = CompTy->getTag();
1271       
1272       // Set tag accordingly.
1273       if (Tag == DW_TAG_vector_type)
1274         Buffer.setTag(DW_TAG_array_type);
1275       else 
1276         Buffer.setTag(Tag);
1277
1278       std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1279       
1280       switch (Tag) {
1281       case DW_TAG_vector_type:
1282         AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1283         // Fall thru
1284       case DW_TAG_array_type: {
1285         // Add element type.
1286         if (TypeDesc *FromTy = CompTy->getFromType())
1287           AddType(&Buffer, FromTy, Unit);
1288         
1289         // Don't emit size attribute.
1290         Size = 0;
1291         
1292         // Construct an anonymous type for index type.
1293         DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed, 4);
1294       
1295         // Add subranges to array type.
1296         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1297           SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1298           int64_t Lo = SRD->getLo();
1299           int64_t Hi = SRD->getHi();
1300           DIE *Subrange = new DIE(DW_TAG_subrange_type);
1301           
1302           // If a range is available.
1303           if (Lo != Hi) {
1304             AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1305             // Only add low if non-zero.
1306             if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1307             AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1308           }
1309           
1310           Buffer.AddChild(Subrange);
1311         }
1312         break;
1313       }
1314       case DW_TAG_structure_type:
1315       case DW_TAG_union_type: {
1316         // Add elements to structure type.
1317         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1318           DebugInfoDesc *Element = Elements[i];
1319           
1320           if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1321             // Add field or base class.
1322             
1323             unsigned Tag = MemberDesc->getTag();
1324           
1325             // Extract the basic information.
1326             const std::string &Name = MemberDesc->getName();
1327             uint64_t Size = MemberDesc->getSize();
1328             uint64_t Align = MemberDesc->getAlign();
1329             uint64_t Offset = MemberDesc->getOffset();
1330        
1331             // Construct member debug information entry.
1332             DIE *Member = new DIE(Tag);
1333             
1334             // Add name if not "".
1335             if (!Name.empty())
1336               AddString(Member, DW_AT_name, DW_FORM_string, Name);
1337             // Add location if available.
1338             AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1339             
1340             // Most of the time the field info is the same as the members.
1341             uint64_t FieldSize = Size;
1342             uint64_t FieldAlign = Align;
1343             uint64_t FieldOffset = Offset;
1344             
1345             // Set the member type.
1346             TypeDesc *FromTy = MemberDesc->getFromType();
1347             AddType(Member, FromTy, Unit);
1348             
1349             // Walk up typedefs until a real size is found.
1350             while (FromTy) {
1351               if (FromTy->getTag() != DW_TAG_typedef) {
1352                 FieldSize = FromTy->getSize();
1353                 FieldAlign = FromTy->getSize();
1354                 break;
1355               }
1356               
1357               FromTy = dyn_cast<DerivedTypeDesc>(FromTy)->getFromType();
1358             }
1359             
1360             // Unless we have a bit field.
1361             if (Tag == DW_TAG_member && FieldSize != Size) {
1362               // Construct the alignment mask.
1363               uint64_t AlignMask = ~(FieldAlign - 1);
1364               // Determine the high bit + 1 of the declared size.
1365               uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1366               // Work backwards to determine the base offset of the field.
1367               FieldOffset = HiMark - FieldSize;
1368               // Now normalize offset to the field.
1369               Offset -= FieldOffset;
1370               
1371               // Maybe we need to work from the other end.
1372               if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1373               
1374               // Add size and offset.
1375               AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1376               AddUInt(Member, DW_AT_bit_size, 0, Size);
1377               AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1378             }
1379             
1380             // Add computation for offset.
1381             DIEBlock *Block = new DIEBlock();
1382             AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1383             AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1384             AddBlock(Member, DW_AT_data_member_location, 0, Block);
1385
1386             // Add accessibility (public default unless is base class.
1387             if (MemberDesc->isProtected()) {
1388               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1389             } else if (MemberDesc->isPrivate()) {
1390               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1391             } else if (Tag == DW_TAG_inheritance) {
1392               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1393             }
1394             
1395             Buffer.AddChild(Member);
1396           } else if (GlobalVariableDesc *StaticDesc =
1397                                         dyn_cast<GlobalVariableDesc>(Element)) {
1398             // Add static member.
1399             
1400             // Construct member debug information entry.
1401             DIE *Static = new DIE(DW_TAG_variable);
1402             
1403             // Add name and mangled name.
1404             const std::string &Name = StaticDesc->getName();
1405             const std::string &LinkageName = StaticDesc->getLinkageName();
1406             AddString(Static, DW_AT_name, DW_FORM_string, Name);
1407             if (!LinkageName.empty()) {
1408               AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1409                                 LinkageName);
1410             }
1411             
1412             // Add location.
1413             AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1414            
1415             // Add type.
1416             if (TypeDesc *StaticTy = StaticDesc->getType())
1417               AddType(Static, StaticTy, Unit);
1418             
1419             // Add flags.
1420             if (!StaticDesc->isStatic())
1421               AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1422             AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1423             
1424             Buffer.AddChild(Static);
1425           } else if (SubprogramDesc *MethodDesc =
1426                                             dyn_cast<SubprogramDesc>(Element)) {
1427             // Add member function.
1428             
1429             // Construct member debug information entry.
1430             DIE *Method = new DIE(DW_TAG_subprogram);
1431            
1432             // Add name and mangled name.
1433             const std::string &Name = MethodDesc->getName();
1434             const std::string &LinkageName = MethodDesc->getLinkageName();
1435             
1436             AddString(Method, DW_AT_name, DW_FORM_string, Name);            
1437             bool IsCTor = TyDesc->getName() == Name;
1438             
1439             if (!LinkageName.empty()) {
1440               AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1441                                 LinkageName);
1442             }
1443             
1444             // Add location.
1445             AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1446            
1447             // Add type.
1448             if (CompositeTypeDesc *MethodTy =
1449                    dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1450               // Get argument information.
1451               std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1452              
1453               // If not a ctor.
1454               if (!IsCTor) {
1455                 // Add return type.
1456                 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1457               }
1458               
1459               // Add arguments.
1460               for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1461                 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1462                 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1463                 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1464                 Method->AddChild(Arg);
1465               }
1466             }
1467
1468             // Add flags.
1469             if (!MethodDesc->isStatic())
1470               AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1471             AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1472               
1473             Buffer.AddChild(Method);
1474           }
1475         }
1476         break;
1477       }
1478       case DW_TAG_enumeration_type: {
1479         // Add enumerators to enumeration type.
1480         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1481           EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1482           const std::string &Name = ED->getName();
1483           int64_t Value = ED->getValue();
1484           DIE *Enumerator = new DIE(DW_TAG_enumerator);
1485           AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1486           AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1487           Buffer.AddChild(Enumerator);
1488         }
1489
1490         break;
1491       }
1492       case DW_TAG_subroutine_type: {
1493         // Add prototype flag.
1494         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1495         // Add return type.
1496         AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1497         
1498         // Add arguments.
1499         for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1500           DIE *Arg = new DIE(DW_TAG_formal_parameter);
1501           AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1502           Buffer.AddChild(Arg);
1503         }
1504         
1505         break;
1506       }
1507       default: break;
1508       }
1509     }
1510    
1511     // Add size if non-zero (derived types don't have a size.)
1512     if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1513     // Add name if not anonymous or intermediate type.
1514     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1515     // Add source line info if available.
1516     AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1517   }
1518
1519   /// NewCompileUnit - Create new compile unit and it's debug information entry.
1520   ///
1521   CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1522     // Construct debug information entry.
1523     DIE *Die = new DIE(DW_TAG_compile_unit);
1524     AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1525                                                   DWLabel("section_line", 0));
1526     AddString(Die, DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
1527     AddUInt  (Die, DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
1528     AddString(Die, DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
1529     AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
1530     
1531     // Construct compile unit.
1532     CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1533     
1534     // Add Unit to compile unit map.
1535     DescToUnitMap[UnitDesc] = Unit;
1536     
1537     return Unit;
1538   }
1539
1540   /// GetBaseCompileUnit - Get the main compile unit.
1541   ///
1542   CompileUnit *GetBaseCompileUnit() const {
1543     CompileUnit *Unit = CompileUnits[0];
1544     assert(Unit && "Missing compile unit.");
1545     return Unit;
1546   }
1547
1548   /// FindCompileUnit - Get the compile unit for the given descriptor.
1549   ///
1550   CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1551     CompileUnit *Unit = DescToUnitMap[UnitDesc];
1552     assert(Unit && "Missing compile unit.");
1553     return Unit;
1554   }
1555
1556   /// NewGlobalVariable - Add a new global variable DIE.
1557   ///
1558   DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1559     // Get the compile unit context.
1560     CompileUnitDesc *UnitDesc =
1561       static_cast<CompileUnitDesc *>(GVD->getContext());
1562     CompileUnit *Unit = GetBaseCompileUnit();
1563
1564     // Check for pre-existence.
1565     DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1566     if (Slot) return Slot;
1567     
1568     // Get the global variable itself.
1569     GlobalVariable *GV = GVD->getGlobalVariable();
1570
1571     const std::string &Name = GVD->getName();
1572     const std::string &FullName = GVD->getFullName();
1573     const std::string &LinkageName = GVD->getLinkageName();
1574     // Create the global's variable DIE.
1575     DIE *VariableDie = new DIE(DW_TAG_variable);
1576     AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1577     if (!LinkageName.empty()) {
1578       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1579                              LinkageName);
1580     }
1581     AddType(VariableDie, GVD->getType(), Unit);
1582     if (!GVD->isStatic())
1583       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1584     
1585     // Add source line info if available.
1586     AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1587     
1588     // Add address.
1589     DIEBlock *Block = new DIEBlock();
1590     AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1591     AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1592     AddBlock(VariableDie, DW_AT_location, 0, Block);
1593     
1594     // Add to map.
1595     Slot = VariableDie;
1596    
1597     // Add to context owner.
1598     Unit->getDie()->AddChild(VariableDie);
1599     
1600     // Expose as global.
1601     // FIXME - need to check external flag.
1602     Unit->AddGlobal(FullName, VariableDie);
1603     
1604     return VariableDie;
1605   }
1606
1607   /// NewSubprogram - Add a new subprogram DIE.
1608   ///
1609   DIE *NewSubprogram(SubprogramDesc *SPD) {
1610     // Get the compile unit context.
1611     CompileUnitDesc *UnitDesc =
1612       static_cast<CompileUnitDesc *>(SPD->getContext());
1613     CompileUnit *Unit = GetBaseCompileUnit();
1614
1615     // Check for pre-existence.
1616     DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1617     if (Slot) return Slot;
1618     
1619     // Gather the details (simplify add attribute code.)
1620     const std::string &Name = SPD->getName();
1621     const std::string &FullName = SPD->getFullName();
1622     const std::string &LinkageName = SPD->getLinkageName();
1623                                       
1624     DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1625     AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1626     if (!LinkageName.empty()) {
1627       AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1628                                LinkageName);
1629     }
1630     if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1631     if (!SPD->isStatic())
1632       AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1633     AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1634     
1635     // Add source line info if available.
1636     AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1637
1638     // Add to map.
1639     Slot = SubprogramDie;
1640    
1641     // Add to context owner.
1642     Unit->getDie()->AddChild(SubprogramDie);
1643     
1644     // Expose as global.
1645     Unit->AddGlobal(FullName, SubprogramDie);
1646     
1647     return SubprogramDie;
1648   }
1649
1650   /// NewScopeVariable - Create a new scope variable.
1651   ///
1652   DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1653     // Get the descriptor.
1654     VariableDesc *VD = DV->getDesc();
1655
1656     // Translate tag to proper Dwarf tag.  The result variable is dropped for
1657     // now.
1658     unsigned Tag;
1659     switch (VD->getTag()) {
1660     case DW_TAG_return_variable:  return NULL;
1661     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
1662     case DW_TAG_auto_variable:    // fall thru
1663     default:                      Tag = DW_TAG_variable; break;
1664     }
1665
1666     // Define variable debug information entry.
1667     DIE *VariableDie = new DIE(Tag);
1668     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1669
1670     // Add source line info if available.
1671     AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1672     
1673     // Add variable type.
1674     AddType(VariableDie, VD->getType(), Unit); 
1675     
1676     // Add variable address.
1677     MachineLocation Location;
1678     RI->getLocation(*MF, DV->getFrameIndex(), Location);
1679     AddAddress(VariableDie, DW_AT_location, Location);
1680
1681     return VariableDie;
1682   }
1683
1684   /// ConstructScope - Construct the components of a scope.
1685   ///
1686   void ConstructScope(DebugScope *ParentScope,
1687                       unsigned ParentStartID, unsigned ParentEndID,
1688                       DIE *ParentDie, CompileUnit *Unit) {
1689     // Add variables to scope.
1690     std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1691     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1692       DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1693       if (VariableDie) ParentDie->AddChild(VariableDie);
1694     }
1695     
1696     // Add nested scopes.
1697     std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1698     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1699       // Define the Scope debug information entry.
1700       DebugScope *Scope = Scopes[j];
1701       // FIXME - Ignore inlined functions for the time being.
1702       if (!Scope->getParent()) continue;
1703       
1704       unsigned StartID = DebugInfo->MappedLabel(Scope->getStartLabelID());
1705       unsigned EndID = DebugInfo->MappedLabel(Scope->getEndLabelID());
1706
1707       // Ignore empty scopes.
1708       if (StartID == EndID && StartID != 0) continue;
1709       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1710       
1711       if (StartID == ParentStartID && EndID == ParentEndID) {
1712         // Just add stuff to the parent scope.
1713         ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1714       } else {
1715         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1716         
1717         // Add the scope bounds.
1718         if (StartID) {
1719           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1720                              DWLabel("loc", StartID));
1721         } else {
1722           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1723                              DWLabel("func_begin", SubprogramCount));
1724         }
1725         if (EndID) {
1726           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1727                              DWLabel("loc", EndID));
1728         } else {
1729           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1730                              DWLabel("func_end", SubprogramCount));
1731         }
1732                            
1733         // Add the scope contents.
1734         ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1735         ParentDie->AddChild(ScopeDie);
1736       }
1737     }
1738   }
1739
1740   /// ConstructRootScope - Construct the scope for the subprogram.
1741   ///
1742   void ConstructRootScope(DebugScope *RootScope) {
1743     // Exit if there is no root scope.
1744     if (!RootScope) return;
1745     
1746     // Get the subprogram debug information entry. 
1747     SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1748     
1749     // Get the compile unit context.
1750     CompileUnit *Unit = GetBaseCompileUnit();
1751     
1752     // Get the subprogram die.
1753     DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1754     assert(SPDie && "Missing subprogram descriptor");
1755     
1756     // Add the function bounds.
1757     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1758                     DWLabel("func_begin", SubprogramCount));
1759     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1760                     DWLabel("func_end", SubprogramCount));
1761     MachineLocation Location(RI->getFrameRegister(*MF));
1762     AddAddress(SPDie, DW_AT_frame_base, Location);
1763
1764     ConstructScope(RootScope, 0, 0, SPDie, Unit);
1765   }
1766
1767   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1768   /// tools to recognize the object file contains Dwarf information.
1769   void EmitInitial() {
1770     // Check to see if we already emitted intial headers.
1771     if (didInitial) return;
1772     didInitial = true;
1773     
1774     // Dwarf sections base addresses.
1775     if (TAI->getDwarfRequiresFrameSection()) {
1776       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1777       EmitLabel("section_frame", 0);
1778     }
1779     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1780     EmitLabel("section_info", 0);
1781     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1782     EmitLabel("section_abbrev", 0);
1783     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1784     EmitLabel("section_aranges", 0);
1785     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1786     EmitLabel("section_macinfo", 0);
1787     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1788     EmitLabel("section_line", 0);
1789     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1790     EmitLabel("section_loc", 0);
1791     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1792     EmitLabel("section_pubnames", 0);
1793     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1794     EmitLabel("section_str", 0);
1795     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1796     EmitLabel("section_ranges", 0);
1797
1798     Asm->SwitchToTextSection(TAI->getTextSection());
1799     EmitLabel("text_begin", 0);
1800     Asm->SwitchToDataSection(TAI->getDataSection());
1801     EmitLabel("data_begin", 0);
1802
1803     // Emit common frame information.
1804     EmitInitialDebugFrame();
1805   }
1806
1807   /// EmitDIE - Recusively Emits a debug information entry.
1808   ///
1809   void EmitDIE(DIE *Die) const {
1810     // Get the abbreviation for this DIE.
1811     unsigned AbbrevNumber = Die->getAbbrevNumber();
1812     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1813     
1814     Asm->EOL("");
1815
1816     // Emit the code (index) for the abbreviation.
1817     Asm->EmitULEB128Bytes(AbbrevNumber);
1818     Asm->EOL(std::string("Abbrev [" +
1819              utostr(AbbrevNumber) +
1820              "] 0x" + utohexstr(Die->getOffset()) +
1821              ":0x" + utohexstr(Die->getSize()) + " " +
1822              TagString(Abbrev->getTag())));
1823     
1824     const std::vector<DIEValue *> &Values = Die->getValues();
1825     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1826     
1827     // Emit the DIE attribute values.
1828     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1829       unsigned Attr = AbbrevData[i].getAttribute();
1830       unsigned Form = AbbrevData[i].getForm();
1831       assert(Form && "Too many attributes for DIE (check abbreviation)");
1832       
1833       switch (Attr) {
1834       case DW_AT_sibling: {
1835         Asm->EmitInt32(Die->SiblingOffset());
1836         break;
1837       }
1838       default: {
1839         // Emit an attribute using the defined form.
1840         Values[i]->EmitValue(*this, Form);
1841         break;
1842       }
1843       }
1844       
1845       Asm->EOL(AttributeString(Attr));
1846     }
1847     
1848     // Emit the DIE children if any.
1849     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
1850       const std::vector<DIE *> &Children = Die->getChildren();
1851       
1852       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1853         EmitDIE(Children[j]);
1854       }
1855       
1856       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1857     }
1858   }
1859
1860   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1861   ///
1862   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1863     // Get the children.
1864     const std::vector<DIE *> &Children = Die->getChildren();
1865     
1866     // If not last sibling and has children then add sibling offset attribute.
1867     if (!Last && !Children.empty()) Die->AddSiblingOffset();
1868
1869     // Record the abbreviation.
1870     AssignAbbrevNumber(Die->getAbbrev());
1871    
1872     // Get the abbreviation for this DIE.
1873     unsigned AbbrevNumber = Die->getAbbrevNumber();
1874     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1875
1876     // Set DIE offset
1877     Die->setOffset(Offset);
1878     
1879     // Start the size with the size of abbreviation code.
1880     Offset += Asm->SizeULEB128(AbbrevNumber);
1881     
1882     const std::vector<DIEValue *> &Values = Die->getValues();
1883     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1884
1885     // Size the DIE attribute values.
1886     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1887       // Size attribute value.
1888       Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
1889     }
1890     
1891     // Size the DIE children if any.
1892     if (!Children.empty()) {
1893       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
1894              "Children flag not set");
1895       
1896       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1897         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1898       }
1899       
1900       // End of children marker.
1901       Offset += sizeof(int8_t);
1902     }
1903
1904     Die->setSize(Offset - Die->getOffset());
1905     return Offset;
1906   }
1907
1908   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1909   ///
1910   void SizeAndOffsets() {
1911     // Process base compile unit.
1912     CompileUnit *Unit = GetBaseCompileUnit();
1913     // Compute size of compile unit header
1914     unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
1915                       sizeof(int16_t) + // DWARF version number
1916                       sizeof(int32_t) + // Offset Into Abbrev. Section
1917                       sizeof(int8_t);   // Pointer Size (in bytes)
1918     SizeAndOffsetDie(Unit->getDie(), Offset, true);
1919   }
1920
1921   /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1922   /// frame.
1923   void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1924                                    std::vector<MachineMove> &Moves) {
1925     int stackGrowth =
1926         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1927           TargetFrameInfo::StackGrowsUp ?
1928             TAI->getAddressSize() : -TAI->getAddressSize();
1929
1930     for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1931       MachineMove &Move = Moves[i];
1932       unsigned LabelID = Move.getLabelID();
1933       
1934       if (LabelID) {
1935         LabelID = DebugInfo->MappedLabel(LabelID);
1936       
1937         // Throw out move if the label is invalid.
1938         if (!LabelID) continue;
1939       }
1940       
1941       const MachineLocation &Dst = Move.getDestination();
1942       const MachineLocation &Src = Move.getSource();
1943       
1944       // Advance row if new location.
1945       if (BaseLabel && LabelID && BaseLabelID != LabelID) {
1946         Asm->EmitInt8(DW_CFA_advance_loc4);
1947         Asm->EOL("DW_CFA_advance_loc4");
1948         EmitDifference("loc", LabelID, BaseLabel, BaseLabelID, true);
1949         Asm->EOL("");
1950         
1951         BaseLabelID = LabelID;
1952         BaseLabel = "loc";
1953       }
1954       
1955       // If advancing cfa.
1956       if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1957         if (!Src.isRegister()) {
1958           if (Src.getRegister() == MachineLocation::VirtualFP) {
1959             Asm->EmitInt8(DW_CFA_def_cfa_offset);
1960             Asm->EOL("DW_CFA_def_cfa_offset");
1961           } else {
1962             Asm->EmitInt8(DW_CFA_def_cfa);
1963             Asm->EOL("DW_CFA_def_cfa");
1964             Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
1965             Asm->EOL("Register");
1966           }
1967           
1968           int Offset = Src.getOffset() / stackGrowth;
1969           
1970           Asm->EmitULEB128Bytes(Offset);
1971           Asm->EOL("Offset");
1972         } else {
1973           assert(0 && "Machine move no supported yet.");
1974         }
1975       } else if (Src.isRegister() &&
1976         Src.getRegister() == MachineLocation::VirtualFP) {
1977         if (Dst.isRegister()) {
1978           Asm->EmitInt8(DW_CFA_def_cfa_register);
1979           Asm->EOL("DW_CFA_def_cfa_register");
1980           Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister()));
1981           Asm->EOL("Register");
1982         } else {
1983           assert(0 && "Machine move no supported yet.");
1984         }
1985       } else {
1986         unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
1987         int Offset = Dst.getOffset() / stackGrowth;
1988         
1989         if (Offset < 0) {
1990           Asm->EmitInt8(DW_CFA_offset_extended_sf);
1991           Asm->EOL("DW_CFA_offset_extended_sf");
1992           Asm->EmitULEB128Bytes(Reg);
1993           Asm->EOL("Reg");
1994           Asm->EmitSLEB128Bytes(Offset);
1995           Asm->EOL("Offset");
1996         } else if (Reg < 64) {
1997           Asm->EmitInt8(DW_CFA_offset + Reg);
1998           Asm->EOL("DW_CFA_offset + Reg");
1999           Asm->EmitULEB128Bytes(Offset);
2000           Asm->EOL("Offset");
2001         } else {
2002           Asm->EmitInt8(DW_CFA_offset_extended);
2003           Asm->EOL("DW_CFA_offset_extended");
2004           Asm->EmitULEB128Bytes(Reg);
2005           Asm->EOL("Reg");
2006           Asm->EmitULEB128Bytes(Offset);
2007           Asm->EOL("Offset");
2008         }
2009       }
2010     }
2011   }
2012
2013   /// EmitDebugInfo - Emit the debug info section.
2014   ///
2015   void EmitDebugInfo() const {
2016     // Start debug info section.
2017     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2018     
2019     CompileUnit *Unit = GetBaseCompileUnit();
2020     DIE *Die = Unit->getDie();
2021     // Emit the compile units header.
2022     EmitLabel("info_begin", Unit->getID());
2023     // Emit size of content not including length itself
2024     unsigned ContentSize = Die->getSize() +
2025                            sizeof(int16_t) + // DWARF version number
2026                            sizeof(int32_t) + // Offset Into Abbrev. Section
2027                            sizeof(int8_t) +  // Pointer Size (in bytes)
2028                            sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2029                            
2030     Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
2031     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2032     EmitDifference("abbrev_begin", 0, "section_abbrev", 0, true);
2033     Asm->EOL("Offset Into Abbrev. Section");
2034     Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Address Size (in bytes)");
2035   
2036     EmitDIE(Die);
2037     // FIXME - extra padding for gdb bug.
2038     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2039     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2040     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2041     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2042     EmitLabel("info_end", Unit->getID());
2043     
2044     Asm->EOL("");
2045   }
2046
2047   /// EmitAbbreviations - Emit the abbreviation section.
2048   ///
2049   void EmitAbbreviations() const {
2050     // Check to see if it is worth the effort.
2051     if (!Abbreviations.empty()) {
2052       // Start the debug abbrev section.
2053       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2054       
2055       EmitLabel("abbrev_begin", 0);
2056       
2057       // For each abbrevation.
2058       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2059         // Get abbreviation data
2060         const DIEAbbrev *Abbrev = Abbreviations[i];
2061         
2062         // Emit the abbrevations code (base 1 index.)
2063         Asm->EmitULEB128Bytes(Abbrev->getNumber());
2064         Asm->EOL("Abbreviation Code");
2065         
2066         // Emit the abbreviations data.
2067         Abbrev->Emit(*this);
2068     
2069         Asm->EOL("");
2070       }
2071       
2072       EmitLabel("abbrev_end", 0);
2073     
2074       Asm->EOL("");
2075     }
2076   }
2077
2078   /// EmitDebugLines - Emit source line information.
2079   ///
2080   void EmitDebugLines() const {
2081     // Minimum line delta, thus ranging from -10..(255-10).
2082     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2083     // Maximum line delta, thus ranging from -10..(255-10).
2084     const int MaxLineDelta = 255 + MinLineDelta;
2085
2086     // Start the dwarf line section.
2087     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2088     
2089     // Construct the section header.
2090     
2091     EmitDifference("line_end", 0, "line_begin", 0, true);
2092     Asm->EOL("Length of Source Line Info");
2093     EmitLabel("line_begin", 0);
2094     
2095     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2096     
2097     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2098     Asm->EOL("Prolog Length");
2099     EmitLabel("line_prolog_begin", 0);
2100     
2101     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2102
2103     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2104
2105     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2106     
2107     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2108
2109     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2110     
2111     // Line number standard opcode encodings argument count
2112     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2113     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2114     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2115     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2116     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2117     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2118     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2119     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2120     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2121
2122     const UniqueVector<std::string> &Directories = DebugInfo->getDirectories();
2123     const UniqueVector<SourceFileInfo>
2124       &SourceFiles = DebugInfo->getSourceFiles();
2125
2126     // Emit directories.
2127     for (unsigned DirectoryID = 1, NDID = Directories.size();
2128                   DirectoryID <= NDID; ++DirectoryID) {
2129       Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2130     }
2131     Asm->EmitInt8(0); Asm->EOL("End of directories");
2132     
2133     // Emit files.
2134     for (unsigned SourceID = 1, NSID = SourceFiles.size();
2135                  SourceID <= NSID; ++SourceID) {
2136       const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2137       Asm->EmitString(SourceFile.getName());
2138       Asm->EOL("Source");
2139       Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2140       Asm->EOL("Directory #");
2141       Asm->EmitULEB128Bytes(0);
2142       Asm->EOL("Mod date");
2143       Asm->EmitULEB128Bytes(0);
2144       Asm->EOL("File size");
2145     }
2146     Asm->EmitInt8(0); Asm->EOL("End of files");
2147     
2148     EmitLabel("line_prolog_end", 0);
2149     
2150     // A sequence for each text section.
2151     for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2152       // Isolate current sections line info.
2153       const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2154       
2155       Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2156
2157       // Dwarf assumes we start with first line of first source file.
2158       unsigned Source = 1;
2159       unsigned Line = 1;
2160       
2161       // Construct rows of the address, source, line, column matrix.
2162       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2163         const SourceLineInfo &LineInfo = LineInfos[i];
2164         unsigned LabelID = DebugInfo->MappedLabel(LineInfo.getLabelID());
2165         if (!LabelID) continue;
2166         
2167         unsigned SourceID = LineInfo.getSourceID();
2168         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2169         unsigned DirectoryID = SourceFile.getDirectoryID();
2170         Asm->EOL(Directories[DirectoryID]
2171           + SourceFile.getName()
2172           + ":"
2173           + utostr_32(LineInfo.getLine()));
2174
2175         // Define the line address.
2176         Asm->EmitInt8(0); Asm->EOL("Extended Op");
2177         Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2178         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2179         EmitReference("loc",  LabelID); Asm->EOL("Location label");
2180         
2181         // If change of source, then switch to the new source.
2182         if (Source != LineInfo.getSourceID()) {
2183           Source = LineInfo.getSourceID();
2184           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2185           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2186         }
2187         
2188         // If change of line.
2189         if (Line != LineInfo.getLine()) {
2190           // Determine offset.
2191           int Offset = LineInfo.getLine() - Line;
2192           int Delta = Offset - MinLineDelta;
2193           
2194           // Update line.
2195           Line = LineInfo.getLine();
2196           
2197           // If delta is small enough and in range...
2198           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2199             // ... then use fast opcode.
2200             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2201           } else {
2202             // ... otherwise use long hand.
2203             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2204             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2205             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2206           }
2207         } else {
2208           // Copy the previous row (different address or source)
2209           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2210         }
2211       }
2212
2213       // Define last address of section.
2214       Asm->EmitInt8(0); Asm->EOL("Extended Op");
2215       Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2216       Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2217       EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2218
2219       // Mark end of matrix.
2220       Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2221       Asm->EmitULEB128Bytes(1); Asm->EOL("");
2222       Asm->EmitInt8(1); Asm->EOL("");
2223     }
2224     
2225     EmitLabel("line_end", 0);
2226     
2227     Asm->EOL("");
2228   }
2229     
2230   /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
2231   ///
2232   void EmitInitialDebugFrame() {
2233     if (!TAI->getDwarfRequiresFrameSection())
2234       return;
2235
2236     int stackGrowth =
2237         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2238           TargetFrameInfo::StackGrowsUp ?
2239         TAI->getAddressSize() : -TAI->getAddressSize();
2240
2241     // Start the dwarf frame section.
2242     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2243
2244     EmitLabel("frame_common", 0);
2245     EmitDifference("frame_common_end", 0,
2246                    "frame_common_begin", 0, true);
2247     Asm->EOL("Length of Common Information Entry");
2248
2249     EmitLabel("frame_common_begin", 0);
2250     Asm->EmitInt32((int)DW_CIE_ID);
2251     Asm->EOL("CIE Identifier Tag");
2252     Asm->EmitInt8(DW_CIE_VERSION);
2253     Asm->EOL("CIE Version");
2254     Asm->EmitString("");
2255     Asm->EOL("CIE Augmentation");
2256     Asm->EmitULEB128Bytes(1);
2257     Asm->EOL("CIE Code Alignment Factor");
2258     Asm->EmitSLEB128Bytes(stackGrowth);
2259     Asm->EOL("CIE Data Alignment Factor");   
2260     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2261     Asm->EOL("CIE RA Column");
2262     
2263     std::vector<MachineMove> Moves;
2264     RI->getInitialFrameState(Moves);
2265     EmitFrameMoves(NULL, 0, Moves);
2266
2267     Asm->EmitAlignment(2);
2268     EmitLabel("frame_common_end", 0);
2269     
2270     Asm->EOL("");
2271   }
2272
2273   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2274   /// section.
2275   void EmitFunctionDebugFrame() {
2276     if (!TAI->getDwarfRequiresFrameSection())
2277       return;
2278        
2279     // Start the dwarf frame section.
2280     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2281     
2282     EmitDifference("frame_end", SubprogramCount,
2283                    "frame_begin", SubprogramCount, true);
2284     Asm->EOL("Length of Frame Information Entry");
2285     
2286     EmitLabel("frame_begin", SubprogramCount);
2287     
2288     EmitDifference("frame_common", 0, "section_frame", 0, true);
2289     Asm->EOL("FDE CIE offset");
2290
2291     EmitReference("func_begin", SubprogramCount);
2292     Asm->EOL("FDE initial location");
2293     EmitDifference("func_end", SubprogramCount,
2294                    "func_begin", SubprogramCount);
2295     Asm->EOL("FDE address range");
2296     
2297     std::vector<MachineMove> &Moves = DebugInfo->getFrameMoves();
2298     
2299     EmitFrameMoves("func_begin", SubprogramCount, Moves);
2300     
2301     Asm->EmitAlignment(2);
2302     EmitLabel("frame_end", SubprogramCount);
2303
2304     Asm->EOL("");
2305   }
2306
2307   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2308   ///
2309   void EmitDebugPubNames() {
2310     // Start the dwarf pubnames section.
2311     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2312       
2313     CompileUnit *Unit = GetBaseCompileUnit(); 
2314  
2315     EmitDifference("pubnames_end", Unit->getID(),
2316                    "pubnames_begin", Unit->getID(), true);
2317     Asm->EOL("Length of Public Names Info");
2318     
2319     EmitLabel("pubnames_begin", Unit->getID());
2320     
2321     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2322     
2323     EmitDifference("info_begin", Unit->getID(), "section_info", 0, true);
2324     Asm->EOL("Offset of Compilation Unit Info");
2325
2326     EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2327     Asm->EOL("Compilation Unit Length");
2328     
2329     std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2330     
2331     for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2332                                                 GE = Globals.end();
2333          GI != GE; ++GI) {
2334       const std::string &Name = GI->first;
2335       DIE * Entity = GI->second;
2336       
2337       Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2338       Asm->EmitString(Name); Asm->EOL("External Name");
2339     }
2340   
2341     Asm->EmitInt32(0); Asm->EOL("End Mark");
2342     EmitLabel("pubnames_end", Unit->getID());
2343   
2344     Asm->EOL("");
2345   }
2346
2347   /// EmitDebugStr - Emit visible names into a debug str section.
2348   ///
2349   void EmitDebugStr() {
2350     // Check to see if it is worth the effort.
2351     if (!StringPool.empty()) {
2352       // Start the dwarf str section.
2353       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2354       
2355       // For each of strings in the string pool.
2356       for (unsigned StringID = 1, N = StringPool.size();
2357            StringID <= N; ++StringID) {
2358         // Emit a label for reference from debug information entries.
2359         EmitLabel("string", StringID);
2360         // Emit the string itself.
2361         const std::string &String = StringPool[StringID];
2362         Asm->EmitString(String); Asm->EOL("");
2363       }
2364     
2365       Asm->EOL("");
2366     }
2367   }
2368
2369   /// EmitDebugLoc - Emit visible names into a debug loc section.
2370   ///
2371   void EmitDebugLoc() {
2372     // Start the dwarf loc section.
2373     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2374     
2375     Asm->EOL("");
2376   }
2377
2378   /// EmitDebugARanges - Emit visible names into a debug aranges section.
2379   ///
2380   void EmitDebugARanges() {
2381     // Start the dwarf aranges section.
2382     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2383     
2384     // FIXME - Mock up
2385   #if 0
2386     CompileUnit *Unit = GetBaseCompileUnit(); 
2387       
2388     // Don't include size of length
2389     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2390     
2391     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2392     
2393     EmitReference("info_begin", Unit->getID());
2394     Asm->EOL("Offset of Compilation Unit Info");
2395
2396     Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Size of Address");
2397
2398     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2399
2400     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
2401     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
2402
2403     // Range 1
2404     EmitReference("text_begin", 0); Asm->EOL("Address");
2405     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2406
2407     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2408     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2409     
2410     Asm->EOL("");
2411   #endif
2412   }
2413
2414   /// EmitDebugRanges - Emit visible names into a debug ranges section.
2415   ///
2416   void EmitDebugRanges() {
2417     // Start the dwarf ranges section.
2418     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2419     
2420     Asm->EOL("");
2421   }
2422
2423   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2424   ///
2425   void EmitDebugMacInfo() {
2426     // Start the dwarf macinfo section.
2427     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2428     
2429     Asm->EOL("");
2430   }
2431
2432   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2433   /// header file.
2434   void ConstructCompileUnitDIEs() {
2435     const UniqueVector<CompileUnitDesc *> CUW = DebugInfo->getCompileUnits();
2436     
2437     for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2438       unsigned ID = DebugInfo->RecordSource(CUW[i]);
2439       CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2440       CompileUnits.push_back(Unit);
2441     }
2442   }
2443
2444   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2445   /// global variables.
2446   void ConstructGlobalDIEs() {
2447     std::vector<GlobalVariableDesc *> GlobalVariables =
2448         DebugInfo->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2449     
2450     for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2451       GlobalVariableDesc *GVD = GlobalVariables[i];
2452       NewGlobalVariable(GVD);
2453     }
2454   }
2455
2456   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2457   /// subprograms.
2458   void ConstructSubprogramDIEs() {
2459     std::vector<SubprogramDesc *> Subprograms =
2460         DebugInfo->getAnchoredDescriptors<SubprogramDesc>(*M);
2461     
2462     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2463       SubprogramDesc *SPD = Subprograms[i];
2464       NewSubprogram(SPD);
2465     }
2466   }
2467
2468   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
2469   ///
2470   bool ShouldEmitDwarf() const { return shouldEmit; }
2471
2472 public:
2473   //===--------------------------------------------------------------------===//
2474   // Main entry points.
2475   //
2476   Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2477   : O(OS)
2478   , Asm(A)
2479   , TAI(T)
2480   , TD(Asm->TM.getTargetData())
2481   , RI(Asm->TM.getRegisterInfo())
2482   , M(NULL)
2483   , MF(NULL)
2484   , DebugInfo(NULL)
2485   , didInitial(false)
2486   , shouldEmit(false)
2487   , SubprogramCount(0)
2488   , CompileUnits()
2489   , AbbreviationsSet(InitAbbreviationsSetSize)
2490   , Abbreviations()
2491   , ValuesSet(InitValuesSetSize)
2492   , Values()
2493   , StringPool()
2494   , DescToUnitMap()
2495   , SectionMap()
2496   , SectionSourceLines()
2497   {
2498   }
2499   virtual ~Dwarf() {
2500     for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2501       delete CompileUnits[i];
2502     for (unsigned j = 0, M = Values.size(); j < M; ++j)
2503       delete Values[j];
2504   }
2505
2506   // Accessors.
2507   //
2508   const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
2509   
2510   /// SetDebugInfo - Set DebugInfo when it's known that pass manager has
2511   /// created it.  Set by the target AsmPrinter.
2512   void SetDebugInfo(MachineDebugInfo *DI) {
2513     // Make sure initial declarations are made.
2514     if (!DebugInfo && DI->hasInfo()) {
2515       DebugInfo = DI;
2516       shouldEmit = true;
2517       
2518       // Emit initial sections
2519       EmitInitial();
2520     
2521       // Create all the compile unit DIEs.
2522       ConstructCompileUnitDIEs();
2523       
2524       // Create DIEs for each of the externally visible global variables.
2525       ConstructGlobalDIEs();
2526
2527       // Create DIEs for each of the externally visible subprograms.
2528       ConstructSubprogramDIEs();
2529       
2530       // Prime section data.
2531       SectionMap.insert(TAI->getTextSection());
2532     }
2533   }
2534
2535   /// BeginModule - Emit all Dwarf sections that should come prior to the
2536   /// content.
2537   void BeginModule(Module *M) {
2538     this->M = M;
2539     
2540     if (!ShouldEmitDwarf()) return;
2541     Asm->EOL("Dwarf Begin Module");
2542   }
2543
2544   /// EndModule - Emit all Dwarf sections that should come after the content.
2545   ///
2546   void EndModule() {
2547     if (!ShouldEmitDwarf()) return;
2548     Asm->EOL("Dwarf End Module");
2549     
2550     // Standard sections final addresses.
2551     Asm->SwitchToTextSection(TAI->getTextSection());
2552     EmitLabel("text_end", 0);
2553     Asm->SwitchToDataSection(TAI->getDataSection());
2554     EmitLabel("data_end", 0);
2555     
2556     // End text sections.
2557     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2558       Asm->SwitchToTextSection(SectionMap[i].c_str());
2559       EmitLabel("section_end", i);
2560     }
2561     
2562     // Compute DIE offsets and sizes.
2563     SizeAndOffsets();
2564     
2565     // Emit all the DIEs into a debug info section
2566     EmitDebugInfo();
2567     
2568     // Corresponding abbreviations into a abbrev section.
2569     EmitAbbreviations();
2570     
2571     // Emit source line correspondence into a debug line section.
2572     EmitDebugLines();
2573     
2574     // Emit info into a debug pubnames section.
2575     EmitDebugPubNames();
2576     
2577     // Emit info into a debug str section.
2578     EmitDebugStr();
2579     
2580     // Emit info into a debug loc section.
2581     EmitDebugLoc();
2582     
2583     // Emit info into a debug aranges section.
2584     EmitDebugARanges();
2585     
2586     // Emit info into a debug ranges section.
2587     EmitDebugRanges();
2588     
2589     // Emit info into a debug macinfo section.
2590     EmitDebugMacInfo();
2591   }
2592
2593   /// BeginFunction - Gather pre-function debug information.  Assumes being 
2594   /// emitted immediately after the function entry point.
2595   void BeginFunction(MachineFunction *MF) {
2596     this->MF = MF;
2597     
2598     if (!ShouldEmitDwarf()) return;
2599     Asm->EOL("Dwarf Begin Function");
2600
2601     // Begin accumulating function debug information.
2602     DebugInfo->BeginFunction(MF);
2603     
2604     // Assumes in correct section after the entry point.
2605     EmitLabel("func_begin", ++SubprogramCount);
2606   }
2607
2608   /// EndFunction - Gather and emit post-function debug information.
2609   ///
2610   void EndFunction() {
2611     if (!ShouldEmitDwarf()) return;
2612     Asm->EOL("Dwarf End Function");
2613     
2614     // Define end label for subprogram.
2615     EmitLabel("func_end", SubprogramCount);
2616       
2617     // Get function line info.
2618     const std::vector<SourceLineInfo> &LineInfos = DebugInfo->getSourceLines();
2619
2620     if (!LineInfos.empty()) {
2621       // Get section line info.
2622       unsigned ID = SectionMap.insert(Asm->CurrentSection);
2623       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2624       std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2625       // Append the function info to section info.
2626       SectionLineInfos.insert(SectionLineInfos.end(),
2627                               LineInfos.begin(), LineInfos.end());
2628     }
2629     
2630     // Construct scopes for subprogram.
2631     ConstructRootScope(DebugInfo->getRootScope());
2632     
2633     // Emit function frame information.
2634     EmitFunctionDebugFrame();
2635     
2636     // Reset the line numbers for the next function.
2637     DebugInfo->ClearLineInfo();
2638
2639     // Clear function debug information.
2640     DebugInfo->EndFunction();
2641   }
2642 };
2643
2644 } // End of namespace llvm
2645
2646 //===----------------------------------------------------------------------===//
2647
2648 /// Emit - Print the abbreviation using the specified Dwarf writer.
2649 ///
2650 void DIEAbbrev::Emit(const Dwarf &DW) const {
2651   // Emit its Dwarf tag type.
2652   DW.getAsm()->EmitULEB128Bytes(Tag);
2653   DW.getAsm()->EOL(TagString(Tag));
2654   
2655   // Emit whether it has children DIEs.
2656   DW.getAsm()->EmitULEB128Bytes(ChildrenFlag);
2657   DW.getAsm()->EOL(ChildrenString(ChildrenFlag));
2658   
2659   // For each attribute description.
2660   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
2661     const DIEAbbrevData &AttrData = Data[i];
2662     
2663     // Emit attribute type.
2664     DW.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
2665     DW.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
2666     
2667     // Emit form type.
2668     DW.getAsm()->EmitULEB128Bytes(AttrData.getForm());
2669     DW.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
2670   }
2671
2672   // Mark end of abbreviation.
2673   DW.getAsm()->EmitULEB128Bytes(0); DW.getAsm()->EOL("EOM(1)");
2674   DW.getAsm()->EmitULEB128Bytes(0); DW.getAsm()->EOL("EOM(2)");
2675 }
2676
2677 #ifndef NDEBUG
2678 void DIEAbbrev::print(std::ostream &O) {
2679   O << "Abbreviation @"
2680     << std::hex << (intptr_t)this << std::dec
2681     << "  "
2682     << TagString(Tag)
2683     << " "
2684     << ChildrenString(ChildrenFlag)
2685     << "\n";
2686   
2687   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
2688     O << "  "
2689       << AttributeString(Data[i].getAttribute())
2690       << "  "
2691       << FormEncodingString(Data[i].getForm())
2692       << "\n";
2693   }
2694 }
2695 void DIEAbbrev::dump() { print(cerr); }
2696 #endif
2697
2698 //===----------------------------------------------------------------------===//
2699
2700 #ifndef NDEBUG
2701 void DIEValue::dump() {
2702   print(cerr);
2703 }
2704 #endif
2705
2706 //===----------------------------------------------------------------------===//
2707
2708 /// EmitValue - Emit integer of appropriate size.
2709 ///
2710 void DIEInteger::EmitValue(const Dwarf &DW, unsigned Form) const {
2711   switch (Form) {
2712   case DW_FORM_flag:  // Fall thru
2713   case DW_FORM_ref1:  // Fall thru
2714   case DW_FORM_data1: DW.getAsm()->EmitInt8(Integer);         break;
2715   case DW_FORM_ref2:  // Fall thru
2716   case DW_FORM_data2: DW.getAsm()->EmitInt16(Integer);        break;
2717   case DW_FORM_ref4:  // Fall thru
2718   case DW_FORM_data4: DW.getAsm()->EmitInt32(Integer);        break;
2719   case DW_FORM_ref8:  // Fall thru
2720   case DW_FORM_data8: DW.getAsm()->EmitInt64(Integer);        break;
2721   case DW_FORM_udata: DW.getAsm()->EmitULEB128Bytes(Integer); break;
2722   case DW_FORM_sdata: DW.getAsm()->EmitSLEB128Bytes(Integer); break;
2723   default: assert(0 && "DIE Value form not supported yet");   break;
2724   }
2725 }
2726
2727 /// SizeOf - Determine size of integer value in bytes.
2728 ///
2729 unsigned DIEInteger::SizeOf(const Dwarf &DW, unsigned Form) const {
2730   switch (Form) {
2731   case DW_FORM_flag:  // Fall thru
2732   case DW_FORM_ref1:  // Fall thru
2733   case DW_FORM_data1: return sizeof(int8_t);
2734   case DW_FORM_ref2:  // Fall thru
2735   case DW_FORM_data2: return sizeof(int16_t);
2736   case DW_FORM_ref4:  // Fall thru
2737   case DW_FORM_data4: return sizeof(int32_t);
2738   case DW_FORM_ref8:  // Fall thru
2739   case DW_FORM_data8: return sizeof(int64_t);
2740   case DW_FORM_udata: return DW.getAsm()->SizeULEB128(Integer);
2741   case DW_FORM_sdata: return DW.getAsm()->SizeSLEB128(Integer);
2742   default: assert(0 && "DIE Value form not supported yet"); break;
2743   }
2744   return 0;
2745 }
2746
2747 //===----------------------------------------------------------------------===//
2748
2749 /// EmitValue - Emit string value.
2750 ///
2751 void DIEString::EmitValue(const Dwarf &DW, unsigned Form) const {
2752   DW.getAsm()->EmitString(String);
2753 }
2754
2755 //===----------------------------------------------------------------------===//
2756
2757 /// EmitValue - Emit label value.
2758 ///
2759 void DIEDwarfLabel::EmitValue(const Dwarf &DW, unsigned Form) const {
2760   DW.EmitReference(Label);
2761 }
2762
2763 /// SizeOf - Determine size of label value in bytes.
2764 ///
2765 unsigned DIEDwarfLabel::SizeOf(const Dwarf &DW, unsigned Form) const {
2766   return DW.getTargetAsmInfo()->getAddressSize();
2767 }
2768
2769 //===----------------------------------------------------------------------===//
2770
2771 /// EmitValue - Emit label value.
2772 ///
2773 void DIEObjectLabel::EmitValue(const Dwarf &DW, unsigned Form) const {
2774   DW.EmitReference(Label);
2775 }
2776
2777 /// SizeOf - Determine size of label value in bytes.
2778 ///
2779 unsigned DIEObjectLabel::SizeOf(const Dwarf &DW, unsigned Form) const {
2780   return DW.getTargetAsmInfo()->getAddressSize();
2781 }
2782     
2783 //===----------------------------------------------------------------------===//
2784
2785 /// EmitValue - Emit delta value.
2786 ///
2787 void DIEDelta::EmitValue(const Dwarf &DW, unsigned Form) const {
2788   bool IsSmall = Form == DW_FORM_data4;
2789   DW.EmitDifference(LabelHi, LabelLo, IsSmall);
2790 }
2791
2792 /// SizeOf - Determine size of delta value in bytes.
2793 ///
2794 unsigned DIEDelta::SizeOf(const Dwarf &DW, unsigned Form) const {
2795   if (Form == DW_FORM_data4) return 4;
2796   return DW.getTargetAsmInfo()->getAddressSize();
2797 }
2798
2799 //===----------------------------------------------------------------------===//
2800
2801 /// EmitValue - Emit debug information entry offset.
2802 ///
2803 void DIEntry::EmitValue(const Dwarf &DW, unsigned Form) const {
2804   DW.getAsm()->EmitInt32(Entry->getOffset());
2805 }
2806     
2807 //===----------------------------------------------------------------------===//
2808
2809 /// ComputeSize - calculate the size of the block.
2810 ///
2811 unsigned DIEBlock::ComputeSize(Dwarf &DW) {
2812   if (!Size) {
2813     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2814     
2815     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2816       Size += Values[i]->SizeOf(DW, AbbrevData[i].getForm());
2817     }
2818   }
2819   return Size;
2820 }
2821
2822 /// EmitValue - Emit block data.
2823 ///
2824 void DIEBlock::EmitValue(const Dwarf &DW, unsigned Form) const {
2825   switch (Form) {
2826   case DW_FORM_block1: DW.getAsm()->EmitInt8(Size);         break;
2827   case DW_FORM_block2: DW.getAsm()->EmitInt16(Size);        break;
2828   case DW_FORM_block4: DW.getAsm()->EmitInt32(Size);        break;
2829   case DW_FORM_block:  DW.getAsm()->EmitULEB128Bytes(Size); break;
2830   default: assert(0 && "Improper form for block");          break;
2831   }
2832   
2833   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2834
2835   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2836     DW.getAsm()->EOL("");
2837     Values[i]->EmitValue(DW, AbbrevData[i].getForm());
2838   }
2839 }
2840
2841 /// SizeOf - Determine size of block data in bytes.
2842 ///
2843 unsigned DIEBlock::SizeOf(const Dwarf &DW, unsigned Form) const {
2844   switch (Form) {
2845   case DW_FORM_block1: return Size + sizeof(int8_t);
2846   case DW_FORM_block2: return Size + sizeof(int16_t);
2847   case DW_FORM_block4: return Size + sizeof(int32_t);
2848   case DW_FORM_block: return Size + DW.getAsm()->SizeULEB128(Size);
2849   default: assert(0 && "Improper form for block"); break;
2850   }
2851   return 0;
2852 }
2853
2854 //===----------------------------------------------------------------------===//
2855 /// DIE Implementation
2856
2857 DIE::~DIE() {
2858   for (unsigned i = 0, N = Children.size(); i < N; ++i)
2859     delete Children[i];
2860 }
2861   
2862 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
2863 ///
2864 void DIE::AddSiblingOffset() {
2865   DIEInteger *DI = new DIEInteger(0);
2866   Values.insert(Values.begin(), DI);
2867   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
2868 }
2869
2870 /// Profile - Used to gather unique data for the value folding set.
2871 ///
2872 void DIE::Profile(FoldingSetNodeID &ID) {
2873   Abbrev.Profile(ID);
2874   
2875   for (unsigned i = 0, N = Children.size(); i < N; ++i)
2876     ID.AddPointer(Children[i]);
2877
2878   for (unsigned j = 0, M = Values.size(); j < M; ++j)
2879     ID.AddPointer(Values[j]);
2880 }
2881
2882 #ifndef NDEBUG
2883 void DIE::print(std::ostream &O, unsigned IncIndent) {
2884   static unsigned IndentCount = 0;
2885   IndentCount += IncIndent;
2886   const std::string Indent(IndentCount, ' ');
2887   bool isBlock = Abbrev.getTag() == 0;
2888   
2889   if (!isBlock) {
2890     O << Indent
2891       << "Die: "
2892       << "0x" << std::hex << (intptr_t)this << std::dec
2893       << ", Offset: " << Offset
2894       << ", Size: " << Size
2895       << "\n"; 
2896     
2897     O << Indent
2898       << TagString(Abbrev.getTag())
2899       << " "
2900       << ChildrenString(Abbrev.getChildrenFlag());
2901   } else {
2902     O << "Size: " << Size;
2903   }
2904   O << "\n";
2905
2906   const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
2907   
2908   IndentCount += 2;
2909   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
2910     O << Indent;
2911     if (!isBlock) {
2912       O << AttributeString(Data[i].getAttribute());
2913     } else {
2914       O << "Blk[" << i << "]";
2915     }
2916     O <<  "  "
2917       << FormEncodingString(Data[i].getForm())
2918       << " ";
2919     Values[i]->print(O);
2920     O << "\n";
2921   }
2922   IndentCount -= 2;
2923
2924   for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2925     Children[j]->print(O, 4);
2926   }
2927   
2928   if (!isBlock) O << "\n";
2929   IndentCount -= IncIndent;
2930 }
2931
2932 void DIE::dump() {
2933   print(cerr);
2934 }
2935 #endif
2936
2937 //===----------------------------------------------------------------------===//
2938 /// DwarfWriter Implementation
2939 ///
2940
2941 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
2942                          const TargetAsmInfo *T) {
2943   DW = new Dwarf(OS, A, T);
2944 }
2945
2946 DwarfWriter::~DwarfWriter() {
2947   delete DW;
2948 }
2949
2950 /// SetDebugInfo - Set DebugInfo when it's known that pass manager has
2951 /// created it.  Set by the target AsmPrinter.
2952 void DwarfWriter::SetDebugInfo(MachineDebugInfo *DI) {
2953   DW->SetDebugInfo(DI);
2954 }
2955
2956 /// BeginModule - Emit all Dwarf sections that should come prior to the
2957 /// content.
2958 void DwarfWriter::BeginModule(Module *M) {
2959   DW->BeginModule(M);
2960 }
2961
2962 /// EndModule - Emit all Dwarf sections that should come after the content.
2963 ///
2964 void DwarfWriter::EndModule() {
2965   DW->EndModule();
2966 }
2967
2968 /// BeginFunction - Gather pre-function debug information.  Assumes being 
2969 /// emitted immediately after the function entry point.
2970 void DwarfWriter::BeginFunction(MachineFunction *MF) {
2971   DW->BeginFunction(MF);
2972 }
2973
2974 /// EndFunction - Gather and emit post-function debug information.
2975 ///
2976 void DwarfWriter::EndFunction() {
2977   DW->EndFunction();
2978 }