Emit debug info, only if at least one compile unit is seen.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfWriter.cpp
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/DwarfWriter.h"
15
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineLocation.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include <ostream>
42 #include <string>
43 using namespace llvm;
44 using namespace llvm::dwarf;
45
46 static RegisterPass<DwarfWriter>
47 X("dwarfwriter", "DWARF Information Writer");
48 char DwarfWriter::ID = 0;
49
50 namespace llvm {
51
52 //===----------------------------------------------------------------------===//
53
54 /// Configuration values for initial hash set sizes (log2).
55 ///
56 static const unsigned InitDiesSetSize          = 9; // 512
57 static const unsigned InitAbbreviationsSetSize = 9; // 512
58 static const unsigned InitValuesSetSize        = 9; // 512
59
60 //===----------------------------------------------------------------------===//
61 /// Forward declarations.
62 ///
63 class DIE;
64 class DIEValue;
65
66 //===----------------------------------------------------------------------===//
67 /// Utility routines.
68 ///
69 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the            
70 /// specified value in their initializer somewhere.                                       
71 static void
72 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
73   // Scan though value users.                                                             
74   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
75     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
76       // If the user is a GlobalVariable then add to result.                              
77       Result.push_back(GV);
78     } else if (Constant *C = dyn_cast<Constant>(*I)) {
79       // If the user is a constant variable then scan its users                           
80       getGlobalVariablesUsing(C, Result);
81     }
82   }
83 }
84
85 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the              
86 /// named GlobalVariable.                                                                 
87 static void
88 getGlobalVariablesUsing(Module &M, const std::string &RootName,
89                         std::vector<GlobalVariable*> &Result) {
90   std::vector<const Type*> FieldTypes;
91   FieldTypes.push_back(Type::Int32Ty);
92   FieldTypes.push_back(Type::Int32Ty);
93
94   // Get the GlobalVariable root.                                                         
95   GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
96                                                 StructType::get(FieldTypes));
97
98   // If present and linkonce then scan for users.                                         
99   if (UseRoot && UseRoot->hasLinkOnceLinkage())
100     getGlobalVariablesUsing(UseRoot, Result);
101 }
102
103 //===----------------------------------------------------------------------===//
104 /// DWLabel - Labels are used to track locations in the assembler file.
105 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
106 /// where the tag is a category of label (Ex. location) and number is a value
107 /// unique in that category.
108 class DWLabel {
109 public:
110   /// Tag - Label category tag. Should always be a staticly declared C string.
111   ///
112   const char *Tag;
113
114   /// Number - Value to make label unique.
115   ///
116   unsigned    Number;
117
118   DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
119
120   void Profile(FoldingSetNodeID &ID) const {
121     ID.AddString(std::string(Tag));
122     ID.AddInteger(Number);
123   }
124
125 #ifndef NDEBUG
126   void print(std::ostream *O) const {
127     if (O) print(*O);
128   }
129   void print(std::ostream &O) const {
130     O << "." << Tag;
131     if (Number) O << Number;
132   }
133 #endif
134 };
135
136 //===----------------------------------------------------------------------===//
137 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
138 /// Dwarf abbreviation.
139 class DIEAbbrevData {
140 private:
141   /// Attribute - Dwarf attribute code.
142   ///
143   unsigned Attribute;
144
145   /// Form - Dwarf form code.
146   ///
147   unsigned Form;
148
149 public:
150   DIEAbbrevData(unsigned A, unsigned F)
151   : Attribute(A)
152   , Form(F)
153   {}
154
155   // Accessors.
156   unsigned getAttribute() const { return Attribute; }
157   unsigned getForm()      const { return Form; }
158
159   /// Profile - Used to gather unique data for the abbreviation folding set.
160   ///
161   void Profile(FoldingSetNodeID &ID)const  {
162     ID.AddInteger(Attribute);
163     ID.AddInteger(Form);
164   }
165 };
166
167 //===----------------------------------------------------------------------===//
168 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
169 /// information object.
170 class DIEAbbrev : public FoldingSetNode {
171 private:
172   /// Tag - Dwarf tag code.
173   ///
174   unsigned Tag;
175
176   /// Unique number for node.
177   ///
178   unsigned Number;
179
180   /// ChildrenFlag - Dwarf children flag.
181   ///
182   unsigned ChildrenFlag;
183
184   /// Data - Raw data bytes for abbreviation.
185   ///
186   SmallVector<DIEAbbrevData, 8> Data;
187
188 public:
189
190   DIEAbbrev(unsigned T, unsigned C)
191   : Tag(T)
192   , ChildrenFlag(C)
193   , Data()
194   {}
195   ~DIEAbbrev() {}
196
197   // Accessors.
198   unsigned getTag()                           const { return Tag; }
199   unsigned getNumber()                        const { return Number; }
200   unsigned getChildrenFlag()                  const { return ChildrenFlag; }
201   const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
202   void setTag(unsigned T)                           { Tag = T; }
203   void setChildrenFlag(unsigned CF)                 { ChildrenFlag = CF; }
204   void setNumber(unsigned N)                        { Number = N; }
205
206   /// AddAttribute - Adds another set of attribute information to the
207   /// abbreviation.
208   void AddAttribute(unsigned Attribute, unsigned Form) {
209     Data.push_back(DIEAbbrevData(Attribute, Form));
210   }
211
212   /// AddFirstAttribute - Adds a set of attribute information to the front
213   /// of the abbreviation.
214   void AddFirstAttribute(unsigned Attribute, unsigned Form) {
215     Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
216   }
217
218   /// Profile - Used to gather unique data for the abbreviation folding set.
219   ///
220   void Profile(FoldingSetNodeID &ID) {
221     ID.AddInteger(Tag);
222     ID.AddInteger(ChildrenFlag);
223
224     // For each attribute description.
225     for (unsigned i = 0, N = Data.size(); i < N; ++i)
226       Data[i].Profile(ID);
227   }
228
229   /// Emit - Print the abbreviation using the specified Dwarf writer.
230   ///
231   void Emit(const DwarfDebug &DD) const;
232
233 #ifndef NDEBUG
234   void print(std::ostream *O) {
235     if (O) print(*O);
236   }
237   void print(std::ostream &O);
238   void dump();
239 #endif
240 };
241
242 //===----------------------------------------------------------------------===//
243 /// DIE - A structured debug information entry.  Has an abbreviation which
244 /// describes it's organization.
245 class DIE : public FoldingSetNode {
246 protected:
247   /// Abbrev - Buffer for constructing abbreviation.
248   ///
249   DIEAbbrev Abbrev;
250
251   /// Offset - Offset in debug info section.
252   ///
253   unsigned Offset;
254
255   /// Size - Size of instance + children.
256   ///
257   unsigned Size;
258
259   /// Children DIEs.
260   ///
261   std::vector<DIE *> Children;
262
263   /// Attributes values.
264   ///
265   SmallVector<DIEValue*, 32> Values;
266
267 public:
268   explicit DIE(unsigned Tag)
269   : Abbrev(Tag, DW_CHILDREN_no)
270   , Offset(0)
271   , Size(0)
272   , Children()
273   , Values()
274   {}
275   virtual ~DIE();
276
277   // Accessors.
278   DIEAbbrev &getAbbrev()                           { return Abbrev; }
279   unsigned   getAbbrevNumber()               const {
280     return Abbrev.getNumber();
281   }
282   unsigned getTag()                          const { return Abbrev.getTag(); }
283   unsigned getOffset()                       const { return Offset; }
284   unsigned getSize()                         const { return Size; }
285   const std::vector<DIE *> &getChildren()    const { return Children; }
286   SmallVector<DIEValue*, 32> &getValues()       { return Values; }
287   void setTag(unsigned Tag)                  { Abbrev.setTag(Tag); }
288   void setOffset(unsigned O)                 { Offset = O; }
289   void setSize(unsigned S)                   { Size = S; }
290
291   /// AddValue - Add a value and attributes to a DIE.
292   ///
293   void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
294     Abbrev.AddAttribute(Attribute, Form);
295     Values.push_back(Value);
296   }
297
298   /// SiblingOffset - Return the offset of the debug information entry's
299   /// sibling.
300   unsigned SiblingOffset() const { return Offset + Size; }
301
302   /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
303   ///
304   void AddSiblingOffset();
305
306   /// AddChild - Add a child to the DIE.
307   ///
308   void AddChild(DIE *Child) {
309     Abbrev.setChildrenFlag(DW_CHILDREN_yes);
310     Children.push_back(Child);
311   }
312
313   /// Detach - Detaches objects connected to it after copying.
314   ///
315   void Detach() {
316     Children.clear();
317   }
318
319   /// Profile - Used to gather unique data for the value folding set.
320   ///
321   void Profile(FoldingSetNodeID &ID) ;
322
323 #ifndef NDEBUG
324   void print(std::ostream *O, unsigned IncIndent = 0) {
325     if (O) print(*O, IncIndent);
326   }
327   void print(std::ostream &O, unsigned IncIndent = 0);
328   void dump();
329 #endif
330 };
331
332 //===----------------------------------------------------------------------===//
333 /// DIEValue - A debug information entry value.
334 ///
335 class DIEValue : public FoldingSetNode {
336 public:
337   enum {
338     isInteger,
339     isString,
340     isLabel,
341     isAsIsLabel,
342     isSectionOffset,
343     isDelta,
344     isEntry,
345     isBlock
346   };
347
348   /// Type - Type of data stored in the value.
349   ///
350   unsigned Type;
351
352   explicit DIEValue(unsigned T)
353   : Type(T)
354   {}
355   virtual ~DIEValue() {}
356
357   // Accessors
358   unsigned getType()  const { return Type; }
359
360   // Implement isa/cast/dyncast.
361   static bool classof(const DIEValue *) { return true; }
362
363   /// EmitValue - Emit value via the Dwarf writer.
364   ///
365   virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
366
367   /// SizeOf - Return the size of a value in bytes.
368   ///
369   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
370
371   /// Profile - Used to gather unique data for the value folding set.
372   ///
373   virtual void Profile(FoldingSetNodeID &ID) = 0;
374
375 #ifndef NDEBUG
376   void print(std::ostream *O) {
377     if (O) print(*O);
378   }
379   virtual void print(std::ostream &O) = 0;
380   void dump();
381 #endif
382 };
383
384 //===----------------------------------------------------------------------===//
385 /// DWInteger - An integer value DIE.
386 ///
387 class DIEInteger : public DIEValue {
388 private:
389   uint64_t Integer;
390
391 public:
392   explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
393
394   // Implement isa/cast/dyncast.
395   static bool classof(const DIEInteger *) { return true; }
396   static bool classof(const DIEValue *I)  { return I->Type == isInteger; }
397
398   /// BestForm - Choose the best form for integer.
399   ///
400   static unsigned BestForm(bool IsSigned, uint64_t Integer) {
401     if (IsSigned) {
402       if ((char)Integer == (signed)Integer)   return DW_FORM_data1;
403       if ((short)Integer == (signed)Integer)  return DW_FORM_data2;
404       if ((int)Integer == (signed)Integer)    return DW_FORM_data4;
405     } else {
406       if ((unsigned char)Integer == Integer)  return DW_FORM_data1;
407       if ((unsigned short)Integer == Integer) return DW_FORM_data2;
408       if ((unsigned int)Integer == Integer)   return DW_FORM_data4;
409     }
410     return DW_FORM_data8;
411   }
412
413   /// EmitValue - Emit integer of appropriate size.
414   ///
415   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
416
417   /// SizeOf - Determine size of integer value in bytes.
418   ///
419   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
420
421   /// Profile - Used to gather unique data for the value folding set.
422   ///
423   static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
424     ID.AddInteger(isInteger);
425     ID.AddInteger(Integer);
426   }
427   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
428
429 #ifndef NDEBUG
430   virtual void print(std::ostream &O) {
431     O << "Int: " << (int64_t)Integer
432       << "  0x" << std::hex << Integer << std::dec;
433   }
434 #endif
435 };
436
437 //===----------------------------------------------------------------------===//
438 /// DIEString - A string value DIE.
439 ///
440 class DIEString : public DIEValue {
441 public:
442   const std::string String;
443
444   explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
445
446   // Implement isa/cast/dyncast.
447   static bool classof(const DIEString *) { return true; }
448   static bool classof(const DIEValue *S) { return S->Type == isString; }
449
450   /// EmitValue - Emit string value.
451   ///
452   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
453
454   /// SizeOf - Determine size of string value in bytes.
455   ///
456   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
457     return String.size() + sizeof(char); // sizeof('\0');
458   }
459
460   /// Profile - Used to gather unique data for the value folding set.
461   ///
462   static void Profile(FoldingSetNodeID &ID, const std::string &String) {
463     ID.AddInteger(isString);
464     ID.AddString(String);
465   }
466   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
467
468 #ifndef NDEBUG
469   virtual void print(std::ostream &O) {
470     O << "Str: \"" << String << "\"";
471   }
472 #endif
473 };
474
475 //===----------------------------------------------------------------------===//
476 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
477 //
478 class DIEDwarfLabel : public DIEValue {
479 public:
480
481   const DWLabel Label;
482
483   explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
484
485   // Implement isa/cast/dyncast.
486   static bool classof(const DIEDwarfLabel *)  { return true; }
487   static bool classof(const DIEValue *L) { return L->Type == isLabel; }
488
489   /// EmitValue - Emit label value.
490   ///
491   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
492
493   /// SizeOf - Determine size of label value in bytes.
494   ///
495   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
496
497   /// Profile - Used to gather unique data for the value folding set.
498   ///
499   static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
500     ID.AddInteger(isLabel);
501     Label.Profile(ID);
502   }
503   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
504
505 #ifndef NDEBUG
506   virtual void print(std::ostream &O) {
507     O << "Lbl: ";
508     Label.print(O);
509   }
510 #endif
511 };
512
513
514 //===----------------------------------------------------------------------===//
515 /// DIEObjectLabel - A label to an object in code or data.
516 //
517 class DIEObjectLabel : public DIEValue {
518 public:
519   const std::string Label;
520
521   explicit DIEObjectLabel(const std::string &L)
522   : DIEValue(isAsIsLabel), Label(L) {}
523
524   // Implement isa/cast/dyncast.
525   static bool classof(const DIEObjectLabel *) { return true; }
526   static bool classof(const DIEValue *L)    { return L->Type == isAsIsLabel; }
527
528   /// EmitValue - Emit label value.
529   ///
530   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
531
532   /// SizeOf - Determine size of label value in bytes.
533   ///
534   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
535
536   /// Profile - Used to gather unique data for the value folding set.
537   ///
538   static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
539     ID.AddInteger(isAsIsLabel);
540     ID.AddString(Label);
541   }
542   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
543
544 #ifndef NDEBUG
545   virtual void print(std::ostream &O) {
546     O << "Obj: " << Label;
547   }
548 #endif
549 };
550
551 //===----------------------------------------------------------------------===//
552 /// DIESectionOffset - A section offset DIE.
553 //
554 class DIESectionOffset : public DIEValue {
555 public:
556   const DWLabel Label;
557   const DWLabel Section;
558   bool IsEH : 1;
559   bool UseSet : 1;
560
561   DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
562                    bool isEH = false, bool useSet = true)
563   : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
564                                IsEH(isEH), UseSet(useSet) {}
565
566   // Implement isa/cast/dyncast.
567   static bool classof(const DIESectionOffset *)  { return true; }
568   static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
569
570   /// EmitValue - Emit section offset.
571   ///
572   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
573
574   /// SizeOf - Determine size of section offset value in bytes.
575   ///
576   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
577
578   /// Profile - Used to gather unique data for the value folding set.
579   ///
580   static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
581                                             const DWLabel &Section) {
582     ID.AddInteger(isSectionOffset);
583     Label.Profile(ID);
584     Section.Profile(ID);
585     // IsEH and UseSet are specific to the Label/Section that we will emit
586     // the offset for; so Label/Section are enough for uniqueness.
587   }
588   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
589
590 #ifndef NDEBUG
591   virtual void print(std::ostream &O) {
592     O << "Off: ";
593     Label.print(O);
594     O << "-";
595     Section.print(O);
596     O << "-" << IsEH << "-" << UseSet;
597   }
598 #endif
599 };
600
601 //===----------------------------------------------------------------------===//
602 /// DIEDelta - A simple label difference DIE.
603 ///
604 class DIEDelta : public DIEValue {
605 public:
606   const DWLabel LabelHi;
607   const DWLabel LabelLo;
608
609   DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
610   : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
611
612   // Implement isa/cast/dyncast.
613   static bool classof(const DIEDelta *)  { return true; }
614   static bool classof(const DIEValue *D) { return D->Type == isDelta; }
615
616   /// EmitValue - Emit delta value.
617   ///
618   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
619
620   /// SizeOf - Determine size of delta value in bytes.
621   ///
622   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
623
624   /// Profile - Used to gather unique data for the value folding set.
625   ///
626   static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
627                                             const DWLabel &LabelLo) {
628     ID.AddInteger(isDelta);
629     LabelHi.Profile(ID);
630     LabelLo.Profile(ID);
631   }
632   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
633
634 #ifndef NDEBUG
635   virtual void print(std::ostream &O) {
636     O << "Del: ";
637     LabelHi.print(O);
638     O << "-";
639     LabelLo.print(O);
640   }
641 #endif
642 };
643
644 //===----------------------------------------------------------------------===//
645 /// DIEntry - A pointer to another debug information entry.  An instance of this
646 /// class can also be used as a proxy for a debug information entry not yet
647 /// defined (ie. types.)
648 class DIEntry : public DIEValue {
649 public:
650   DIE *Entry;
651
652   explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
653
654   // Implement isa/cast/dyncast.
655   static bool classof(const DIEntry *)   { return true; }
656   static bool classof(const DIEValue *E) { return E->Type == isEntry; }
657
658   /// EmitValue - Emit debug information entry offset.
659   ///
660   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
661
662   /// SizeOf - Determine size of debug information entry in bytes.
663   ///
664   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
665     return sizeof(int32_t);
666   }
667
668   /// Profile - Used to gather unique data for the value folding set.
669   ///
670   static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
671     ID.AddInteger(isEntry);
672     ID.AddPointer(Entry);
673   }
674   virtual void Profile(FoldingSetNodeID &ID) {
675     ID.AddInteger(isEntry);
676
677     if (Entry) {
678       ID.AddPointer(Entry);
679     } else {
680       ID.AddPointer(this);
681     }
682   }
683
684 #ifndef NDEBUG
685   virtual void print(std::ostream &O) {
686     O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
687   }
688 #endif
689 };
690
691 //===----------------------------------------------------------------------===//
692 /// DIEBlock - A block of values.  Primarily used for location expressions.
693 //
694 class DIEBlock : public DIEValue, public DIE {
695 public:
696   unsigned Size;                        // Size in bytes excluding size header.
697
698   DIEBlock()
699   : DIEValue(isBlock)
700   , DIE(0)
701   , Size(0)
702   {}
703   ~DIEBlock()  {
704   }
705
706   // Implement isa/cast/dyncast.
707   static bool classof(const DIEBlock *)  { return true; }
708   static bool classof(const DIEValue *E) { return E->Type == isBlock; }
709
710   /// ComputeSize - calculate the size of the block.
711   ///
712   unsigned ComputeSize(DwarfDebug &DD);
713
714   /// BestForm - Choose the best form for data.
715   ///
716   unsigned BestForm() const {
717     if ((unsigned char)Size == Size)  return DW_FORM_block1;
718     if ((unsigned short)Size == Size) return DW_FORM_block2;
719     if ((unsigned int)Size == Size)   return DW_FORM_block4;
720     return DW_FORM_block;
721   }
722
723   /// EmitValue - Emit block data.
724   ///
725   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
726
727   /// SizeOf - Determine size of block data in bytes.
728   ///
729   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
730
731
732   /// Profile - Used to gather unique data for the value folding set.
733   ///
734   virtual void Profile(FoldingSetNodeID &ID) {
735     ID.AddInteger(isBlock);
736     DIE::Profile(ID);
737   }
738
739 #ifndef NDEBUG
740   virtual void print(std::ostream &O) {
741     O << "Blk: ";
742     DIE::print(O, 5);
743   }
744 #endif
745 };
746
747 //===----------------------------------------------------------------------===//
748 /// CompileUnit - This dwarf writer support class manages information associate
749 /// with a source file.
750 class CompileUnit {
751 private:
752   /// Desc - Compile unit debug descriptor.
753   ///
754   CompileUnitDesc *Desc;
755
756   /// ID - File identifier for source.
757   ///
758   unsigned ID;
759
760   /// Die - Compile unit debug information entry.
761   ///
762   DIE *Die;
763
764   /// DescToDieMap - Tracks the mapping of unit level debug informaton
765   /// descriptors to debug information entries.
766   std::map<DebugInfoDesc *, DIE *> DescToDieMap;
767   DenseMap<GlobalVariable *, DIE *> GVToDieMap;
768
769   /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
770   /// descriptors to debug information entries using a DIEntry proxy.
771   std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
772   DenseMap<GlobalVariable *, DIEntry *> GVToDIEntryMap;
773
774   /// Globals - A map of globally visible named entities for this unit.
775   ///
776   std::map<std::string, DIE *> Globals;
777
778   /// DiesSet - Used to uniquely define dies within the compile unit.
779   ///
780   FoldingSet<DIE> DiesSet;
781
782   /// Dies - List of all dies in the compile unit.
783   ///
784   std::vector<DIE *> Dies;
785
786 public:
787   CompileUnit(unsigned I, DIE *D)
788     : ID(I), Die(D), DescToDieMap(), GVToDieMap(), DescToDIEntryMap(),
789       GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize), Dies()
790   {}
791
792   CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
793   : Desc(CUD)
794   , ID(I)
795   , Die(D)
796   , DescToDieMap()
797   , GVToDieMap()
798   , DescToDIEntryMap()
799   , GVToDIEntryMap()
800   , Globals()
801   , DiesSet(InitDiesSetSize)
802   , Dies()
803   {}
804
805   ~CompileUnit() {
806     delete Die;
807
808     for (unsigned i = 0, N = Dies.size(); i < N; ++i)
809       delete Dies[i];
810   }
811
812   // Accessors.
813   CompileUnitDesc *getDesc() const { return Desc; }
814   unsigned getID()           const { return ID; }
815   DIE* getDie()              const { return Die; }
816   std::map<std::string, DIE *> &getGlobals() { return Globals; }
817
818   /// hasContent - Return true if this compile unit has something to write out.
819   ///
820   bool hasContent() const {
821     return !Die->getChildren().empty();
822   }
823
824   /// AddGlobal - Add a new global entity to the compile unit.
825   ///
826   void AddGlobal(const std::string &Name, DIE *Die) {
827     Globals[Name] = Die;
828   }
829
830   /// getDieMapSlotFor - Returns the debug information entry map slot for the
831   /// specified debug descriptor.
832   DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
833     return DescToDieMap[DID];
834   }
835   DIE *&getDieMapSlotFor(GlobalVariable *GV) {
836     return GVToDieMap[GV];
837   }
838
839   /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
840   /// specified debug descriptor.
841   DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
842     return DescToDIEntryMap[DID];
843   }
844   DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
845     return GVToDIEntryMap[GV];
846   }
847
848   /// AddDie - Adds or interns the DIE to the compile unit.
849   ///
850   DIE *AddDie(DIE &Buffer) {
851     FoldingSetNodeID ID;
852     Buffer.Profile(ID);
853     void *Where;
854     DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
855
856     if (!Die) {
857       Die = new DIE(Buffer);
858       DiesSet.InsertNode(Die, Where);
859       this->Die->AddChild(Die);
860       Buffer.Detach();
861     }
862
863     return Die;
864   }
865 };
866
867 //===----------------------------------------------------------------------===//
868 /// Dwarf - Emits general Dwarf directives.
869 ///
870 class Dwarf {
871
872 protected:
873
874   //===--------------------------------------------------------------------===//
875   // Core attributes used by the Dwarf writer.
876   //
877
878   //
879   /// O - Stream to .s file.
880   ///
881   raw_ostream &O;
882
883   /// Asm - Target of Dwarf emission.
884   ///
885   AsmPrinter *Asm;
886
887   /// TAI - Target asm information.
888   const TargetAsmInfo *TAI;
889
890   /// TD - Target data.
891   const TargetData *TD;
892
893   /// RI - Register Information.
894   const TargetRegisterInfo *RI;
895
896   /// M - Current module.
897   ///
898   Module *M;
899
900   /// MF - Current machine function.
901   ///
902   MachineFunction *MF;
903
904   /// MMI - Collected machine module information.
905   ///
906   MachineModuleInfo *MMI;
907
908   /// SubprogramCount - The running count of functions being compiled.
909   ///
910   unsigned SubprogramCount;
911
912   /// Flavor - A unique string indicating what dwarf producer this is, used to
913   /// unique labels.
914   const char * const Flavor;
915
916   unsigned SetCounter;
917   Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
918         const char *flavor)
919   : O(OS)
920   , Asm(A)
921   , TAI(T)
922   , TD(Asm->TM.getTargetData())
923   , RI(Asm->TM.getRegisterInfo())
924   , M(NULL)
925   , MF(NULL)
926   , MMI(NULL)
927   , SubprogramCount(0)
928   , Flavor(flavor)
929   , SetCounter(1)
930   {
931   }
932
933 public:
934
935   //===--------------------------------------------------------------------===//
936   // Accessors.
937   //
938   AsmPrinter *getAsm() const { return Asm; }
939   MachineModuleInfo *getMMI() const { return MMI; }
940   const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
941   const TargetData *getTargetData() const { return TD; }
942
943   void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
944                                                                          const {
945     if (isInSection && TAI->getDwarfSectionOffsetDirective())
946       O << TAI->getDwarfSectionOffsetDirective();
947     else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
948       O << TAI->getData32bitsDirective();
949     else
950       O << TAI->getData64bitsDirective();
951   }
952
953   /// PrintLabelName - Print label name in form used by Dwarf writer.
954   ///
955   void PrintLabelName(DWLabel Label) const {
956     PrintLabelName(Label.Tag, Label.Number);
957   }
958   void PrintLabelName(const char *Tag, unsigned Number) const {
959     O << TAI->getPrivateGlobalPrefix() << Tag;
960     if (Number) O << Number;
961   }
962
963   void PrintLabelName(const char *Tag, unsigned Number,
964                       const char *Suffix) const {
965     O << TAI->getPrivateGlobalPrefix() << Tag;
966     if (Number) O << Number;
967     O << Suffix;
968   }
969
970   /// EmitLabel - Emit location label for internal use by Dwarf.
971   ///
972   void EmitLabel(DWLabel Label) const {
973     EmitLabel(Label.Tag, Label.Number);
974   }
975   void EmitLabel(const char *Tag, unsigned Number) const {
976     PrintLabelName(Tag, Number);
977     O << ":\n";
978   }
979
980   /// EmitReference - Emit a reference to a label.
981   ///
982   void EmitReference(DWLabel Label, bool IsPCRelative = false,
983                      bool Force32Bit = false) const {
984     EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
985   }
986   void EmitReference(const char *Tag, unsigned Number,
987                      bool IsPCRelative = false, bool Force32Bit = false) const {
988     PrintRelDirective(Force32Bit);
989     PrintLabelName(Tag, Number);
990
991     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
992   }
993   void EmitReference(const std::string &Name, bool IsPCRelative = false,
994                      bool Force32Bit = false) const {
995     PrintRelDirective(Force32Bit);
996
997     O << Name;
998
999     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
1000   }
1001
1002   /// EmitDifference - Emit the difference between two labels.  Some
1003   /// assemblers do not behave with absolute expressions with data directives,
1004   /// so there is an option (needsSet) to use an intermediary set expression.
1005   void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
1006                       bool IsSmall = false) {
1007     EmitDifference(LabelHi.Tag, LabelHi.Number,
1008                    LabelLo.Tag, LabelLo.Number,
1009                    IsSmall);
1010   }
1011   void EmitDifference(const char *TagHi, unsigned NumberHi,
1012                       const char *TagLo, unsigned NumberLo,
1013                       bool IsSmall = false) {
1014     if (TAI->needsSet()) {
1015       O << "\t.set\t";
1016       PrintLabelName("set", SetCounter, Flavor);
1017       O << ",";
1018       PrintLabelName(TagHi, NumberHi);
1019       O << "-";
1020       PrintLabelName(TagLo, NumberLo);
1021       O << "\n";
1022
1023       PrintRelDirective(IsSmall);
1024       PrintLabelName("set", SetCounter, Flavor);
1025       ++SetCounter;
1026     } else {
1027       PrintRelDirective(IsSmall);
1028
1029       PrintLabelName(TagHi, NumberHi);
1030       O << "-";
1031       PrintLabelName(TagLo, NumberLo);
1032     }
1033   }
1034
1035   void EmitSectionOffset(const char* Label, const char* Section,
1036                          unsigned LabelNumber, unsigned SectionNumber,
1037                          bool IsSmall = false, bool isEH = false,
1038                          bool useSet = true) {
1039     bool printAbsolute = false;
1040     if (isEH)
1041       printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1042     else
1043       printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1044
1045     if (TAI->needsSet() && useSet) {
1046       O << "\t.set\t";
1047       PrintLabelName("set", SetCounter, Flavor);
1048       O << ",";
1049       PrintLabelName(Label, LabelNumber);
1050
1051       if (!printAbsolute) {
1052         O << "-";
1053         PrintLabelName(Section, SectionNumber);
1054       }
1055       O << "\n";
1056
1057       PrintRelDirective(IsSmall);
1058
1059       PrintLabelName("set", SetCounter, Flavor);
1060       ++SetCounter;
1061     } else {
1062       PrintRelDirective(IsSmall, true);
1063
1064       PrintLabelName(Label, LabelNumber);
1065
1066       if (!printAbsolute) {
1067         O << "-";
1068         PrintLabelName(Section, SectionNumber);
1069       }
1070     }
1071   }
1072
1073   /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1074   /// frame.
1075   void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1076                       const std::vector<MachineMove> &Moves, bool isEH) {
1077     int stackGrowth =
1078         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1079           TargetFrameInfo::StackGrowsUp ?
1080             TD->getPointerSize() : -TD->getPointerSize();
1081     bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1082
1083     for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1084       const MachineMove &Move = Moves[i];
1085       unsigned LabelID = Move.getLabelID();
1086
1087       if (LabelID) {
1088         LabelID = MMI->MappedLabel(LabelID);
1089
1090         // Throw out move if the label is invalid.
1091         if (!LabelID) continue;
1092       }
1093
1094       const MachineLocation &Dst = Move.getDestination();
1095       const MachineLocation &Src = Move.getSource();
1096
1097       // Advance row if new location.
1098       if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1099         Asm->EmitInt8(DW_CFA_advance_loc4);
1100         Asm->EOL("DW_CFA_advance_loc4");
1101         EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1102         Asm->EOL();
1103
1104         BaseLabelID = LabelID;
1105         BaseLabel = "label";
1106         IsLocal = true;
1107       }
1108
1109       // If advancing cfa.
1110       if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1111         if (!Src.isReg()) {
1112           if (Src.getReg() == MachineLocation::VirtualFP) {
1113             Asm->EmitInt8(DW_CFA_def_cfa_offset);
1114             Asm->EOL("DW_CFA_def_cfa_offset");
1115           } else {
1116             Asm->EmitInt8(DW_CFA_def_cfa);
1117             Asm->EOL("DW_CFA_def_cfa");
1118             Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1119             Asm->EOL("Register");
1120           }
1121
1122           int Offset = -Src.getOffset();
1123
1124           Asm->EmitULEB128Bytes(Offset);
1125           Asm->EOL("Offset");
1126         } else {
1127           assert(0 && "Machine move no supported yet.");
1128         }
1129       } else if (Src.isReg() &&
1130         Src.getReg() == MachineLocation::VirtualFP) {
1131         if (Dst.isReg()) {
1132           Asm->EmitInt8(DW_CFA_def_cfa_register);
1133           Asm->EOL("DW_CFA_def_cfa_register");
1134           Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1135           Asm->EOL("Register");
1136         } else {
1137           assert(0 && "Machine move no supported yet.");
1138         }
1139       } else {
1140         unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1141         int Offset = Dst.getOffset() / stackGrowth;
1142
1143         if (Offset < 0) {
1144           Asm->EmitInt8(DW_CFA_offset_extended_sf);
1145           Asm->EOL("DW_CFA_offset_extended_sf");
1146           Asm->EmitULEB128Bytes(Reg);
1147           Asm->EOL("Reg");
1148           Asm->EmitSLEB128Bytes(Offset);
1149           Asm->EOL("Offset");
1150         } else if (Reg < 64) {
1151           Asm->EmitInt8(DW_CFA_offset + Reg);
1152           if (VerboseAsm)
1153             Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1154           else
1155             Asm->EOL();
1156           Asm->EmitULEB128Bytes(Offset);
1157           Asm->EOL("Offset");
1158         } else {
1159           Asm->EmitInt8(DW_CFA_offset_extended);
1160           Asm->EOL("DW_CFA_offset_extended");
1161           Asm->EmitULEB128Bytes(Reg);
1162           Asm->EOL("Reg");
1163           Asm->EmitULEB128Bytes(Offset);
1164           Asm->EOL("Offset");
1165         }
1166       }
1167     }
1168   }
1169
1170 };
1171
1172 //===----------------------------------------------------------------------===//
1173 /// SrcLineInfo - This class is used to record source line correspondence.
1174 ///
1175 class SrcLineInfo {
1176   unsigned Line;                        // Source line number.
1177   unsigned Column;                      // Source column.
1178   unsigned SourceID;                    // Source ID number.
1179   unsigned LabelID;                     // Label in code ID number.
1180 public:
1181   SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1182   : Line(L), Column(C), SourceID(S), LabelID(I) {}
1183   
1184   // Accessors
1185   unsigned getLine()     const { return Line; }
1186   unsigned getColumn()   const { return Column; }
1187   unsigned getSourceID() const { return SourceID; }
1188   unsigned getLabelID()  const { return LabelID; }
1189 };
1190
1191
1192 //===----------------------------------------------------------------------===//
1193 /// SrcFileInfo - This class is used to track source information.
1194 ///
1195 class SrcFileInfo {
1196   unsigned DirectoryID;                 // Directory ID number.
1197   std::string Name;                     // File name (not including directory.)
1198 public:
1199   SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
1200             
1201   // Accessors
1202   unsigned getDirectoryID()    const { return DirectoryID; }
1203   const std::string &getName() const { return Name; }
1204
1205   /// operator== - Used by UniqueVector to locate entry.
1206   ///
1207   bool operator==(const SourceFileInfo &SI) const {
1208     return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
1209   }
1210
1211   /// operator< - Used by UniqueVector to locate entry.
1212   ///
1213   bool operator<(const SrcFileInfo &SI) const {
1214     return getDirectoryID() < SI.getDirectoryID() ||
1215           (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
1216   }
1217 };
1218
1219 //===----------------------------------------------------------------------===//
1220 /// DbgVariable - This class is used to track local variable information.
1221 ///
1222 class DbgVariable {
1223 private:
1224   DIVariable *Var;                   // Variable Descriptor.
1225   unsigned FrameIndex;               // Variable frame index.
1226
1227 public:
1228   DbgVariable(DIVariable *V, unsigned I) : Var(V), FrameIndex(I)  {}
1229   
1230   // Accessors.
1231   DIVariable *getVariable()  const { return Var; }
1232   unsigned getFrameIndex() const { return FrameIndex; }
1233 };
1234
1235 //===----------------------------------------------------------------------===//
1236 /// DbgScope - This class is used to track scope information.
1237 ///
1238 class DbgScope {
1239 private:
1240   DbgScope *Parent;                   // Parent to this scope.
1241   DIDescriptor *Desc;                 // Debug info descriptor for scope.
1242                                       // Either subprogram or block.
1243   unsigned StartLabelID;              // Label ID of the beginning of scope.
1244   unsigned EndLabelID;                // Label ID of the end of scope.
1245   SmallVector<DbgScope *, 4> Scopes;     // Scopes defined in scope.
1246   SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1247   
1248 public:
1249   DbgScope(DbgScope *P, DIDescriptor *D)
1250   : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1251   {}
1252   ~DbgScope() {
1253     for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1254     for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1255   }
1256   
1257   // Accessors.
1258   DbgScope *getParent()        const { return Parent; }
1259   DIDescriptor *getDesc()       const { return Desc; }
1260   unsigned getStartLabelID()     const { return StartLabelID; }
1261   unsigned getEndLabelID()       const { return EndLabelID; }
1262   SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1263   SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1264   void setStartLabelID(unsigned S) { StartLabelID = S; }
1265   void setEndLabelID(unsigned E)   { EndLabelID = E; }
1266   
1267   /// AddScope - Add a scope to the scope.
1268   ///
1269   void AddScope(DbgScope *S) { Scopes.push_back(S); }
1270   
1271   /// AddVariable - Add a variable to the scope.
1272   ///
1273   void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1274 };
1275
1276 //===----------------------------------------------------------------------===//
1277 /// DwarfDebug - Emits Dwarf debug directives.
1278 ///
1279 class DwarfDebug : public Dwarf {
1280
1281 private:
1282   //===--------------------------------------------------------------------===//
1283   // Attributes used to construct specific Dwarf sections.
1284   //
1285
1286   /// CompileUnits - All the compile units involved in this build.  The index
1287   /// of each entry in this vector corresponds to the sources in MMI.
1288   std::vector<CompileUnit *> CompileUnits;
1289   DenseMap<Value *, CompileUnit *> DW_CUs;
1290
1291   /// AbbreviationsSet - Used to uniquely define abbreviations.
1292   ///
1293   FoldingSet<DIEAbbrev> AbbreviationsSet;
1294
1295   /// Abbreviations - A list of all the unique abbreviations in use.
1296   ///
1297   std::vector<DIEAbbrev *> Abbreviations;
1298
1299   /// ValuesSet - Used to uniquely define values.
1300   ///
1301   // Directories - Uniquing vector for directories.                                       
1302   UniqueVector<std::string> Directories;
1303
1304   // SourceFiles - Uniquing vector for source files.                                      
1305   UniqueVector<SrcFileInfo> SrcFiles;
1306
1307   // Lines - List of of source line correspondence.
1308   std::vector<SrcLineInfo> Lines;
1309
1310   FoldingSet<DIEValue> ValuesSet;
1311
1312   /// Values - A list of all the unique values in use.
1313   ///
1314   std::vector<DIEValue *> Values;
1315
1316   /// StringPool - A UniqueVector of strings used by indirect references.
1317   ///
1318   UniqueVector<std::string> StringPool;
1319
1320   /// UnitMap - Map debug information descriptor to compile unit.
1321   ///
1322   std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1323
1324   /// SectionMap - Provides a unique id per text section.
1325   ///
1326   UniqueVector<const Section*> SectionMap;
1327
1328   /// SectionSourceLines - Tracks line numbers per text section.
1329   ///
1330   std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1331
1332   /// didInitial - Flag to indicate if initial emission has been done.
1333   ///
1334   bool didInitial;
1335
1336   /// shouldEmit - Flag to indicate if debug information should be emitted.
1337   ///
1338   bool shouldEmit;
1339
1340   // RootScope - Top level scope for the current function.
1341   //
1342   DbgScope *RootDbgScope;
1343   
1344   // DbgScopeMap - Tracks the scopes in the current function.
1345   DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1346   
1347   struct FunctionDebugFrameInfo {
1348     unsigned Number;
1349     std::vector<MachineMove> Moves;
1350
1351     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1352       Number(Num), Moves(M) { }
1353   };
1354
1355   std::vector<FunctionDebugFrameInfo> DebugFrames;
1356
1357 public:
1358
1359   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1360   ///
1361   bool ShouldEmitDwarf() const { return shouldEmit; }
1362
1363   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1364   ///
1365   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1366     // Profile the node so that we can make it unique.
1367     FoldingSetNodeID ID;
1368     Abbrev.Profile(ID);
1369
1370     // Check the set for priors.
1371     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1372
1373     // If it's newly added.
1374     if (InSet == &Abbrev) {
1375       // Add to abbreviation list.
1376       Abbreviations.push_back(&Abbrev);
1377       // Assign the vector position + 1 as its number.
1378       Abbrev.setNumber(Abbreviations.size());
1379     } else {
1380       // Assign existing abbreviation number.
1381       Abbrev.setNumber(InSet->getNumber());
1382     }
1383   }
1384
1385   /// NewString - Add a string to the constant pool and returns a label.
1386   ///
1387   DWLabel NewString(const std::string &String) {
1388     unsigned StringID = StringPool.insert(String);
1389     return DWLabel("string", StringID);
1390   }
1391
1392   /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1393   /// entry.
1394   DIEntry *NewDIEntry(DIE *Entry = NULL) {
1395     DIEntry *Value;
1396
1397     if (Entry) {
1398       FoldingSetNodeID ID;
1399       DIEntry::Profile(ID, Entry);
1400       void *Where;
1401       Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1402
1403       if (Value) return Value;
1404
1405       Value = new DIEntry(Entry);
1406       ValuesSet.InsertNode(Value, Where);
1407     } else {
1408       Value = new DIEntry(Entry);
1409     }
1410
1411     Values.push_back(Value);
1412     return Value;
1413   }
1414
1415   /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1416   ///
1417   void SetDIEntry(DIEntry *Value, DIE *Entry) {
1418     Value->Entry = Entry;
1419     // Add to values set if not already there.  If it is, we merely have a
1420     // duplicate in the values list (no harm.)
1421     ValuesSet.GetOrInsertNode(Value);
1422   }
1423
1424   /// AddUInt - Add an unsigned integer attribute data and value.
1425   ///
1426   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1427     if (!Form) Form = DIEInteger::BestForm(false, Integer);
1428
1429     FoldingSetNodeID ID;
1430     DIEInteger::Profile(ID, Integer);
1431     void *Where;
1432     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1433     if (!Value) {
1434       Value = new DIEInteger(Integer);
1435       ValuesSet.InsertNode(Value, Where);
1436       Values.push_back(Value);
1437     }
1438
1439     Die->AddValue(Attribute, Form, Value);
1440   }
1441
1442   /// AddSInt - Add an signed integer attribute data and value.
1443   ///
1444   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1445     if (!Form) Form = DIEInteger::BestForm(true, Integer);
1446
1447     FoldingSetNodeID ID;
1448     DIEInteger::Profile(ID, (uint64_t)Integer);
1449     void *Where;
1450     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1451     if (!Value) {
1452       Value = new DIEInteger(Integer);
1453       ValuesSet.InsertNode(Value, Where);
1454       Values.push_back(Value);
1455     }
1456
1457     Die->AddValue(Attribute, Form, Value);
1458   }
1459
1460   /// AddString - Add a std::string attribute data and value.
1461   ///
1462   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1463                  const std::string &String) {
1464     FoldingSetNodeID ID;
1465     DIEString::Profile(ID, String);
1466     void *Where;
1467     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1468     if (!Value) {
1469       Value = new DIEString(String);
1470       ValuesSet.InsertNode(Value, Where);
1471       Values.push_back(Value);
1472     }
1473
1474     Die->AddValue(Attribute, Form, Value);
1475   }
1476
1477   /// AddLabel - Add a Dwarf label attribute data and value.
1478   ///
1479   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1480                      const DWLabel &Label) {
1481     FoldingSetNodeID ID;
1482     DIEDwarfLabel::Profile(ID, Label);
1483     void *Where;
1484     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1485     if (!Value) {
1486       Value = new DIEDwarfLabel(Label);
1487       ValuesSet.InsertNode(Value, Where);
1488       Values.push_back(Value);
1489     }
1490
1491     Die->AddValue(Attribute, Form, Value);
1492   }
1493
1494   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1495   ///
1496   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1497                       const std::string &Label) {
1498     FoldingSetNodeID ID;
1499     DIEObjectLabel::Profile(ID, Label);
1500     void *Where;
1501     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1502     if (!Value) {
1503       Value = new DIEObjectLabel(Label);
1504       ValuesSet.InsertNode(Value, Where);
1505       Values.push_back(Value);
1506     }
1507
1508     Die->AddValue(Attribute, Form, Value);
1509   }
1510
1511   /// AddSectionOffset - Add a section offset label attribute data and value.
1512   ///
1513   void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1514                         const DWLabel &Label, const DWLabel &Section,
1515                         bool isEH = false, bool useSet = true) {
1516     FoldingSetNodeID ID;
1517     DIESectionOffset::Profile(ID, Label, Section);
1518     void *Where;
1519     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1520     if (!Value) {
1521       Value = new DIESectionOffset(Label, Section, isEH, useSet);
1522       ValuesSet.InsertNode(Value, Where);
1523       Values.push_back(Value);
1524     }
1525
1526     Die->AddValue(Attribute, Form, Value);
1527   }
1528
1529   /// AddDelta - Add a label delta attribute data and value.
1530   ///
1531   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1532                           const DWLabel &Hi, const DWLabel &Lo) {
1533     FoldingSetNodeID ID;
1534     DIEDelta::Profile(ID, Hi, Lo);
1535     void *Where;
1536     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1537     if (!Value) {
1538       Value = new DIEDelta(Hi, Lo);
1539       ValuesSet.InsertNode(Value, Where);
1540       Values.push_back(Value);
1541     }
1542
1543     Die->AddValue(Attribute, Form, Value);
1544   }
1545
1546   /// AddDIEntry - Add a DIE attribute data and value.
1547   ///
1548   void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1549     Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1550   }
1551
1552   /// AddBlock - Add block data.
1553   ///
1554   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1555     Block->ComputeSize(*this);
1556     FoldingSetNodeID ID;
1557     Block->Profile(ID);
1558     void *Where;
1559     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1560     if (!Value) {
1561       Value = Block;
1562       ValuesSet.InsertNode(Value, Where);
1563       Values.push_back(Value);
1564     } else {
1565       // Already exists, reuse the previous one.
1566       delete Block;
1567       Block = cast<DIEBlock>(Value);
1568     }
1569
1570     Die->AddValue(Attribute, Block->BestForm(), Value);
1571   }
1572
1573 private:
1574
1575   /// AddSourceLine - Add location information to specified debug information
1576   /// entry.
1577   void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1578     if (File && Line) {
1579       CompileUnit *FileUnit = FindCompileUnit(File);
1580       unsigned FileID = FileUnit->getID();
1581       AddUInt(Die, DW_AT_decl_file, 0, FileID);
1582       AddUInt(Die, DW_AT_decl_line, 0, Line);
1583     }
1584   }
1585
1586   /// AddSourceLine - Add location information to specified debug information
1587   /// entry.
1588   void AddSourceLine(DIE *Die, DIVariable *V) {
1589     unsigned FileID = 0;
1590     unsigned Line = V->getLineNumber();
1591     if (V->getVersion() < DIDescriptor::Version7) {
1592       // Version6 or earlier. Use compile unit info to get file id.
1593       CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1594       FileID = Unit->getID();
1595     } else {
1596       // Version7 or newer, use filename and directory info from DIVariable
1597       // directly.
1598       unsigned DID = Directories.idFor(V->getDirectory());
1599       FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
1600     }
1601     AddUInt(Die, DW_AT_decl_file, 0, FileID);
1602     AddUInt(Die, DW_AT_decl_line, 0, Line);
1603   }
1604
1605   /// AddSourceLine - Add location information to specified debug information
1606   /// entry.
1607   void AddSourceLine(DIE *Die, DIGlobal *G) {
1608     unsigned FileID = 0;
1609     unsigned Line = G->getLineNumber();
1610     if (G->getVersion() < DIDescriptor::Version7) {
1611       // Version6 or earlier. Use compile unit info to get file id.
1612       CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1613       FileID = Unit->getID();
1614     } else {
1615       // Version7 or newer, use filename and directory info from DIGlobal
1616       // directly.
1617       unsigned DID = Directories.idFor(G->getDirectory());
1618       FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1619     }
1620     AddUInt(Die, DW_AT_decl_file, 0, FileID);
1621     AddUInt(Die, DW_AT_decl_line, 0, Line);
1622   }
1623
1624   void AddSourceLine(DIE *Die, DIType *G) {
1625     unsigned FileID = 0;
1626     unsigned Line = G->getLineNumber();
1627     if (G->getVersion() < DIDescriptor::Version7) {
1628       // Version6 or earlier. Use compile unit info to get file id.
1629       CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1630       FileID = Unit->getID();
1631     } else {
1632       // Version7 or newer, use filename and directory info from DIGlobal
1633       // directly.
1634       unsigned DID = Directories.idFor(G->getDirectory());
1635       FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1636     }
1637     AddUInt(Die, DW_AT_decl_file, 0, FileID);
1638     AddUInt(Die, DW_AT_decl_line, 0, Line);
1639   }
1640
1641   /// AddAddress - Add an address attribute to a die based on the location
1642   /// provided.
1643   void AddAddress(DIE *Die, unsigned Attribute,
1644                             const MachineLocation &Location) {
1645     unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1646     DIEBlock *Block = new DIEBlock();
1647
1648     if (Location.isReg()) {
1649       if (Reg < 32) {
1650         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1651       } else {
1652         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1653         AddUInt(Block, 0, DW_FORM_udata, Reg);
1654       }
1655     } else {
1656       if (Reg < 32) {
1657         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1658       } else {
1659         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1660         AddUInt(Block, 0, DW_FORM_udata, Reg);
1661       }
1662       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1663     }
1664
1665     AddBlock(Die, Attribute, 0, Block);
1666   }
1667
1668   /// AddBasicType - Add a new basic type attribute to the specified entity.
1669   ///
1670   void AddBasicType(DIE *Entity, CompileUnit *Unit,
1671                     const std::string &Name,
1672                     unsigned Encoding, unsigned Size) {
1673
1674     DIE Buffer(DW_TAG_base_type);
1675     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1676     AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1677     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1678     DIE *BasicTypeDie = Unit->AddDie(Buffer);
1679     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1680   }
1681
1682   /// AddPointerType - Add a new pointer type attribute to the specified entity.
1683   ///
1684   void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1685     DIE Buffer(DW_TAG_pointer_type);
1686     AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1687     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1688     DIE *PointerTypeDie =  Unit->AddDie(Buffer);
1689     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1690   }
1691
1692   /// AddType - Add a new type attribute to the specified entity.
1693   ///
1694   void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1695     if (!TyDesc) {
1696       AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1697     } else {
1698       // Check for pre-existence.
1699       DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1700
1701       // If it exists then use the existing value.
1702       if (Slot) {
1703         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1704         return;
1705       }
1706
1707       if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1708         // FIXME - Not sure why programs and variables are coming through here.
1709         // Short cut for handling subprogram types (not really a TyDesc.)
1710         AddPointerType(Entity, Unit, SubprogramTy->getName());
1711       } else if (GlobalVariableDesc *GlobalTy =
1712                                          dyn_cast<GlobalVariableDesc>(TyDesc)) {
1713         // FIXME - Not sure why programs and variables are coming through here.
1714         // Short cut for handling global variable types (not really a TyDesc.)
1715         AddPointerType(Entity, Unit, GlobalTy->getName());
1716       } else {
1717         // Set up proxy.
1718         Slot = NewDIEntry();
1719
1720         // Construct type.
1721         DIE Buffer(DW_TAG_base_type);
1722         ConstructType(Buffer, TyDesc, Unit);
1723
1724         // Add debug information entry to entity and unit.
1725         DIE *Die = Unit->AddDie(Buffer);
1726         SetDIEntry(Slot, Die);
1727         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1728       }
1729     }
1730   }
1731
1732   /// AddType - Add a new type attribute to the specified entity.
1733   void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1734     if (Ty.isNull()) {
1735       AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1736       return;
1737     }
1738
1739     // Check for pre-existence.
1740     DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1741     // If it exists then use the existing value.
1742     if (Slot) {
1743       Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1744       return;
1745     }
1746
1747     // Set up proxy. 
1748     Slot = NewDIEntry();
1749
1750     // Construct type.
1751     DIE Buffer(DW_TAG_base_type);
1752     if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1753       ConstructTypeDIE(DW_Unit, Buffer, BT);
1754     else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1755       ConstructTypeDIE(DW_Unit, Buffer, DT);
1756     else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1757       ConstructTypeDIE(DW_Unit, Buffer, CT);
1758
1759     // Add debug information entry to entity and unit.
1760     DIE *Die = DW_Unit->AddDie(Buffer);
1761     SetDIEntry(Slot, Die);
1762     Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1763   }
1764
1765   /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1766   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1767                         DIBasicType *BTy) {
1768     
1769     // Get core information.
1770     const std::string &Name = BTy->getName();
1771     Buffer.setTag(DW_TAG_base_type);
1772     AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BTy->getEncoding());
1773     // Add name if not anonymous or intermediate type.
1774     if (!Name.empty())
1775       AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1776     uint64_t Size = BTy->getSizeInBits() >> 3;
1777     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1778   }
1779
1780   /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1781   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1782                         DIDerivedType *DTy) {
1783
1784     // Get core information.
1785     const std::string &Name = DTy->getName();
1786     uint64_t Size = DTy->getSizeInBits() >> 3;
1787     unsigned Tag = DTy->getTag();
1788     // FIXME - Workaround for templates.
1789     if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1790
1791     Buffer.setTag(Tag);
1792     // Map to main type, void will not have a type.
1793     DIType FromTy = DTy->getTypeDerivedFrom();
1794     AddType(DW_Unit, &Buffer, FromTy);
1795
1796     // Add name if not anonymous or intermediate type.
1797     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1798
1799     // Add size if non-zero (derived types might be zero-sized.)
1800     if (Size)
1801       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1802
1803     // Add source line info if available and TyDesc is not a forward
1804     // declaration.
1805     // FIXME - Enable this. if (!DTy->isForwardDecl())
1806     // FIXME - Enable this.     AddSourceLine(&Buffer, *DTy);
1807   }
1808
1809   /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1810   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1811                         DICompositeType *CTy) {
1812
1813     // Get core information.                                                              
1814     const std::string &Name = CTy->getName();
1815     uint64_t Size = CTy->getSizeInBits() >> 3;
1816     unsigned Tag = CTy->getTag();
1817     switch (Tag) {
1818     case DW_TAG_vector_type:
1819     case DW_TAG_array_type:
1820       ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
1821       break;
1822     //FIXME - Enable this. 
1823     // case DW_TAG_enumeration_type:
1824     //  DIArray Elements = CTy->getTypeArray();
1825     //  // Add enumerators to enumeration type.
1826     //  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) 
1827     //   ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1828     //  break;
1829     case DW_TAG_subroutine_type: 
1830       {
1831         // Add prototype flag.
1832         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1833         DIArray Elements = CTy->getTypeArray();
1834         // Add return type.
1835         DIDescriptor RTy = Elements.getElement(0);
1836         if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
1837           AddType(DW_Unit, &Buffer, *BT);
1838         else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
1839           AddType(DW_Unit, &Buffer, *DT);
1840         else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
1841           AddType(DW_Unit, &Buffer, *CT);
1842
1843         //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1844         // Add arguments.
1845         for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1846           DIE *Arg = new DIE(DW_TAG_formal_parameter);
1847           DIDescriptor Ty = Elements.getElement(i);
1848           if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1849             AddType(DW_Unit, &Buffer, *BT);
1850           else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1851             AddType(DW_Unit, &Buffer, *DT);
1852           else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1853             AddType(DW_Unit, &Buffer, *CT);
1854           Buffer.AddChild(Arg);
1855         }
1856       }
1857       break;
1858     case DW_TAG_structure_type:
1859     case DW_TAG_union_type: 
1860       {
1861         // Add elements to structure type.
1862         DIArray Elements = CTy->getTypeArray();
1863         // Add elements to structure type.
1864         for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1865           DIDescriptor Element = Elements.getElement(i);
1866           if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
1867             ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
1868           else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
1869             ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1870           else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
1871             ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
1872         }
1873       }
1874       break;
1875     default:
1876       break;
1877     }
1878
1879     // Add name if not anonymous or intermediate type.
1880     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1881
1882     // Add size if non-zero (derived types might be zero-sized.)
1883     if (Size)
1884       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1885     else {
1886       // Add zero size even if it is not a forward declaration.
1887       // FIXME - Enable this.
1888       //      if (!CTy->isDefinition())
1889       //        AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1890       //      else
1891       //        AddUInt(&Buffer, DW_AT_byte_size, 0, 0); 
1892     }
1893
1894     // Add source line info if available and TyDesc is not a forward
1895     // declaration.
1896     // FIXME - Enable this.
1897     // if (CTy->isForwardDecl())                                            
1898     //   AddSourceLine(&Buffer, *CTy);                                    
1899   }
1900   
1901   // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1902   void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1903     int64_t L = SR->getLo();
1904     int64_t H = SR->getHi();
1905     DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1906     if (L != H) {
1907       AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1908       if (L)
1909         AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1910         AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1911     }
1912     Buffer.AddChild(DW_Subrange);
1913   }
1914
1915   /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1916   void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 
1917                              DICompositeType *CTy) {
1918     Buffer.setTag(DW_TAG_array_type);
1919     if (CTy->getTag() == DW_TAG_vector_type)
1920       AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1921     
1922     DIArray Elements = CTy->getTypeArray();
1923     // FIXME - Enable this. 
1924     AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1925
1926     // Construct an anonymous type for index type.
1927     DIE IdxBuffer(DW_TAG_base_type);
1928     AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1929     AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1930     DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1931
1932     // Add subranges to array type.
1933     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1934       DIDescriptor Element = Elements.getElement(i);
1935       if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
1936         ConstructSubrangeDIE(Buffer, SR, IndexTy);
1937     }
1938   }
1939
1940   /// ConstructEnumTypeDIE - Construct enum type DIE from 
1941   /// DIEnumerator.
1942   void ConstructEnumTypeDIE(CompileUnit *DW_Unit, 
1943                             DIE &Buffer, DIEnumerator *ETy) {
1944
1945     DIE *Enumerator = new DIE(DW_TAG_enumerator);
1946     AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1947     int64_t Value = ETy->getEnumValue();                             
1948     AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1949     Buffer.AddChild(Enumerator);
1950   }
1951
1952   /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1953   void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1954                              DIE &Buffer, DIGlobalVariable *V) {
1955
1956     DIE *VariableDie = new DIE(DW_TAG_variable);
1957     const std::string &LinkageName = V->getLinkageName();
1958     if (!LinkageName.empty())
1959       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1960                 LinkageName);
1961     // FIXME - Enable this. AddSourceLine(VariableDie, V);
1962     AddType(DW_Unit, VariableDie, V->getType());
1963     if (!V->isLocalToUnit())
1964       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1965     AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1966     Buffer.AddChild(VariableDie);
1967   }
1968
1969   /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1970   void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1971                              DIE &Buffer, DISubprogram *SP,
1972                              bool IsConstructor = false) {
1973     DIE *Method = new DIE(DW_TAG_subprogram);
1974     AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
1975     const std::string &LinkageName = SP->getLinkageName();
1976     if (!LinkageName.empty())
1977       AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1978     // FIXME - Enable this. AddSourceLine(Method, SP);
1979
1980     DICompositeType MTy = SP->getType();
1981     DIArray Args = MTy.getTypeArray();
1982
1983     // Add Return Type.
1984     if (!IsConstructor) {
1985       DIDescriptor Ty = Args.getElement(0);
1986       if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1987         AddType(DW_Unit, Method, *BT);
1988       else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1989         AddType(DW_Unit, Method, *DT);
1990       else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1991         AddType(DW_Unit, Method, *CT);
1992     }
1993
1994     // Add arguments.
1995     for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1996       DIE *Arg = new DIE(DW_TAG_formal_parameter);
1997       DIDescriptor Ty = Args.getElement(i);
1998       if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1999         AddType(DW_Unit, Method, *BT);
2000       else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
2001         AddType(DW_Unit, Method, *DT);
2002       else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
2003         AddType(DW_Unit, Method, *CT);
2004       AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
2005       Method->AddChild(Arg);
2006     }
2007
2008     if (!SP->isLocalToUnit())
2009       AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);                     
2010     Buffer.AddChild(Method);
2011   }
2012
2013   /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
2014  void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
2015                             DIDerivedType *DTy) {
2016     unsigned Tag = DTy->getTag();
2017     DIE *MemberDie = new DIE(Tag);
2018     if (!DTy->getName().empty())
2019       AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
2020     // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
2021
2022     DIType FromTy = DTy->getTypeDerivedFrom();
2023     AddType(DW_Unit, MemberDie, FromTy);
2024
2025     uint64_t Size = DTy->getSizeInBits();
2026     uint64_t Offset = DTy->getOffsetInBits();
2027
2028     // FIXME Handle bitfields                                                      
2029
2030     // Add size.
2031     AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
2032     // Add computation for offset.                                                        
2033     DIEBlock *Block = new DIEBlock();
2034     AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2035     AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
2036     AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
2037
2038     // FIXME Handle DW_AT_accessibility.
2039
2040     Buffer.AddChild(MemberDie);
2041   }
2042
2043   /// ConstructType - Adds all the required attributes to the type.
2044   ///
2045   void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
2046     // Get core information.
2047     const std::string &Name = TyDesc->getName();
2048     uint64_t Size = TyDesc->getSize() >> 3;
2049
2050     if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
2051       // Fundamental types like int, float, bool
2052       Buffer.setTag(DW_TAG_base_type);
2053       AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BasicTy->getEncoding());
2054     } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
2055       // Fetch tag.
2056       unsigned Tag = DerivedTy->getTag();
2057       // FIXME - Workaround for templates.
2058       if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
2059       // Pointers, typedefs et al.
2060       Buffer.setTag(Tag);
2061       // Map to main type, void will not have a type.
2062       if (TypeDesc *FromTy = DerivedTy->getFromType())
2063         AddType(&Buffer, FromTy, Unit);
2064     } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
2065       // Fetch tag.
2066       unsigned Tag = CompTy->getTag();
2067
2068       // Set tag accordingly.
2069       if (Tag == DW_TAG_vector_type)
2070         Buffer.setTag(DW_TAG_array_type);
2071       else
2072         Buffer.setTag(Tag);
2073
2074       std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
2075
2076       switch (Tag) {
2077       case DW_TAG_vector_type:
2078         AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
2079         // Fall thru
2080       case DW_TAG_array_type: {
2081         // Add element type.
2082         if (TypeDesc *FromTy = CompTy->getFromType())
2083           AddType(&Buffer, FromTy, Unit);
2084
2085         // Don't emit size attribute.
2086         Size = 0;
2087
2088         // Construct an anonymous type for index type.
2089         DIE Buffer(DW_TAG_base_type);
2090         AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
2091         AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
2092         DIE *IndexTy = Unit->AddDie(Buffer);
2093
2094         // Add subranges to array type.
2095         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2096           SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
2097           int64_t Lo = SRD->getLo();
2098           int64_t Hi = SRD->getHi();
2099           DIE *Subrange = new DIE(DW_TAG_subrange_type);
2100
2101           // If a range is available.
2102           if (Lo != Hi) {
2103             AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
2104             // Only add low if non-zero.
2105             if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
2106             AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
2107           }
2108
2109           Buffer.AddChild(Subrange);
2110         }
2111         break;
2112       }
2113       case DW_TAG_structure_type:
2114       case DW_TAG_union_type: {
2115         // Add elements to structure type.
2116         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2117           DebugInfoDesc *Element = Elements[i];
2118
2119           if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
2120             // Add field or base class.
2121             unsigned Tag = MemberDesc->getTag();
2122
2123             // Extract the basic information.
2124             const std::string &Name = MemberDesc->getName();
2125             uint64_t Size = MemberDesc->getSize();
2126             uint64_t Align = MemberDesc->getAlign();
2127             uint64_t Offset = MemberDesc->getOffset();
2128
2129             // Construct member debug information entry.
2130             DIE *Member = new DIE(Tag);
2131
2132             // Add name if not "".
2133             if (!Name.empty())
2134               AddString(Member, DW_AT_name, DW_FORM_string, Name);
2135
2136             // Add location if available.
2137             AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
2138
2139             // Most of the time the field info is the same as the members.
2140             uint64_t FieldSize = Size;
2141             uint64_t FieldAlign = Align;
2142             uint64_t FieldOffset = Offset;
2143
2144             // Set the member type.
2145             TypeDesc *FromTy = MemberDesc->getFromType();
2146             AddType(Member, FromTy, Unit);
2147
2148             // Walk up typedefs until a real size is found.
2149             while (FromTy) {
2150               if (FromTy->getTag() != DW_TAG_typedef) {
2151                 FieldSize = FromTy->getSize();
2152                 FieldAlign = FromTy->getAlign();
2153                 break;
2154               }
2155
2156               FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
2157             }
2158
2159             // Unless we have a bit field.
2160             if (Tag == DW_TAG_member && FieldSize != Size) {
2161               // Construct the alignment mask.
2162               uint64_t AlignMask = ~(FieldAlign - 1);
2163               // Determine the high bit + 1 of the declared size.
2164               uint64_t HiMark = (Offset + FieldSize) & AlignMask;
2165               // Work backwards to determine the base offset of the field.
2166               FieldOffset = HiMark - FieldSize;
2167               // Now normalize offset to the field.
2168               Offset -= FieldOffset;
2169
2170               // Maybe we need to work from the other end.
2171               if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
2172
2173               // Add size and offset.
2174               AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
2175               AddUInt(Member, DW_AT_bit_size, 0, Size);
2176               AddUInt(Member, DW_AT_bit_offset, 0, Offset);
2177             }
2178
2179             // Add computation for offset.
2180             DIEBlock *Block = new DIEBlock();
2181             AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2182             AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
2183             AddBlock(Member, DW_AT_data_member_location, 0, Block);
2184
2185             // Add accessibility (public default unless is base class.
2186             if (MemberDesc->isProtected()) {
2187               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
2188             } else if (MemberDesc->isPrivate()) {
2189               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
2190             } else if (Tag == DW_TAG_inheritance) {
2191               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
2192             }
2193
2194             Buffer.AddChild(Member);
2195           } else if (GlobalVariableDesc *StaticDesc =
2196                                         dyn_cast<GlobalVariableDesc>(Element)) {
2197             // Add static member.
2198
2199             // Construct member debug information entry.
2200             DIE *Static = new DIE(DW_TAG_variable);
2201
2202             // Add name and mangled name.
2203             const std::string &Name = StaticDesc->getName();
2204             const std::string &LinkageName = StaticDesc->getLinkageName();
2205             AddString(Static, DW_AT_name, DW_FORM_string, Name);
2206             if (!LinkageName.empty()) {
2207               AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
2208                                 LinkageName);
2209             }
2210
2211             // Add location.
2212             AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
2213
2214             // Add type.
2215             if (TypeDesc *StaticTy = StaticDesc->getType())
2216               AddType(Static, StaticTy, Unit);
2217
2218             // Add flags.
2219             if (!StaticDesc->isStatic())
2220               AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
2221             AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
2222
2223             Buffer.AddChild(Static);
2224           } else if (SubprogramDesc *MethodDesc =
2225                                             dyn_cast<SubprogramDesc>(Element)) {
2226             // Add member function.
2227
2228             // Construct member debug information entry.
2229             DIE *Method = new DIE(DW_TAG_subprogram);
2230
2231             // Add name and mangled name.
2232             const std::string &Name = MethodDesc->getName();
2233             const std::string &LinkageName = MethodDesc->getLinkageName();
2234
2235             AddString(Method, DW_AT_name, DW_FORM_string, Name);
2236             bool IsCTor = TyDesc->getName() == Name;
2237
2238             if (!LinkageName.empty()) {
2239               AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
2240                                 LinkageName);
2241             }
2242
2243             // Add location.
2244             AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
2245
2246             // Add type.
2247             if (CompositeTypeDesc *MethodTy =
2248                    dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
2249               // Get argument information.
2250               std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
2251
2252               // If not a ctor.
2253               if (!IsCTor) {
2254                 // Add return type.
2255                 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
2256               }
2257
2258               // Add arguments.
2259               for (unsigned i = 1, N = Args.size(); i < N; ++i) {
2260                 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2261                 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
2262                 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
2263                 Method->AddChild(Arg);
2264               }
2265             }
2266
2267             // Add flags.
2268             if (!MethodDesc->isStatic())
2269               AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2270             AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
2271
2272             Buffer.AddChild(Method);
2273           }
2274         }
2275         break;
2276       }
2277       case DW_TAG_enumeration_type: {
2278         // Add enumerators to enumeration type.
2279         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2280           EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
2281           const std::string &Name = ED->getName();
2282           int64_t Value = ED->getValue();
2283           DIE *Enumerator = new DIE(DW_TAG_enumerator);
2284           AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
2285           AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
2286           Buffer.AddChild(Enumerator);
2287         }
2288
2289         break;
2290       }
2291       case DW_TAG_subroutine_type: {
2292         // Add prototype flag.
2293         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
2294         // Add return type.
2295         AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
2296
2297         // Add arguments.
2298         for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
2299           DIE *Arg = new DIE(DW_TAG_formal_parameter);
2300           AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
2301           Buffer.AddChild(Arg);
2302         }
2303
2304         break;
2305       }
2306       default: break;
2307       }
2308     }
2309
2310     // Add name if not anonymous or intermediate type.
2311     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
2312
2313     // Add size if non-zero (derived types might be zero-sized.)
2314     if (Size)
2315       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
2316     else if (isa<CompositeTypeDesc>(TyDesc)) {
2317       // If TyDesc is a composite type, then add size even if it's zero unless
2318       // it's a forward declaration.
2319       if (TyDesc->isForwardDecl())
2320         AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
2321       else
2322         AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
2323     }
2324
2325     // Add source line info if available and TyDesc is not a forward
2326     // declaration.
2327     if (!TyDesc->isForwardDecl())
2328       AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
2329   }
2330
2331   /// NewCompileUnit - Create new compile unit and it's debug information entry.
2332   ///
2333   CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
2334     // Construct debug information entry.
2335     DIE *Die = new DIE(DW_TAG_compile_unit);
2336     AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2337               DWLabel("section_line", 0), DWLabel("section_line", 0), false);
2338     AddString(Die, DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
2339     AddUInt  (Die, DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
2340     AddString(Die, DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
2341     if (!UnitDesc->getDirectory().empty())
2342       AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
2343
2344     // Construct compile unit.
2345     CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
2346
2347     // Add Unit to compile unit map.
2348     DescToUnitMap[UnitDesc] = Unit;
2349
2350     return Unit;
2351   }
2352
2353   /// GetBaseCompileUnit - Get the main compile unit.
2354   ///
2355   CompileUnit *GetBaseCompileUnit() const {
2356     CompileUnit *Unit = CompileUnits[0];
2357     assert(Unit && "Missing compile unit.");
2358     return Unit;
2359   }
2360
2361   /// FindCompileUnit - Get the compile unit for the given descriptor.
2362   ///
2363   CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
2364     CompileUnit *Unit = DescToUnitMap[UnitDesc];
2365     assert(Unit && "Missing compile unit.");
2366     return Unit;
2367   }
2368
2369   /// FindCompileUnit - Get the compile unit for the given descriptor.                    
2370   ///                                                                                     
2371   CompileUnit *FindCompileUnit(DICompileUnit Unit) {
2372     CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
2373     assert(DW_Unit && "Missing compile unit.");
2374     return DW_Unit;
2375   }
2376
2377   /// NewGlobalVariable - Add a new global variable DIE.
2378   ///
2379   DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
2380     // Get the compile unit context.
2381     CompileUnitDesc *UnitDesc =
2382       static_cast<CompileUnitDesc *>(GVD->getContext());
2383     CompileUnit *Unit = GetBaseCompileUnit();
2384
2385     // Check for pre-existence.
2386     DIE *&Slot = Unit->getDieMapSlotFor(GVD);
2387     if (Slot) return Slot;
2388
2389     // Get the global variable itself.
2390     GlobalVariable *GV = GVD->getGlobalVariable();
2391
2392     const std::string &Name = GVD->getName();
2393     const std::string &FullName = GVD->getFullName();
2394     const std::string &LinkageName = GVD->getLinkageName();
2395     // Create the global's variable DIE.
2396     DIE *VariableDie = new DIE(DW_TAG_variable);
2397     AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2398     if (!LinkageName.empty()) {
2399       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2400                              LinkageName);
2401     }
2402     AddType(VariableDie, GVD->getType(), Unit);
2403     if (!GVD->isStatic())
2404       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2405
2406     // Add source line info if available.
2407     AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
2408
2409     // Add address.
2410     DIEBlock *Block = new DIEBlock();
2411     AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2412     AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
2413     AddBlock(VariableDie, DW_AT_location, 0, Block);
2414
2415     // Add to map.
2416     Slot = VariableDie;
2417
2418     // Add to context owner.
2419     Unit->getDie()->AddChild(VariableDie);
2420
2421     // Expose as global.
2422     // FIXME - need to check external flag.
2423     Unit->AddGlobal(FullName, VariableDie);
2424
2425     return VariableDie;
2426   }
2427
2428   /// NewSubprogram - Add a new subprogram DIE.
2429   ///
2430   DIE *NewSubprogram(SubprogramDesc *SPD) {
2431     // Get the compile unit context.
2432     CompileUnitDesc *UnitDesc =
2433       static_cast<CompileUnitDesc *>(SPD->getContext());
2434     CompileUnit *Unit = GetBaseCompileUnit();
2435
2436     // Check for pre-existence.
2437     DIE *&Slot = Unit->getDieMapSlotFor(SPD);
2438     if (Slot) return Slot;
2439
2440     // Gather the details (simplify add attribute code.)
2441     const std::string &Name = SPD->getName();
2442     const std::string &FullName = SPD->getFullName();
2443     const std::string &LinkageName = SPD->getLinkageName();
2444
2445     DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2446     AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
2447     if (!LinkageName.empty()) {
2448       AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2449                                LinkageName);
2450     }
2451     if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
2452     if (!SPD->isStatic())
2453       AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2454     AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2455
2456     // Add source line info if available.
2457     AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2458
2459     // Add to map.
2460     Slot = SubprogramDie;
2461
2462     // Add to context owner.
2463     Unit->getDie()->AddChild(SubprogramDie);
2464
2465     // Expose as global.
2466     Unit->AddGlobal(FullName, SubprogramDie);
2467
2468     return SubprogramDie;
2469   }
2470
2471   /// NewScopeVariable - Create a new scope variable.
2472   ///
2473   DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2474     // Get the descriptor.
2475     VariableDesc *VD = DV->getDesc();
2476
2477     // Translate tag to proper Dwarf tag.  The result variable is dropped for
2478     // now.
2479     unsigned Tag;
2480     switch (VD->getTag()) {
2481     case DW_TAG_return_variable:  return NULL;
2482     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
2483     case DW_TAG_auto_variable:    // fall thru
2484     default:                      Tag = DW_TAG_variable; break;
2485     }
2486
2487     // Define variable debug information entry.
2488     DIE *VariableDie = new DIE(Tag);
2489     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2490
2491     // Add source line info if available.
2492     AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2493
2494     // Add variable type.
2495     AddType(VariableDie, VD->getType(), Unit);
2496
2497     // Add variable address.
2498     MachineLocation Location;
2499     Location.set(RI->getFrameRegister(*MF),
2500                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2501     AddAddress(VariableDie, DW_AT_location, Location);
2502
2503     return VariableDie;
2504   }
2505
2506   /// NewScopeVariable - Create a new scope variable.
2507   ///
2508   DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
2509     // Get the descriptor.
2510     DIVariable *VD = DV->getVariable();
2511
2512     // Translate tag to proper Dwarf tag.  The result variable is dropped for
2513     // now.
2514     unsigned Tag;
2515     switch (VD->getTag()) {
2516     case DW_TAG_return_variable:  return NULL;
2517     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
2518     case DW_TAG_auto_variable:    // fall thru
2519     default:                      Tag = DW_TAG_variable; break;
2520     }
2521
2522     // Define variable debug information entry.
2523     DIE *VariableDie = new DIE(Tag);
2524     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2525
2526     // Add source line info if available.
2527     AddSourceLine(VariableDie, VD);
2528
2529     // Add variable type.
2530     AddType(Unit, VariableDie, VD->getType());
2531
2532     // Add variable address.
2533     MachineLocation Location;
2534     Location.set(RI->getFrameRegister(*MF),
2535                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2536     AddAddress(VariableDie, DW_AT_location, Location);
2537
2538     return VariableDie;
2539   }
2540
2541   /// getOrCreateScope - Returns the scope associated with the given descriptor.
2542   ///
2543   DbgScope *getOrCreateScope(GlobalVariable *V) {
2544     DbgScope *&Slot = DbgScopeMap[V];
2545     if (!Slot) {
2546       // FIXME - breaks down when the context is an inlined function.
2547       DIDescriptor ParentDesc;
2548       DIDescriptor *DB = new DIBlock(V);
2549       if (DIBlock *Block = dyn_cast<DIBlock>(DB)) {
2550         ParentDesc = Block->getContext();
2551       }
2552       DbgScope *Parent = ParentDesc.isNull() ? 
2553         NULL : getOrCreateScope(ParentDesc.getGV());
2554       Slot = new DbgScope(Parent, DB);
2555       if (Parent) {
2556         Parent->AddScope(Slot);
2557       } else if (RootDbgScope) {
2558         // FIXME - Add inlined function scopes to the root so we can delete
2559         // them later.  Long term, handle inlined functions properly.
2560         RootDbgScope->AddScope(Slot);
2561       } else {
2562         // First function is top level function.
2563         RootDbgScope = Slot;
2564       }
2565     }
2566     return Slot;
2567   }
2568
2569   /// ConstructDbgScope - Construct the components of a scope.
2570   ///
2571   void ConstructDbgScope(DbgScope *ParentScope,
2572                          unsigned ParentStartID, unsigned ParentEndID,
2573                          DIE *ParentDie, CompileUnit *Unit) {
2574     // Add variables to scope.
2575     SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2576     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2577       DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2578       if (VariableDie) ParentDie->AddChild(VariableDie);
2579     }
2580
2581     // Add nested scopes.
2582     SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2583     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2584       // Define the Scope debug information entry.
2585       DbgScope *Scope = Scopes[j];
2586       // FIXME - Ignore inlined functions for the time being.
2587       if (!Scope->getParent()) continue;
2588
2589       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2590       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2591
2592       // Ignore empty scopes.
2593       if (StartID == EndID && StartID != 0) continue;
2594       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2595
2596       if (StartID == ParentStartID && EndID == ParentEndID) {
2597         // Just add stuff to the parent scope.
2598         ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2599       } else {
2600         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2601
2602         // Add the scope bounds.
2603         if (StartID) {
2604           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2605                              DWLabel("label", StartID));
2606         } else {
2607           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2608                              DWLabel("func_begin", SubprogramCount));
2609         }
2610         if (EndID) {
2611           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2612                              DWLabel("label", EndID));
2613         } else {
2614           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2615                              DWLabel("func_end", SubprogramCount));
2616         }
2617
2618         // Add the scope contents.
2619         ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2620         ParentDie->AddChild(ScopeDie);
2621       }
2622     }
2623   }
2624
2625   /// ConstructRootDbgScope - Construct the scope for the subprogram.
2626   ///
2627   void ConstructRootDbgScope(DbgScope *RootScope) {
2628     // Exit if there is no root scope.
2629     if (!RootScope) return;
2630
2631     // Get the subprogram debug information entry.
2632     DISubprogram SPD(RootScope->getDesc()->getGV());
2633
2634     // Get the compile unit context.
2635     CompileUnit *Unit = FindCompileUnit(SPD.getCompileUnit());
2636
2637     // Get the subprogram die.
2638     DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2639     assert(SPDie && "Missing subprogram descriptor");
2640
2641     // Add the function bounds.
2642     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2643                     DWLabel("func_begin", SubprogramCount));
2644     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2645                     DWLabel("func_end", SubprogramCount));
2646     MachineLocation Location(RI->getFrameRegister(*MF));
2647     AddAddress(SPDie, DW_AT_frame_base, Location);
2648
2649     ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2650   }
2651
2652   /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2653   ///
2654   void ConstructDefaultDbgScope(MachineFunction *MF) {
2655     // Find the correct subprogram descriptor.
2656     std::string SPName = "llvm.dbg.subprograms";
2657     std::vector<GlobalVariable*> Result;
2658     getGlobalVariablesUsing(*M, SPName, Result);
2659     for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2660            E = Result.end(); I != E; ++I) {
2661
2662       DISubprogram *SPD = new DISubprogram(*I);
2663
2664       if (SPD->getName() == MF->getFunction()->getName()) {
2665         // Get the compile unit context.
2666         CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2667
2668         // Get the subprogram die.
2669         DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2670         assert(SPDie && "Missing subprogram descriptor");
2671
2672         // Add the function bounds.
2673         AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2674                  DWLabel("func_begin", SubprogramCount));
2675         AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2676                  DWLabel("func_end", SubprogramCount));
2677
2678         MachineLocation Location(RI->getFrameRegister(*MF));
2679         AddAddress(SPDie, DW_AT_frame_base, Location);
2680         return;
2681       }
2682     }
2683 #if 0
2684     // FIXME: This is causing an abort because C++ mangled names are compared
2685     // with their unmangled counterparts. See PR2885. Don't do this assert.
2686     assert(0 && "Couldn't find DIE for machine function!");
2687 #endif
2688   }
2689
2690   /// ConstructScope - Construct the components of a scope.
2691   ///
2692   void ConstructScope(DebugScope *ParentScope,
2693                       unsigned ParentStartID, unsigned ParentEndID,
2694                       DIE *ParentDie, CompileUnit *Unit) {
2695     // Add variables to scope.
2696     std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2697     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2698       DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2699       if (VariableDie) ParentDie->AddChild(VariableDie);
2700     }
2701
2702     // Add nested scopes.
2703     std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2704     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2705       // Define the Scope debug information entry.
2706       DebugScope *Scope = Scopes[j];
2707       // FIXME - Ignore inlined functions for the time being.
2708       if (!Scope->getParent()) continue;
2709
2710       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2711       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2712
2713       // Ignore empty scopes.
2714       if (StartID == EndID && StartID != 0) continue;
2715       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2716
2717       if (StartID == ParentStartID && EndID == ParentEndID) {
2718         // Just add stuff to the parent scope.
2719         ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2720       } else {
2721         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2722
2723         // Add the scope bounds.
2724         if (StartID) {
2725           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2726                              DWLabel("label", StartID));
2727         } else {
2728           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2729                              DWLabel("func_begin", SubprogramCount));
2730         }
2731         if (EndID) {
2732           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2733                              DWLabel("label", EndID));
2734         } else {
2735           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2736                              DWLabel("func_end", SubprogramCount));
2737         }
2738
2739         // Add the scope contents.
2740         ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2741         ParentDie->AddChild(ScopeDie);
2742       }
2743     }
2744   }
2745
2746   /// ConstructRootScope - Construct the scope for the subprogram.
2747   ///
2748   void ConstructRootScope(DebugScope *RootScope) {
2749     // Exit if there is no root scope.
2750     if (!RootScope) return;
2751
2752     // Get the subprogram debug information entry.
2753     SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2754
2755     // Get the compile unit context.
2756     CompileUnit *Unit = GetBaseCompileUnit();
2757
2758     // Get the subprogram die.
2759     DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2760     assert(SPDie && "Missing subprogram descriptor");
2761
2762     // Add the function bounds.
2763     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2764                     DWLabel("func_begin", SubprogramCount));
2765     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2766                     DWLabel("func_end", SubprogramCount));
2767     MachineLocation Location(RI->getFrameRegister(*MF));
2768     AddAddress(SPDie, DW_AT_frame_base, Location);
2769
2770     ConstructScope(RootScope, 0, 0, SPDie, Unit);
2771   }
2772
2773   /// ConstructDefaultScope - Construct a default scope for the subprogram.
2774   ///
2775   void ConstructDefaultScope(MachineFunction *MF) {
2776     // Find the correct subprogram descriptor.
2777     std::vector<SubprogramDesc *> Subprograms;
2778     MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2779
2780     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2781       SubprogramDesc *SPD = Subprograms[i];
2782
2783       if (SPD->getName() == MF->getFunction()->getName()) {
2784         // Get the compile unit context.
2785         CompileUnit *Unit = GetBaseCompileUnit();
2786
2787         // Get the subprogram die.
2788         DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2789         assert(SPDie && "Missing subprogram descriptor");
2790
2791         // Add the function bounds.
2792         AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2793                  DWLabel("func_begin", SubprogramCount));
2794         AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2795                  DWLabel("func_end", SubprogramCount));
2796
2797         MachineLocation Location(RI->getFrameRegister(*MF));
2798         AddAddress(SPDie, DW_AT_frame_base, Location);
2799         return;
2800       }
2801     }
2802 #if 0
2803     // FIXME: This is causing an abort because C++ mangled names are compared
2804     // with their unmangled counterparts. See PR2885. Don't do this assert.
2805     assert(0 && "Couldn't find DIE for machine function!");
2806 #endif
2807   }
2808
2809   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
2810   /// tools to recognize the object file contains Dwarf information.
2811   void EmitInitial() {
2812     // Check to see if we already emitted intial headers.
2813     if (didInitial) return;
2814     didInitial = true;
2815
2816     // Dwarf sections base addresses.
2817     if (TAI->doesDwarfRequireFrameSection()) {
2818       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2819       EmitLabel("section_debug_frame", 0);
2820     }
2821     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2822     EmitLabel("section_info", 0);
2823     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2824     EmitLabel("section_abbrev", 0);
2825     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2826     EmitLabel("section_aranges", 0);
2827     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2828     EmitLabel("section_macinfo", 0);
2829     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2830     EmitLabel("section_line", 0);
2831     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2832     EmitLabel("section_loc", 0);
2833     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2834     EmitLabel("section_pubnames", 0);
2835     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2836     EmitLabel("section_str", 0);
2837     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2838     EmitLabel("section_ranges", 0);
2839
2840     Asm->SwitchToSection(TAI->getTextSection());
2841     EmitLabel("text_begin", 0);
2842     Asm->SwitchToSection(TAI->getDataSection());
2843     EmitLabel("data_begin", 0);
2844   }
2845
2846   /// EmitDIE - Recusively Emits a debug information entry.
2847   ///
2848   void EmitDIE(DIE *Die) {
2849     // Get the abbreviation for this DIE.
2850     unsigned AbbrevNumber = Die->getAbbrevNumber();
2851     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2852
2853     Asm->EOL();
2854
2855     // Emit the code (index) for the abbreviation.
2856     Asm->EmitULEB128Bytes(AbbrevNumber);
2857
2858     if (VerboseAsm)
2859       Asm->EOL(std::string("Abbrev [" +
2860                            utostr(AbbrevNumber) +
2861                            "] 0x" + utohexstr(Die->getOffset()) +
2862                            ":0x" + utohexstr(Die->getSize()) + " " +
2863                            TagString(Abbrev->getTag())));
2864     else
2865       Asm->EOL();
2866
2867     SmallVector<DIEValue*, 32> &Values = Die->getValues();
2868     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2869
2870     // Emit the DIE attribute values.
2871     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2872       unsigned Attr = AbbrevData[i].getAttribute();
2873       unsigned Form = AbbrevData[i].getForm();
2874       assert(Form && "Too many attributes for DIE (check abbreviation)");
2875
2876       switch (Attr) {
2877       case DW_AT_sibling: {
2878         Asm->EmitInt32(Die->SiblingOffset());
2879         break;
2880       }
2881       default: {
2882         // Emit an attribute using the defined form.
2883         Values[i]->EmitValue(*this, Form);
2884         break;
2885       }
2886       }
2887
2888       Asm->EOL(AttributeString(Attr));
2889     }
2890
2891     // Emit the DIE children if any.
2892     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2893       const std::vector<DIE *> &Children = Die->getChildren();
2894
2895       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2896         EmitDIE(Children[j]);
2897       }
2898
2899       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2900     }
2901   }
2902
2903   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2904   ///
2905   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2906     // Get the children.
2907     const std::vector<DIE *> &Children = Die->getChildren();
2908
2909     // If not last sibling and has children then add sibling offset attribute.
2910     if (!Last && !Children.empty()) Die->AddSiblingOffset();
2911
2912     // Record the abbreviation.
2913     AssignAbbrevNumber(Die->getAbbrev());
2914
2915     // Get the abbreviation for this DIE.
2916     unsigned AbbrevNumber = Die->getAbbrevNumber();
2917     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2918
2919     // Set DIE offset
2920     Die->setOffset(Offset);
2921
2922     // Start the size with the size of abbreviation code.
2923     Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2924
2925     const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2926     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2927
2928     // Size the DIE attribute values.
2929     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2930       // Size attribute value.
2931       Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2932     }
2933
2934     // Size the DIE children if any.
2935     if (!Children.empty()) {
2936       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2937              "Children flag not set");
2938
2939       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2940         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2941       }
2942
2943       // End of children marker.
2944       Offset += sizeof(int8_t);
2945     }
2946
2947     Die->setSize(Offset - Die->getOffset());
2948     return Offset;
2949   }
2950
2951   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2952   ///
2953   void SizeAndOffsets() {
2954     // Process base compile unit.
2955     for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2956            CE = DW_CUs.end(); CI != CE; ++CI) {
2957       CompileUnit *Unit = CI->second;
2958       // Compute size of compile unit header
2959       unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2960         sizeof(int16_t) + // DWARF version number
2961         sizeof(int32_t) + // Offset Into Abbrev. Section
2962         sizeof(int8_t);   // Pointer Size (in bytes)
2963       SizeAndOffsetDie(Unit->getDie(), Offset, true);
2964     }
2965   }
2966
2967   /// EmitDebugInfo - Emit the debug info section.
2968   ///
2969   void EmitDebugInfo() {
2970     // Start debug info section.
2971     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2972
2973     for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2974            CE = DW_CUs.end(); CI != CE; ++CI) {
2975       CompileUnit *Unit = CI->second;
2976       DIE *Die = Unit->getDie();
2977       // Emit the compile units header.
2978       EmitLabel("info_begin", Unit->getID());
2979       // Emit size of content not including length itself
2980       unsigned ContentSize = Die->getSize() +
2981         sizeof(int16_t) + // DWARF version number
2982         sizeof(int32_t) + // Offset Into Abbrev. Section
2983         sizeof(int8_t) +  // Pointer Size (in bytes)
2984         sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2985       
2986       Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
2987       Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2988       EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2989       Asm->EOL("Offset Into Abbrev. Section");
2990       Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2991       
2992       EmitDIE(Die);
2993       // FIXME - extra padding for gdb bug.
2994       Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2995       Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2996       Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2997       Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2998       EmitLabel("info_end", Unit->getID());
2999       
3000       Asm->EOL();
3001     }
3002   }
3003
3004   /// EmitAbbreviations - Emit the abbreviation section.
3005   ///
3006   void EmitAbbreviations() const {
3007     // Check to see if it is worth the effort.
3008     if (!Abbreviations.empty()) {
3009       // Start the debug abbrev section.
3010       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
3011
3012       EmitLabel("abbrev_begin", 0);
3013
3014       // For each abbrevation.
3015       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3016         // Get abbreviation data
3017         const DIEAbbrev *Abbrev = Abbreviations[i];
3018
3019         // Emit the abbrevations code (base 1 index.)
3020         Asm->EmitULEB128Bytes(Abbrev->getNumber());
3021         Asm->EOL("Abbreviation Code");
3022
3023         // Emit the abbreviations data.
3024         Abbrev->Emit(*this);
3025
3026         Asm->EOL();
3027       }
3028
3029       // Mark end of abbreviations.
3030       Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
3031
3032       EmitLabel("abbrev_end", 0);
3033
3034       Asm->EOL();
3035     }
3036   }
3037
3038   /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
3039   /// the line matrix.
3040   ///
3041   void EmitEndOfLineMatrix(unsigned SectionEnd) {
3042     // Define last address of section.
3043     Asm->EmitInt8(0); Asm->EOL("Extended Op");
3044     Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3045     Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3046     EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
3047
3048     // Mark end of matrix.
3049     Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
3050     Asm->EmitULEB128Bytes(1); Asm->EOL();
3051     Asm->EmitInt8(1); Asm->EOL();
3052   }
3053
3054   /// EmitDebugLines - Emit source line information.
3055   ///
3056   void EmitDebugLines() {
3057     // If the target is using .loc/.file, the assembler will be emitting the
3058     // .debug_line table automatically.
3059     if (TAI->hasDotLocAndDotFile())
3060       return;
3061
3062     // Minimum line delta, thus ranging from -10..(255-10).
3063     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
3064     // Maximum line delta, thus ranging from -10..(255-10).
3065     const int MaxLineDelta = 255 + MinLineDelta;
3066
3067     // Start the dwarf line section.
3068     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
3069
3070     // Construct the section header.
3071
3072     EmitDifference("line_end", 0, "line_begin", 0, true);
3073     Asm->EOL("Length of Source Line Info");
3074     EmitLabel("line_begin", 0);
3075
3076     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3077
3078     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
3079     Asm->EOL("Prolog Length");
3080     EmitLabel("line_prolog_begin", 0);
3081
3082     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
3083
3084     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
3085
3086     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
3087
3088     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
3089
3090     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
3091
3092     // Line number standard opcode encodings argument count
3093     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
3094     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
3095     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
3096     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
3097     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
3098     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
3099     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
3100     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
3101     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
3102
3103     const UniqueVector<std::string> &Directories = MMI->getDirectories();
3104     const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3105
3106     // Emit directories.
3107     for (unsigned DirectoryID = 1, NDID = Directories.size();
3108                   DirectoryID <= NDID; ++DirectoryID) {
3109       Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
3110     }
3111     Asm->EmitInt8(0); Asm->EOL("End of directories");
3112
3113     // Emit files.
3114     for (unsigned SourceID = 1, NSID = SourceFiles.size();
3115                  SourceID <= NSID; ++SourceID) {
3116       const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3117       Asm->EmitString(SourceFile.getName());
3118       Asm->EOL("Source");
3119       Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
3120       Asm->EOL("Directory #");
3121       Asm->EmitULEB128Bytes(0);
3122       Asm->EOL("Mod date");
3123       Asm->EmitULEB128Bytes(0);
3124       Asm->EOL("File size");
3125     }
3126     Asm->EmitInt8(0); Asm->EOL("End of files");
3127
3128     EmitLabel("line_prolog_end", 0);
3129
3130     // A sequence for each text section.
3131     unsigned SecSrcLinesSize = SectionSourceLines.size();
3132
3133     for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3134       // Isolate current sections line info.
3135       const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
3136
3137       if (VerboseAsm) {
3138         const Section* S = SectionMap[j + 1];
3139         Asm->EOL(std::string("Section ") + S->getName());
3140       } else
3141         Asm->EOL();
3142
3143       // Dwarf assumes we start with first line of first source file.
3144       unsigned Source = 1;
3145       unsigned Line = 1;
3146
3147       // Construct rows of the address, source, line, column matrix.
3148       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3149         const SrcLineInfo &LineInfo = LineInfos[i];
3150         unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
3151         if (!LabelID) continue;
3152
3153         unsigned SourceID = LineInfo.getSourceID();
3154         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3155         unsigned DirectoryID = SourceFile.getDirectoryID();
3156         if (VerboseAsm)
3157           Asm->EOL(Directories[DirectoryID]
3158                    + SourceFile.getName()
3159                    + ":"
3160                    + utostr_32(LineInfo.getLine()));
3161         else
3162           Asm->EOL();
3163
3164         // Define the line address.
3165         Asm->EmitInt8(0); Asm->EOL("Extended Op");
3166         Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3167         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3168         EmitReference("label",  LabelID); Asm->EOL("Location label");
3169
3170         // If change of source, then switch to the new source.
3171         if (Source != LineInfo.getSourceID()) {
3172           Source = LineInfo.getSourceID();
3173           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
3174           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
3175         }
3176
3177         // If change of line.
3178         if (Line != LineInfo.getLine()) {
3179           // Determine offset.
3180           int Offset = LineInfo.getLine() - Line;
3181           int Delta = Offset - MinLineDelta;
3182
3183           // Update line.
3184           Line = LineInfo.getLine();
3185
3186           // If delta is small enough and in range...
3187           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3188             // ... then use fast opcode.
3189             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
3190           } else {
3191             // ... otherwise use long hand.
3192             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
3193             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
3194             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3195           }
3196         } else {
3197           // Copy the previous row (different address or source)
3198           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3199         }
3200       }
3201
3202       EmitEndOfLineMatrix(j + 1);
3203     }
3204
3205     if (SecSrcLinesSize == 0)
3206       // Because we're emitting a debug_line section, we still need a line
3207       // table. The linker and friends expect it to exist. If there's nothing to
3208       // put into it, emit an empty table.
3209       EmitEndOfLineMatrix(1);
3210
3211     EmitLabel("line_end", 0);
3212
3213     Asm->EOL();
3214   }
3215
3216   /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
3217   ///
3218   void EmitCommonDebugFrame() {
3219     if (!TAI->doesDwarfRequireFrameSection())
3220       return;
3221
3222     int stackGrowth =
3223         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3224           TargetFrameInfo::StackGrowsUp ?
3225         TD->getPointerSize() : -TD->getPointerSize();
3226
3227     // Start the dwarf frame section.
3228     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3229
3230     EmitLabel("debug_frame_common", 0);
3231     EmitDifference("debug_frame_common_end", 0,
3232                    "debug_frame_common_begin", 0, true);
3233     Asm->EOL("Length of Common Information Entry");
3234
3235     EmitLabel("debug_frame_common_begin", 0);
3236     Asm->EmitInt32((int)DW_CIE_ID);
3237     Asm->EOL("CIE Identifier Tag");
3238     Asm->EmitInt8(DW_CIE_VERSION);
3239     Asm->EOL("CIE Version");
3240     Asm->EmitString("");
3241     Asm->EOL("CIE Augmentation");
3242     Asm->EmitULEB128Bytes(1);
3243     Asm->EOL("CIE Code Alignment Factor");
3244     Asm->EmitSLEB128Bytes(stackGrowth);
3245     Asm->EOL("CIE Data Alignment Factor");
3246     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3247     Asm->EOL("CIE RA Column");
3248
3249     std::vector<MachineMove> Moves;
3250     RI->getInitialFrameState(Moves);
3251
3252     EmitFrameMoves(NULL, 0, Moves, false);
3253
3254     Asm->EmitAlignment(2, 0, 0, false);
3255     EmitLabel("debug_frame_common_end", 0);
3256
3257     Asm->EOL();
3258   }
3259
3260   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
3261   /// section.
3262   void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3263     if (!TAI->doesDwarfRequireFrameSection())
3264       return;
3265
3266     // Start the dwarf frame section.
3267     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3268
3269     EmitDifference("debug_frame_end", DebugFrameInfo.Number,
3270                    "debug_frame_begin", DebugFrameInfo.Number, true);
3271     Asm->EOL("Length of Frame Information Entry");
3272
3273     EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
3274
3275     EmitSectionOffset("debug_frame_common", "section_debug_frame",
3276                       0, 0, true, false);
3277     Asm->EOL("FDE CIE offset");
3278
3279     EmitReference("func_begin", DebugFrameInfo.Number);
3280     Asm->EOL("FDE initial location");
3281     EmitDifference("func_end", DebugFrameInfo.Number,
3282                    "func_begin", DebugFrameInfo.Number);
3283     Asm->EOL("FDE address range");
3284
3285     EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
3286
3287     Asm->EmitAlignment(2, 0, 0, false);
3288     EmitLabel("debug_frame_end", DebugFrameInfo.Number);
3289
3290     Asm->EOL();
3291   }
3292
3293   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
3294   ///
3295   void EmitDebugPubNames() {
3296     // Start the dwarf pubnames section.
3297     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
3298
3299     for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
3300            CE = DW_CUs.end(); CI != CE; ++CI) {
3301       CompileUnit *Unit = CI->second;
3302
3303       EmitDifference("pubnames_end", Unit->getID(),
3304                      "pubnames_begin", Unit->getID(), true);
3305       Asm->EOL("Length of Public Names Info");
3306       
3307       EmitLabel("pubnames_begin", Unit->getID());
3308       
3309       Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
3310       
3311       EmitSectionOffset("info_begin", "section_info",
3312                         Unit->getID(), 0, true, false);
3313       Asm->EOL("Offset of Compilation Unit Info");
3314       
3315       EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
3316       Asm->EOL("Compilation Unit Length");
3317       
3318       std::map<std::string, DIE *> &Globals = Unit->getGlobals();
3319       
3320       for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
3321              GE = Globals.end();
3322            GI != GE; ++GI) {
3323         const std::string &Name = GI->first;
3324         DIE * Entity = GI->second;
3325         
3326         Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
3327         Asm->EmitString(Name); Asm->EOL("External Name");
3328       }
3329       
3330       Asm->EmitInt32(0); Asm->EOL("End Mark");
3331       EmitLabel("pubnames_end", Unit->getID());
3332       
3333       Asm->EOL();
3334     }
3335   }
3336
3337   /// EmitDebugStr - Emit visible names into a debug str section.
3338   ///
3339   void EmitDebugStr() {
3340     // Check to see if it is worth the effort.
3341     if (!StringPool.empty()) {
3342       // Start the dwarf str section.
3343       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
3344
3345       // For each of strings in the string pool.
3346       for (unsigned StringID = 1, N = StringPool.size();
3347            StringID <= N; ++StringID) {
3348         // Emit a label for reference from debug information entries.
3349         EmitLabel("string", StringID);
3350         // Emit the string itself.
3351         const std::string &String = StringPool[StringID];
3352         Asm->EmitString(String); Asm->EOL();
3353       }
3354
3355       Asm->EOL();
3356     }
3357   }
3358
3359   /// EmitDebugLoc - Emit visible names into a debug loc section.
3360   ///
3361   void EmitDebugLoc() {
3362     // Start the dwarf loc section.
3363     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
3364
3365     Asm->EOL();
3366   }
3367
3368   /// EmitDebugARanges - Emit visible names into a debug aranges section.
3369   ///
3370   void EmitDebugARanges() {
3371     // Start the dwarf aranges section.
3372     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
3373
3374     // FIXME - Mock up
3375 #if 0
3376     CompileUnit *Unit = GetBaseCompileUnit();
3377
3378     // Don't include size of length
3379     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
3380
3381     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
3382
3383     EmitReference("info_begin", Unit->getID());
3384     Asm->EOL("Offset of Compilation Unit Info");
3385
3386     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
3387
3388     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
3389
3390     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
3391     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
3392
3393     // Range 1
3394     EmitReference("text_begin", 0); Asm->EOL("Address");
3395     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
3396
3397     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
3398     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
3399 #endif
3400
3401     Asm->EOL();
3402   }
3403
3404   /// EmitDebugRanges - Emit visible names into a debug ranges section.
3405   ///
3406   void EmitDebugRanges() {
3407     // Start the dwarf ranges section.
3408     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
3409
3410     Asm->EOL();
3411   }
3412
3413   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
3414   ///
3415   void EmitDebugMacInfo() {
3416     // Start the dwarf macinfo section.
3417     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
3418
3419     Asm->EOL();
3420   }
3421
3422   /// ConstructCompileUnits - Create a compile unit DIEs.
3423   void ConstructCompileUnits() {
3424     std::string CUName = "llvm.dbg.compile_units";
3425     std::vector<GlobalVariable*> Result;
3426     getGlobalVariablesUsing(*M, CUName, Result);
3427     for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3428            RE = Result.end(); RI != RE; ++RI) {
3429       DICompileUnit *DIUnit = new DICompileUnit(*RI);
3430       unsigned ID = RecordSource(DIUnit->getDirectory(),
3431                                  DIUnit->getFilename());
3432
3433       DIE *Die = new DIE(DW_TAG_compile_unit);
3434       AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
3435                        DWLabel("section_line", 0), DWLabel("section_line", 0),
3436                        false);
3437       AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit->getProducer());
3438       AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit->getLanguage());
3439       AddString(Die, DW_AT_name, DW_FORM_string, DIUnit->getFilename());
3440       if (!DIUnit->getDirectory().empty())
3441         AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit->getDirectory());
3442
3443       CompileUnit *Unit = new CompileUnit(ID, Die);
3444       DW_CUs[DIUnit->getGV()] = Unit;
3445     }
3446   }
3447
3448   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
3449   /// header file.
3450   void ConstructCompileUnitDIEs() {
3451     const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
3452
3453     for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
3454       unsigned ID = MMI->RecordSource(CUW[i]);
3455       CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
3456       CompileUnits.push_back(Unit);
3457     }
3458   }
3459
3460   /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally 
3461   /// visible global variables.
3462   void ConstructGlobalVariableDIEs() {
3463     std::string GVName = "llvm.dbg.global_variables";
3464     std::vector<GlobalVariable*> Result;
3465     getGlobalVariablesUsing(*M, GVName, Result);
3466     for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
3467            GVE = Result.end(); GVI != GVE; ++GVI) {
3468       DIGlobalVariable *DI_GV = new DIGlobalVariable(*GVI);
3469       CompileUnit *DW_Unit = FindCompileUnit(DI_GV->getCompileUnit());
3470
3471       // Check for pre-existence.
3472       DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV->getGV());
3473       if (Slot) continue;
3474
3475       DIE *VariableDie = new DIE(DW_TAG_variable);
3476       AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV->getName());
3477       const std::string &LinkageName  = DI_GV->getLinkageName();
3478       if (!LinkageName.empty())
3479         AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3480                   LinkageName);
3481       AddType(DW_Unit, VariableDie, DI_GV->getType());
3482
3483       if (!DI_GV->isLocalToUnit())
3484         AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);              
3485
3486       // Add source line info, if available.
3487       AddSourceLine(VariableDie, DI_GV);
3488
3489       // Add address.
3490       DIEBlock *Block = new DIEBlock();
3491       AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
3492       AddObjectLabel(Block, 0, DW_FORM_udata,
3493                      Asm->getGlobalLinkName(DI_GV->getGV()));
3494       AddBlock(VariableDie, DW_AT_location, 0, Block);
3495
3496       //Add to map.
3497       Slot = VariableDie;
3498
3499       //Add to context owner.
3500       DW_Unit->getDie()->AddChild(VariableDie);
3501
3502       //Expose as global. FIXME - need to check external flag.
3503       DW_Unit->AddGlobal(DI_GV->getName(), VariableDie);
3504     }
3505   }
3506
3507   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
3508   /// global variables.
3509   void ConstructGlobalDIEs() {
3510     std::vector<GlobalVariableDesc *> GlobalVariables;
3511     MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
3512
3513     for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
3514       GlobalVariableDesc *GVD = GlobalVariables[i];
3515       NewGlobalVariable(GVD);
3516     }
3517   }
3518
3519   /// ConstructSubprograms - Create DIEs for each of the externally visible
3520   /// subprograms.
3521   void ConstructSubprograms() {
3522
3523     std::string SPName = "llvm.dbg.subprograms";
3524     std::vector<GlobalVariable*> Result;
3525     getGlobalVariablesUsing(*M, SPName, Result);
3526     for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3527            RE = Result.end(); RI != RE; ++RI) {
3528
3529       DISubprogram *SP = new DISubprogram(*RI);
3530       CompileUnit *Unit = FindCompileUnit(SP->getCompileUnit());
3531
3532       // Check for pre-existence.                                                         
3533       DIE *&Slot = Unit->getDieMapSlotFor(SP->getGV());
3534       if (Slot) continue;
3535
3536       DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
3537       AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP->getName());
3538       const std::string &LinkageName = SP->getLinkageName();
3539       if (!LinkageName.empty())
3540         AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3541                   LinkageName);
3542       DIType SPTy = SP->getType();
3543       AddType(Unit, SubprogramDie, SPTy);
3544       if (!SP->isLocalToUnit())
3545         AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
3546       AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
3547
3548       AddSourceLine(SubprogramDie, SP);
3549       //Add to map.
3550       Slot = SubprogramDie;
3551       //Add to context owner.
3552       Unit->getDie()->AddChild(SubprogramDie);
3553       //Expose as global.
3554       Unit->AddGlobal(SP->getName(), SubprogramDie);
3555     }
3556   }
3557
3558   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
3559   /// subprograms.
3560   void ConstructSubprogramDIEs() {
3561     std::vector<SubprogramDesc *> Subprograms;
3562     MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
3563
3564     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
3565       SubprogramDesc *SPD = Subprograms[i];
3566       NewSubprogram(SPD);
3567     }
3568   }
3569
3570 public:
3571   //===--------------------------------------------------------------------===//
3572   // Main entry points.
3573   //
3574   DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3575   : Dwarf(OS, A, T, "dbg")
3576   , CompileUnits()
3577   , AbbreviationsSet(InitAbbreviationsSetSize)
3578   , Abbreviations()
3579   , ValuesSet(InitValuesSetSize)
3580   , Values()
3581   , StringPool()
3582   , DescToUnitMap()
3583   , SectionMap()
3584   , SectionSourceLines()
3585   , didInitial(false)
3586   , shouldEmit(false)
3587   , RootDbgScope(NULL)
3588   {
3589   }
3590   virtual ~DwarfDebug() {
3591     for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
3592       delete CompileUnits[i];
3593     for (unsigned j = 0, M = Values.size(); j < M; ++j)
3594       delete Values[j];
3595   }
3596
3597   /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3598   /// This is inovked by the target AsmPrinter.
3599   void SetDebugInfo(MachineModuleInfo *mmi) {
3600
3601       // Create all the compile unit DIEs.
3602       ConstructCompileUnits();
3603       
3604       if (DW_CUs.empty())
3605         return;
3606
3607       MMI = mmi;
3608       shouldEmit = true;
3609
3610       // Create DIEs for each of the externally visible global variables.
3611       ConstructGlobalVariableDIEs();
3612
3613       // Create DIEs for each of the externally visible subprograms.
3614       ConstructSubprograms();
3615
3616       // Prime section data.
3617       SectionMap.insert(TAI->getTextSection());
3618
3619       // Print out .file directives to specify files for .loc directives. These
3620       // are printed out early so that they precede any .loc directives.
3621       if (TAI->hasDotLocAndDotFile()) {
3622         for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
3623           sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
3624           bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
3625           assert(AppendOk && "Could not append filename to directory!");
3626           AppendOk = false;
3627           Asm->EmitFile(i, FullPath.toString());
3628           Asm->EOL();
3629         }
3630       }
3631
3632       // Emit initial sections
3633       EmitInitial();
3634   }
3635
3636   /// SetModuleInfo - Set machine module information when it's known that pass
3637   /// manager has created it.  Set by the target AsmPrinter.
3638   void SetModuleInfo(MachineModuleInfo *mmi) {
3639     // Make sure initial declarations are made.
3640     if (!MMI && mmi->hasDebugInfo()) {
3641       MMI = mmi;
3642       shouldEmit = true;
3643
3644       // Create all the compile unit DIEs.
3645       ConstructCompileUnitDIEs();
3646
3647       // Create DIEs for each of the externally visible global variables.
3648       ConstructGlobalDIEs();
3649
3650       // Create DIEs for each of the externally visible subprograms.
3651       ConstructSubprogramDIEs();
3652
3653       // Prime section data.
3654       SectionMap.insert(TAI->getTextSection());
3655
3656       // Print out .file directives to specify files for .loc directives. These
3657       // are printed out early so that they precede any .loc directives.
3658       if (TAI->hasDotLocAndDotFile()) {
3659         const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3660         const UniqueVector<std::string> &Directories = MMI->getDirectories();
3661         for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
3662           sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
3663           bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
3664           assert(AppendOk && "Could not append filename to directory!");
3665           AppendOk = false;
3666           Asm->EmitFile(i, FullPath.toString());
3667           Asm->EOL();
3668         }
3669       }
3670
3671       // Emit initial sections
3672       EmitInitial();
3673     }
3674   }
3675
3676   /// BeginModule - Emit all Dwarf sections that should come prior to the
3677   /// content.
3678   void BeginModule(Module *M) {
3679     this->M = M;
3680   }
3681
3682   /// EndModule - Emit all Dwarf sections that should come after the content.
3683   ///
3684   void EndModule() {
3685     if (!ShouldEmitDwarf()) return;
3686
3687     // Standard sections final addresses.
3688     Asm->SwitchToSection(TAI->getTextSection());
3689     EmitLabel("text_end", 0);
3690     Asm->SwitchToSection(TAI->getDataSection());
3691     EmitLabel("data_end", 0);
3692
3693     // End text sections.
3694     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3695       Asm->SwitchToSection(SectionMap[i]);
3696       EmitLabel("section_end", i);
3697     }
3698
3699     // Emit common frame information.
3700     EmitCommonDebugFrame();
3701
3702     // Emit function debug frame information
3703     for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3704            E = DebugFrames.end(); I != E; ++I)
3705       EmitFunctionDebugFrame(*I);
3706
3707     // Compute DIE offsets and sizes.
3708     SizeAndOffsets();
3709
3710     // Emit all the DIEs into a debug info section
3711     EmitDebugInfo();
3712
3713     // Corresponding abbreviations into a abbrev section.
3714     EmitAbbreviations();
3715
3716     // Emit source line correspondence into a debug line section.
3717     EmitDebugLines();
3718
3719     // Emit info into a debug pubnames section.
3720     EmitDebugPubNames();
3721
3722     // Emit info into a debug str section.
3723     EmitDebugStr();
3724
3725     // Emit info into a debug loc section.
3726     EmitDebugLoc();
3727
3728     // Emit info into a debug aranges section.
3729     EmitDebugARanges();
3730
3731     // Emit info into a debug ranges section.
3732     EmitDebugRanges();
3733
3734     // Emit info into a debug macinfo section.
3735     EmitDebugMacInfo();
3736   }
3737
3738   /// BeginFunction - Gather pre-function debug information.  Assumes being
3739   /// emitted immediately after the function entry point.
3740   void BeginFunction(MachineFunction *MF) {
3741     this->MF = MF;
3742
3743     if (!ShouldEmitDwarf()) return;
3744
3745     // Begin accumulating function debug information.
3746     MMI->BeginFunction(MF);
3747
3748     // Assumes in correct section after the entry point.
3749     EmitLabel("func_begin", ++SubprogramCount);
3750
3751     // Emit label for the implicitly defined dbg.stoppoint at the start of
3752     // the function.
3753     if (!Lines.empty()) {
3754       const SrcLineInfo &LineInfo = Lines[0];
3755       Asm->printLabel(LineInfo.getLabelID());
3756     }
3757   }
3758
3759   /// EndFunction - Gather and emit post-function debug information.
3760   ///
3761   void EndFunction(MachineFunction *MF) {
3762     if (!ShouldEmitDwarf()) return;
3763
3764     // Define end label for subprogram.
3765     EmitLabel("func_end", SubprogramCount);
3766
3767     // Get function line info.
3768     if (!Lines.empty()) {
3769       // Get section line info.
3770       unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3771       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3772       std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3773       // Append the function info to section info.
3774       SectionLineInfos.insert(SectionLineInfos.end(),
3775                               Lines.begin(), Lines.end());
3776     }
3777
3778     // Construct scopes for subprogram.
3779     if (MMI->getRootScope())
3780       ConstructRootScope(MMI->getRootScope());
3781     else
3782       // FIXME: This is wrong. We are essentially getting past a problem with
3783       // debug information not being able to handle unreachable blocks that have
3784       // debug information in them. In particular, those unreachable blocks that
3785       // have "region end" info in them. That situation results in the "root
3786       // scope" not being created. If that's the case, then emit a "default"
3787       // scope, i.e., one that encompasses the whole function. This isn't
3788       // desirable. And a better way of handling this (and all of the debugging
3789       // information) needs to be explored.
3790       ConstructDefaultScope(MF);
3791
3792     DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3793                                                  MMI->getFrameMoves()));
3794
3795     // Clear debug info
3796     if (RootDbgScope) {
3797       delete RootDbgScope;
3798       DbgScopeMap.clear();
3799       RootDbgScope = NULL;
3800     }
3801     Lines.clear();
3802   }
3803
3804 public:
3805
3806   /// RecordSourceLine - Records location information and associates it with a 
3807   /// label. Returns a unique label ID used to generate a label and provide
3808   /// correspondence to the source line list.
3809   unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3810     CompileUnit *Unit = DW_CUs[V];
3811     assert (Unit && "Unable to find CompileUnit");
3812     unsigned ID = MMI->NextLabelID();
3813     Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3814     return ID;
3815   }
3816   
3817   /// RecordSourceLine - Records location information and associates it with a 
3818   /// label. Returns a unique label ID used to generate a label and provide
3819   /// correspondence to the source line list.
3820   unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3821     unsigned ID = MMI->NextLabelID();
3822     Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3823     return ID;
3824   }
3825
3826   unsigned getRecordSourceLineCount() {
3827     return Lines.size();
3828   }
3829                             
3830   /// RecordSource - Register a source file with debug info. Returns an source
3831   /// ID.
3832   unsigned RecordSource(const std::string &Directory,
3833                         const std::string &File) {
3834     unsigned DID = Directories.insert(Directory);
3835     return SrcFiles.insert(SrcFileInfo(DID,File));
3836   }
3837
3838   /// RecordRegionStart - Indicate the start of a region.
3839   ///
3840   unsigned RecordRegionStart(GlobalVariable *V) {
3841     DbgScope *Scope = getOrCreateScope(V);
3842     unsigned ID = MMI->NextLabelID();
3843     if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3844     return ID;
3845   }
3846
3847   /// RecordRegionEnd - Indicate the end of a region.
3848   ///
3849   unsigned RecordRegionEnd(GlobalVariable *V) {
3850     DbgScope *Scope = getOrCreateScope(V);
3851     unsigned ID = MMI->NextLabelID();
3852     Scope->setEndLabelID(ID);
3853     return ID;
3854   }
3855
3856   /// RecordVariable - Indicate the declaration of  a local variable.
3857   ///
3858   void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3859     DbgScope *Scope = getOrCreateScope(GV);
3860     DIVariable *VD = new DIVariable(GV);
3861     DbgVariable *DV = new DbgVariable(VD, FrameIndex);
3862     Scope->AddVariable(DV);
3863   }
3864 };
3865
3866 //===----------------------------------------------------------------------===//
3867 /// DwarfException - Emits Dwarf exception handling directives.
3868 ///
3869 class DwarfException : public Dwarf  {
3870
3871 private:
3872   struct FunctionEHFrameInfo {
3873     std::string FnName;
3874     unsigned Number;
3875     unsigned PersonalityIndex;
3876     bool hasCalls;
3877     bool hasLandingPads;
3878     std::vector<MachineMove> Moves;
3879     const Function * function;
3880
3881     FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3882                         bool hC, bool hL,
3883                         const std::vector<MachineMove> &M,
3884                         const Function *f):
3885       FnName(FN), Number(Num), PersonalityIndex(P),
3886       hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3887   };
3888
3889   std::vector<FunctionEHFrameInfo> EHFrames;
3890
3891   /// shouldEmitTable - Per-function flag to indicate if EH tables should
3892   /// be emitted.
3893   bool shouldEmitTable;
3894
3895   /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3896   /// should be emitted.
3897   bool shouldEmitMoves;
3898
3899   /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3900   /// should be emitted.
3901   bool shouldEmitTableModule;
3902
3903   /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3904   /// should be emitted.
3905   bool shouldEmitMovesModule;
3906
3907   /// EmitCommonEHFrame - Emit the common eh unwind frame.
3908   ///
3909   void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3910     // Size and sign of stack growth.
3911     int stackGrowth =
3912         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3913           TargetFrameInfo::StackGrowsUp ?
3914         TD->getPointerSize() : -TD->getPointerSize();
3915
3916     // Begin eh frame section.
3917     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3918
3919     if (!TAI->doesRequireNonLocalEHFrameLabel())
3920       O << TAI->getEHGlobalPrefix();
3921     O << "EH_frame" << Index << ":\n";
3922     EmitLabel("section_eh_frame", Index);
3923
3924     // Define base labels.
3925     EmitLabel("eh_frame_common", Index);
3926
3927     // Define the eh frame length.
3928     EmitDifference("eh_frame_common_end", Index,
3929                    "eh_frame_common_begin", Index, true);
3930     Asm->EOL("Length of Common Information Entry");
3931
3932     // EH frame header.
3933     EmitLabel("eh_frame_common_begin", Index);
3934     Asm->EmitInt32((int)0);
3935     Asm->EOL("CIE Identifier Tag");
3936     Asm->EmitInt8(DW_CIE_VERSION);
3937     Asm->EOL("CIE Version");
3938
3939     // The personality presence indicates that language specific information
3940     // will show up in the eh frame.
3941     Asm->EmitString(Personality ? "zPLR" : "zR");
3942     Asm->EOL("CIE Augmentation");
3943
3944     // Round out reader.
3945     Asm->EmitULEB128Bytes(1);
3946     Asm->EOL("CIE Code Alignment Factor");
3947     Asm->EmitSLEB128Bytes(stackGrowth);
3948     Asm->EOL("CIE Data Alignment Factor");
3949     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3950     Asm->EOL("CIE Return Address Column");
3951
3952     // If there is a personality, we need to indicate the functions location.
3953     if (Personality) {
3954       Asm->EmitULEB128Bytes(7);
3955       Asm->EOL("Augmentation Size");
3956
3957       if (TAI->getNeedsIndirectEncoding()) {
3958         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3959         Asm->EOL("Personality (pcrel sdata4 indirect)");
3960       } else {
3961         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3962         Asm->EOL("Personality (pcrel sdata4)");
3963       }
3964
3965       PrintRelDirective(true);
3966       O << TAI->getPersonalityPrefix();
3967       Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3968       O << TAI->getPersonalitySuffix();
3969       if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3970         O << "-" << TAI->getPCSymbol();
3971       Asm->EOL("Personality");
3972
3973       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3974       Asm->EOL("LSDA Encoding (pcrel sdata4)");
3975
3976       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3977       Asm->EOL("FDE Encoding (pcrel sdata4)");
3978    } else {
3979       Asm->EmitULEB128Bytes(1);
3980       Asm->EOL("Augmentation Size");
3981
3982       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3983       Asm->EOL("FDE Encoding (pcrel sdata4)");
3984     }
3985
3986     // Indicate locations of general callee saved registers in frame.
3987     std::vector<MachineMove> Moves;
3988     RI->getInitialFrameState(Moves);
3989     EmitFrameMoves(NULL, 0, Moves, true);
3990
3991     // On Darwin the linker honors the alignment of eh_frame, which means it
3992     // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise
3993     // you get holes which confuse readers of eh_frame.
3994     Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3995                        0, 0, false);
3996     EmitLabel("eh_frame_common_end", Index);
3997
3998     Asm->EOL();
3999   }
4000
4001   /// EmitEHFrame - Emit function exception frame information.
4002   ///
4003   void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
4004     Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
4005
4006     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
4007
4008     // Externally visible entry into the functions eh frame info.
4009     // If the corresponding function is static, this should not be
4010     // externally visible.
4011     if (linkage != Function::InternalLinkage) {
4012       if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
4013         O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
4014     }
4015
4016     // If corresponding function is weak definition, this should be too.
4017     if ((linkage == Function::WeakLinkage ||
4018          linkage == Function::LinkOnceLinkage) &&
4019         TAI->getWeakDefDirective())
4020       O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
4021
4022     // If there are no calls then you can't unwind.  This may mean we can
4023     // omit the EH Frame, but some environments do not handle weak absolute
4024     // symbols.
4025     // If UnwindTablesMandatory is set we cannot do this optimization; the
4026     // unwind info is to be available for non-EH uses.
4027     if (!EHFrameInfo.hasCalls &&
4028         !UnwindTablesMandatory &&
4029         ((linkage != Function::WeakLinkage &&
4030           linkage != Function::LinkOnceLinkage) ||
4031          !TAI->getWeakDefDirective() ||
4032          TAI->getSupportsWeakOmittedEHFrame()))
4033     {
4034       O << EHFrameInfo.FnName << " = 0\n";
4035       // This name has no connection to the function, so it might get
4036       // dead-stripped when the function is not, erroneously.  Prohibit
4037       // dead-stripping unconditionally.
4038       if (const char *UsedDirective = TAI->getUsedDirective())
4039         O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4040     } else {
4041       O << EHFrameInfo.FnName << ":\n";
4042
4043       // EH frame header.
4044       EmitDifference("eh_frame_end", EHFrameInfo.Number,
4045                      "eh_frame_begin", EHFrameInfo.Number, true);
4046       Asm->EOL("Length of Frame Information Entry");
4047
4048       EmitLabel("eh_frame_begin", EHFrameInfo.Number);
4049
4050       if (TAI->doesRequireNonLocalEHFrameLabel()) {
4051         PrintRelDirective(true, true);
4052         PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
4053
4054         if (!TAI->isAbsoluteEHSectionOffsets())
4055           O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
4056       } else {
4057         EmitSectionOffset("eh_frame_begin", "eh_frame_common",
4058                           EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
4059                           true, true, false);
4060       }
4061
4062       Asm->EOL("FDE CIE offset");
4063
4064       EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
4065       Asm->EOL("FDE initial location");
4066       EmitDifference("eh_func_end", EHFrameInfo.Number,
4067                      "eh_func_begin", EHFrameInfo.Number, true);
4068       Asm->EOL("FDE address range");
4069
4070       // If there is a personality and landing pads then point to the language
4071       // specific data area in the exception table.
4072       if (EHFrameInfo.PersonalityIndex) {
4073         Asm->EmitULEB128Bytes(4);
4074         Asm->EOL("Augmentation size");
4075
4076         if (EHFrameInfo.hasLandingPads)
4077           EmitReference("exception", EHFrameInfo.Number, true, true);
4078         else
4079           Asm->EmitInt32((int)0);
4080         Asm->EOL("Language Specific Data Area");
4081       } else {
4082         Asm->EmitULEB128Bytes(0);
4083         Asm->EOL("Augmentation size");
4084       }
4085
4086       // Indicate locations of function specific  callee saved registers in
4087       // frame.
4088       EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
4089
4090       // On Darwin the linker honors the alignment of eh_frame, which means it
4091       // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise
4092       // you get holes which confuse readers of eh_frame.
4093       Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
4094                          0, 0, false);
4095       EmitLabel("eh_frame_end", EHFrameInfo.Number);
4096
4097       // If the function is marked used, this table should be also.  We cannot
4098       // make the mark unconditional in this case, since retaining the table
4099       // also retains the function in this case, and there is code around
4100       // that depends on unused functions (calling undefined externals) being
4101       // dead-stripped to link correctly.  Yes, there really is.
4102       if (MMI->getUsedFunctions().count(EHFrameInfo.function))
4103         if (const char *UsedDirective = TAI->getUsedDirective())
4104           O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4105     }
4106   }
4107
4108   /// EmitExceptionTable - Emit landing pads and actions.
4109   ///
4110   /// The general organization of the table is complex, but the basic concepts
4111   /// are easy.  First there is a header which describes the location and
4112   /// organization of the three components that follow.
4113   ///  1. The landing pad site information describes the range of code covered
4114   ///     by the try.  In our case it's an accumulation of the ranges covered
4115   ///     by the invokes in the try.  There is also a reference to the landing
4116   ///     pad that handles the exception once processed.  Finally an index into
4117   ///     the actions table.
4118   ///  2. The action table, in our case, is composed of pairs of type ids
4119   ///     and next action offset.  Starting with the action index from the
4120   ///     landing pad site, each type Id is checked for a match to the current
4121   ///     exception.  If it matches then the exception and type id are passed
4122   ///     on to the landing pad.  Otherwise the next action is looked up.  This
4123   ///     chain is terminated with a next action of zero.  If no type id is
4124   ///     found the the frame is unwound and handling continues.
4125   ///  3. Type id table contains references to all the C++ typeinfo for all
4126   ///     catches in the function.  This tables is reversed indexed base 1.
4127
4128   /// SharedTypeIds - How many leading type ids two landing pads have in common.
4129   static unsigned SharedTypeIds(const LandingPadInfo *L,
4130                                 const LandingPadInfo *R) {
4131     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4132     unsigned LSize = LIds.size(), RSize = RIds.size();
4133     unsigned MinSize = LSize < RSize ? LSize : RSize;
4134     unsigned Count = 0;
4135
4136     for (; Count != MinSize; ++Count)
4137       if (LIds[Count] != RIds[Count])
4138         return Count;
4139
4140     return Count;
4141   }
4142
4143   /// PadLT - Order landing pads lexicographically by type id.
4144   static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
4145     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4146     unsigned LSize = LIds.size(), RSize = RIds.size();
4147     unsigned MinSize = LSize < RSize ? LSize : RSize;
4148
4149     for (unsigned i = 0; i != MinSize; ++i)
4150       if (LIds[i] != RIds[i])
4151         return LIds[i] < RIds[i];
4152
4153     return LSize < RSize;
4154   }
4155
4156   struct KeyInfo {
4157     static inline unsigned getEmptyKey() { return -1U; }
4158     static inline unsigned getTombstoneKey() { return -2U; }
4159     static unsigned getHashValue(const unsigned &Key) { return Key; }
4160     static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
4161     static bool isPod() { return true; }
4162   };
4163
4164   /// ActionEntry - Structure describing an entry in the actions table.
4165   struct ActionEntry {
4166     int ValueForTypeID; // The value to write - may not be equal to the type id.
4167     int NextAction;
4168     struct ActionEntry *Previous;
4169   };
4170
4171   /// PadRange - Structure holding a try-range and the associated landing pad.
4172   struct PadRange {
4173     // The index of the landing pad.
4174     unsigned PadIndex;
4175     // The index of the begin and end labels in the landing pad's label lists.
4176     unsigned RangeIndex;
4177   };
4178
4179   typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
4180
4181   /// CallSiteEntry - Structure describing an entry in the call-site table.
4182   struct CallSiteEntry {
4183     // The 'try-range' is BeginLabel .. EndLabel.
4184     unsigned BeginLabel; // zero indicates the start of the function.
4185     unsigned EndLabel;   // zero indicates the end of the function.
4186     // The landing pad starts at PadLabel.
4187     unsigned PadLabel;   // zero indicates that there is no landing pad.
4188     unsigned Action;
4189   };
4190
4191   void EmitExceptionTable() {
4192     const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
4193     const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
4194     const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
4195     if (PadInfos.empty()) return;
4196
4197     // Sort the landing pads in order of their type ids.  This is used to fold
4198     // duplicate actions.
4199     SmallVector<const LandingPadInfo *, 64> LandingPads;
4200     LandingPads.reserve(PadInfos.size());
4201     for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
4202       LandingPads.push_back(&PadInfos[i]);
4203     std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
4204
4205     // Negative type ids index into FilterIds, positive type ids index into
4206     // TypeInfos.  The value written for a positive type id is just the type
4207     // id itself.  For a negative type id, however, the value written is the
4208     // (negative) byte offset of the corresponding FilterIds entry.  The byte
4209     // offset is usually equal to the type id, because the FilterIds entries
4210     // are written using a variable width encoding which outputs one byte per
4211     // entry as long as the value written is not too large, but can differ.
4212     // This kind of complication does not occur for positive type ids because
4213     // type infos are output using a fixed width encoding.
4214     // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
4215     SmallVector<int, 16> FilterOffsets;
4216     FilterOffsets.reserve(FilterIds.size());
4217     int Offset = -1;
4218     for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
4219         E = FilterIds.end(); I != E; ++I) {
4220       FilterOffsets.push_back(Offset);
4221       Offset -= TargetAsmInfo::getULEB128Size(*I);
4222     }
4223
4224     // Compute the actions table and gather the first action index for each
4225     // landing pad site.
4226     SmallVector<ActionEntry, 32> Actions;
4227     SmallVector<unsigned, 64> FirstActions;
4228     FirstActions.reserve(LandingPads.size());
4229
4230     int FirstAction = 0;
4231     unsigned SizeActions = 0;
4232     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4233       const LandingPadInfo *LP = LandingPads[i];
4234       const std::vector<int> &TypeIds = LP->TypeIds;
4235       const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
4236       unsigned SizeSiteActions = 0;
4237
4238       if (NumShared < TypeIds.size()) {
4239         unsigned SizeAction = 0;
4240         ActionEntry *PrevAction = 0;
4241
4242         if (NumShared) {
4243           const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
4244           assert(Actions.size());
4245           PrevAction = &Actions.back();
4246           SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
4247             TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4248           for (unsigned j = NumShared; j != SizePrevIds; ++j) {
4249             SizeAction -=
4250               TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4251             SizeAction += -PrevAction->NextAction;
4252             PrevAction = PrevAction->Previous;
4253           }
4254         }
4255
4256         // Compute the actions.
4257         for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
4258           int TypeID = TypeIds[I];
4259           assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
4260           int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
4261           unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
4262
4263           int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
4264           SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
4265           SizeSiteActions += SizeAction;
4266
4267           ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
4268           Actions.push_back(Action);
4269
4270           PrevAction = &Actions.back();
4271         }
4272
4273         // Record the first action of the landing pad site.
4274         FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
4275       } // else identical - re-use previous FirstAction
4276
4277       FirstActions.push_back(FirstAction);
4278
4279       // Compute this sites contribution to size.
4280       SizeActions += SizeSiteActions;
4281     }
4282
4283     // Compute the call-site table.  The entry for an invoke has a try-range
4284     // containing the call, a non-zero landing pad and an appropriate action.
4285     // The entry for an ordinary call has a try-range containing the call and
4286     // zero for the landing pad and the action.  Calls marked 'nounwind' have
4287     // no entry and must not be contained in the try-range of any entry - they
4288     // form gaps in the table.  Entries must be ordered by try-range address.
4289     SmallVector<CallSiteEntry, 64> CallSites;
4290
4291     RangeMapType PadMap;
4292     // Invokes and nounwind calls have entries in PadMap (due to being bracketed
4293     // by try-range labels when lowered).  Ordinary calls do not, so appropriate
4294     // try-ranges for them need be deduced.
4295     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4296       const LandingPadInfo *LandingPad = LandingPads[i];
4297       for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
4298         unsigned BeginLabel = LandingPad->BeginLabels[j];
4299         assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
4300         PadRange P = { i, j };
4301         PadMap[BeginLabel] = P;
4302       }
4303     }
4304
4305     // The end label of the previous invoke or nounwind try-range.
4306     unsigned LastLabel = 0;
4307
4308     // Whether there is a potentially throwing instruction (currently this means
4309     // an ordinary call) between the end of the previous try-range and now.
4310     bool SawPotentiallyThrowing = false;
4311
4312     // Whether the last callsite entry was for an invoke.
4313     bool PreviousIsInvoke = false;
4314
4315     // Visit all instructions in order of address.
4316     for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
4317          I != E; ++I) {
4318       for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
4319            MI != E; ++MI) {
4320         if (!MI->isLabel()) {
4321           SawPotentiallyThrowing |= MI->getDesc().isCall();
4322           continue;
4323         }
4324
4325         unsigned BeginLabel = MI->getOperand(0).getImm();
4326         assert(BeginLabel && "Invalid label!");
4327
4328         // End of the previous try-range?
4329         if (BeginLabel == LastLabel)
4330           SawPotentiallyThrowing = false;
4331
4332         // Beginning of a new try-range?
4333         RangeMapType::iterator L = PadMap.find(BeginLabel);
4334         if (L == PadMap.end())
4335           // Nope, it was just some random label.
4336           continue;
4337
4338         PadRange P = L->second;
4339         const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
4340
4341         assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
4342                "Inconsistent landing pad map!");
4343
4344         // If some instruction between the previous try-range and this one may
4345         // throw, create a call-site entry with no landing pad for the region
4346         // between the try-ranges.
4347         if (SawPotentiallyThrowing) {
4348           CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
4349           CallSites.push_back(Site);
4350           PreviousIsInvoke = false;
4351         }
4352
4353         LastLabel = LandingPad->EndLabels[P.RangeIndex];
4354         assert(BeginLabel && LastLabel && "Invalid landing pad!");
4355
4356         if (LandingPad->LandingPadLabel) {
4357           // This try-range is for an invoke.
4358           CallSiteEntry Site = {BeginLabel, LastLabel,
4359             LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
4360
4361           // Try to merge with the previous call-site.
4362           if (PreviousIsInvoke) {
4363             CallSiteEntry &Prev = CallSites.back();
4364             if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
4365               // Extend the range of the previous entry.
4366               Prev.EndLabel = Site.EndLabel;
4367               continue;
4368             }
4369           }
4370
4371           // Otherwise, create a new call-site.
4372           CallSites.push_back(Site);
4373           PreviousIsInvoke = true;
4374         } else {
4375           // Create a gap.
4376           PreviousIsInvoke = false;
4377         }
4378       }
4379     }
4380     // If some instruction between the previous try-range and the end of the
4381     // function may throw, create a call-site entry with no landing pad for the
4382     // region following the try-range.
4383     if (SawPotentiallyThrowing) {
4384       CallSiteEntry Site = {LastLabel, 0, 0, 0};
4385       CallSites.push_back(Site);
4386     }
4387
4388     // Final tallies.
4389
4390     // Call sites.
4391     const unsigned SiteStartSize  = sizeof(int32_t); // DW_EH_PE_udata4
4392     const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
4393     const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
4394     unsigned SizeSites = CallSites.size() * (SiteStartSize +
4395                                              SiteLengthSize +
4396                                              LandingPadSize);
4397     for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
4398       SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
4399
4400     // Type infos.
4401     const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
4402     unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
4403
4404     unsigned TypeOffset = sizeof(int8_t) + // Call site format
4405            TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
4406                           SizeSites + SizeActions + SizeTypes;
4407
4408     unsigned TotalSize = sizeof(int8_t) + // LPStart format
4409                          sizeof(int8_t) + // TType format
4410            TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
4411                          TypeOffset;
4412
4413     unsigned SizeAlign = (4 - TotalSize) & 3;
4414
4415     // Begin the exception table.
4416     Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
4417     Asm->EmitAlignment(2, 0, 0, false);
4418     O << "GCC_except_table" << SubprogramCount << ":\n";
4419     for (unsigned i = 0; i != SizeAlign; ++i) {
4420       Asm->EmitInt8(0);
4421       Asm->EOL("Padding");
4422     }
4423     EmitLabel("exception", SubprogramCount);
4424
4425     // Emit the header.
4426     Asm->EmitInt8(DW_EH_PE_omit);
4427     Asm->EOL("LPStart format (DW_EH_PE_omit)");
4428     Asm->EmitInt8(DW_EH_PE_absptr);
4429     Asm->EOL("TType format (DW_EH_PE_absptr)");
4430     Asm->EmitULEB128Bytes(TypeOffset);
4431     Asm->EOL("TType base offset");
4432     Asm->EmitInt8(DW_EH_PE_udata4);
4433     Asm->EOL("Call site format (DW_EH_PE_udata4)");
4434     Asm->EmitULEB128Bytes(SizeSites);
4435     Asm->EOL("Call-site table length");
4436
4437     // Emit the landing pad site information.
4438     for (unsigned i = 0; i < CallSites.size(); ++i) {
4439       CallSiteEntry &S = CallSites[i];
4440       const char *BeginTag;
4441       unsigned BeginNumber;
4442
4443       if (!S.BeginLabel) {
4444         BeginTag = "eh_func_begin";
4445         BeginNumber = SubprogramCount;
4446       } else {
4447         BeginTag = "label";
4448         BeginNumber = S.BeginLabel;
4449       }
4450
4451       EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4452                         true, true);
4453       Asm->EOL("Region start");
4454
4455       if (!S.EndLabel) {
4456         EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4457                        true);
4458       } else {
4459         EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4460       }
4461       Asm->EOL("Region length");
4462
4463       if (!S.PadLabel)
4464         Asm->EmitInt32(0);
4465       else
4466         EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4467                           true, true);
4468       Asm->EOL("Landing pad");
4469
4470       Asm->EmitULEB128Bytes(S.Action);
4471       Asm->EOL("Action");
4472     }
4473
4474     // Emit the actions.
4475     for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4476       ActionEntry &Action = Actions[I];
4477
4478       Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4479       Asm->EOL("TypeInfo index");
4480       Asm->EmitSLEB128Bytes(Action.NextAction);
4481       Asm->EOL("Next action");
4482     }
4483
4484     // Emit the type ids.
4485     for (unsigned M = TypeInfos.size(); M; --M) {
4486       GlobalVariable *GV = TypeInfos[M - 1];
4487
4488       PrintRelDirective();
4489
4490       if (GV)
4491         O << Asm->getGlobalLinkName(GV);
4492       else
4493         O << "0";
4494
4495       Asm->EOL("TypeInfo");
4496     }
4497
4498     // Emit the filter typeids.
4499     for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4500       unsigned TypeID = FilterIds[j];
4501       Asm->EmitULEB128Bytes(TypeID);
4502       Asm->EOL("Filter TypeInfo index");
4503     }
4504
4505     Asm->EmitAlignment(2, 0, 0, false);
4506   }
4507
4508 public:
4509   //===--------------------------------------------------------------------===//
4510   // Main entry points.
4511   //
4512   DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4513   : Dwarf(OS, A, T, "eh")
4514   , shouldEmitTable(false)
4515   , shouldEmitMoves(false)
4516   , shouldEmitTableModule(false)
4517   , shouldEmitMovesModule(false)
4518   {}
4519
4520   virtual ~DwarfException() {}
4521
4522   /// SetModuleInfo - Set machine module information when it's known that pass
4523   /// manager has created it.  Set by the target AsmPrinter.
4524   void SetModuleInfo(MachineModuleInfo *mmi) {
4525     MMI = mmi;
4526   }
4527
4528   /// BeginModule - Emit all exception information that should come prior to the
4529   /// content.
4530   void BeginModule(Module *M) {
4531     this->M = M;
4532   }
4533
4534   /// EndModule - Emit all exception information that should come after the
4535   /// content.
4536   void EndModule() {
4537     if (shouldEmitMovesModule || shouldEmitTableModule) {
4538       const std::vector<Function *> Personalities = MMI->getPersonalities();
4539       for (unsigned i =0; i < Personalities.size(); ++i)
4540         EmitCommonEHFrame(Personalities[i], i);
4541
4542       for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4543              E = EHFrames.end(); I != E; ++I)
4544         EmitEHFrame(*I);
4545     }
4546   }
4547
4548   /// BeginFunction - Gather pre-function exception information.  Assumes being
4549   /// emitted immediately after the function entry point.
4550   void BeginFunction(MachineFunction *MF) {
4551     this->MF = MF;
4552     shouldEmitTable = shouldEmitMoves = false;
4553     if (MMI && TAI->doesSupportExceptionHandling()) {
4554
4555       // Map all labels and get rid of any dead landing pads.
4556       MMI->TidyLandingPads();
4557       // If any landing pads survive, we need an EH table.
4558       if (MMI->getLandingPads().size())
4559         shouldEmitTable = true;
4560
4561       // See if we need frame move info.
4562       if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4563         shouldEmitMoves = true;
4564
4565       if (shouldEmitMoves || shouldEmitTable)
4566         // Assumes in correct section after the entry point.
4567         EmitLabel("eh_func_begin", ++SubprogramCount);
4568     }
4569     shouldEmitTableModule |= shouldEmitTable;
4570     shouldEmitMovesModule |= shouldEmitMoves;
4571   }
4572
4573   /// EndFunction - Gather and emit post-function exception information.
4574   ///
4575   void EndFunction() {
4576     if (shouldEmitMoves || shouldEmitTable) {
4577       EmitLabel("eh_func_end", SubprogramCount);
4578       EmitExceptionTable();
4579
4580       // Save EH frame information
4581       EHFrames.
4582         push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4583                                     SubprogramCount,
4584                                     MMI->getPersonalityIndex(),
4585                                     MF->getFrameInfo()->hasCalls(),
4586                                     !MMI->getLandingPads().empty(),
4587                                     MMI->getFrameMoves(),
4588                                     MF->getFunction()));
4589       }
4590   }
4591 };
4592
4593 } // End of namespace llvm
4594
4595 //===----------------------------------------------------------------------===//
4596
4597 /// Emit - Print the abbreviation using the specified Dwarf writer.
4598 ///
4599 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4600   // Emit its Dwarf tag type.
4601   DD.getAsm()->EmitULEB128Bytes(Tag);
4602   DD.getAsm()->EOL(TagString(Tag));
4603
4604   // Emit whether it has children DIEs.
4605   DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4606   DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4607
4608   // For each attribute description.
4609   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4610     const DIEAbbrevData &AttrData = Data[i];
4611
4612     // Emit attribute type.
4613     DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4614     DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4615
4616     // Emit form type.
4617     DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4618     DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4619   }
4620
4621   // Mark end of abbreviation.
4622   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4623   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4624 }
4625
4626 #ifndef NDEBUG
4627 void DIEAbbrev::print(std::ostream &O) {
4628   O << "Abbreviation @"
4629     << std::hex << (intptr_t)this << std::dec
4630     << "  "
4631     << TagString(Tag)
4632     << " "
4633     << ChildrenString(ChildrenFlag)
4634     << "\n";
4635
4636   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4637     O << "  "
4638       << AttributeString(Data[i].getAttribute())
4639       << "  "
4640       << FormEncodingString(Data[i].getForm())
4641       << "\n";
4642   }
4643 }
4644 void DIEAbbrev::dump() { print(cerr); }
4645 #endif
4646
4647 //===----------------------------------------------------------------------===//
4648
4649 #ifndef NDEBUG
4650 void DIEValue::dump() {
4651   print(cerr);
4652 }
4653 #endif
4654
4655 //===----------------------------------------------------------------------===//
4656
4657 /// EmitValue - Emit integer of appropriate size.
4658 ///
4659 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4660   switch (Form) {
4661   case DW_FORM_flag:  // Fall thru
4662   case DW_FORM_ref1:  // Fall thru
4663   case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer);         break;
4664   case DW_FORM_ref2:  // Fall thru
4665   case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer);        break;
4666   case DW_FORM_ref4:  // Fall thru
4667   case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer);        break;
4668   case DW_FORM_ref8:  // Fall thru
4669   case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer);        break;
4670   case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4671   case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4672   default: assert(0 && "DIE Value form not supported yet");   break;
4673   }
4674 }
4675
4676 /// SizeOf - Determine size of integer value in bytes.
4677 ///
4678 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4679   switch (Form) {
4680   case DW_FORM_flag:  // Fall thru
4681   case DW_FORM_ref1:  // Fall thru
4682   case DW_FORM_data1: return sizeof(int8_t);
4683   case DW_FORM_ref2:  // Fall thru
4684   case DW_FORM_data2: return sizeof(int16_t);
4685   case DW_FORM_ref4:  // Fall thru
4686   case DW_FORM_data4: return sizeof(int32_t);
4687   case DW_FORM_ref8:  // Fall thru
4688   case DW_FORM_data8: return sizeof(int64_t);
4689   case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4690   case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4691   default: assert(0 && "DIE Value form not supported yet"); break;
4692   }
4693   return 0;
4694 }
4695
4696 //===----------------------------------------------------------------------===//
4697
4698 /// EmitValue - Emit string value.
4699 ///
4700 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4701   DD.getAsm()->EmitString(String);
4702 }
4703
4704 //===----------------------------------------------------------------------===//
4705
4706 /// EmitValue - Emit label value.
4707 ///
4708 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4709   bool IsSmall = Form == DW_FORM_data4;
4710   DD.EmitReference(Label, false, IsSmall);
4711 }
4712
4713 /// SizeOf - Determine size of label value in bytes.
4714 ///
4715 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4716   if (Form == DW_FORM_data4) return 4;
4717   return DD.getTargetData()->getPointerSize();
4718 }
4719
4720 //===----------------------------------------------------------------------===//
4721
4722 /// EmitValue - Emit label value.
4723 ///
4724 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4725   bool IsSmall = Form == DW_FORM_data4;
4726   DD.EmitReference(Label, false, IsSmall);
4727 }
4728
4729 /// SizeOf - Determine size of label value in bytes.
4730 ///
4731 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4732   if (Form == DW_FORM_data4) return 4;
4733   return DD.getTargetData()->getPointerSize();
4734 }
4735
4736 //===----------------------------------------------------------------------===//
4737
4738 /// EmitValue - Emit delta value.
4739 ///
4740 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4741   bool IsSmall = Form == DW_FORM_data4;
4742   DD.EmitSectionOffset(Label.Tag, Section.Tag,
4743                        Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4744 }
4745
4746 /// SizeOf - Determine size of delta value in bytes.
4747 ///
4748 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4749   if (Form == DW_FORM_data4) return 4;
4750   return DD.getTargetData()->getPointerSize();
4751 }
4752
4753 //===----------------------------------------------------------------------===//
4754
4755 /// EmitValue - Emit delta value.
4756 ///
4757 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4758   bool IsSmall = Form == DW_FORM_data4;
4759   DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4760 }
4761
4762 /// SizeOf - Determine size of delta value in bytes.
4763 ///
4764 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4765   if (Form == DW_FORM_data4) return 4;
4766   return DD.getTargetData()->getPointerSize();
4767 }
4768
4769 //===----------------------------------------------------------------------===//
4770
4771 /// EmitValue - Emit debug information entry offset.
4772 ///
4773 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4774   DD.getAsm()->EmitInt32(Entry->getOffset());
4775 }
4776
4777 //===----------------------------------------------------------------------===//
4778
4779 /// ComputeSize - calculate the size of the block.
4780 ///
4781 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4782   if (!Size) {
4783     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4784
4785     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4786       Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4787     }
4788   }
4789   return Size;
4790 }
4791
4792 /// EmitValue - Emit block data.
4793 ///
4794 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4795   switch (Form) {
4796   case DW_FORM_block1: DD.getAsm()->EmitInt8(Size);         break;
4797   case DW_FORM_block2: DD.getAsm()->EmitInt16(Size);        break;
4798   case DW_FORM_block4: DD.getAsm()->EmitInt32(Size);        break;
4799   case DW_FORM_block:  DD.getAsm()->EmitULEB128Bytes(Size); break;
4800   default: assert(0 && "Improper form for block");          break;
4801   }
4802
4803   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4804
4805   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4806     DD.getAsm()->EOL();
4807     Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4808   }
4809 }
4810
4811 /// SizeOf - Determine size of block data in bytes.
4812 ///
4813 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4814   switch (Form) {
4815   case DW_FORM_block1: return Size + sizeof(int8_t);
4816   case DW_FORM_block2: return Size + sizeof(int16_t);
4817   case DW_FORM_block4: return Size + sizeof(int32_t);
4818   case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4819   default: assert(0 && "Improper form for block"); break;
4820   }
4821   return 0;
4822 }
4823
4824 //===----------------------------------------------------------------------===//
4825 /// DIE Implementation
4826
4827 DIE::~DIE() {
4828   for (unsigned i = 0, N = Children.size(); i < N; ++i)
4829     delete Children[i];
4830 }
4831
4832 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4833 ///
4834 void DIE::AddSiblingOffset() {
4835   DIEInteger *DI = new DIEInteger(0);
4836   Values.insert(Values.begin(), DI);
4837   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4838 }
4839
4840 /// Profile - Used to gather unique data for the value folding set.
4841 ///
4842 void DIE::Profile(FoldingSetNodeID &ID) {
4843   Abbrev.Profile(ID);
4844
4845   for (unsigned i = 0, N = Children.size(); i < N; ++i)
4846     ID.AddPointer(Children[i]);
4847
4848   for (unsigned j = 0, M = Values.size(); j < M; ++j)
4849     ID.AddPointer(Values[j]);
4850 }
4851
4852 #ifndef NDEBUG
4853 void DIE::print(std::ostream &O, unsigned IncIndent) {
4854   static unsigned IndentCount = 0;
4855   IndentCount += IncIndent;
4856   const std::string Indent(IndentCount, ' ');
4857   bool isBlock = Abbrev.getTag() == 0;
4858
4859   if (!isBlock) {
4860     O << Indent
4861       << "Die: "
4862       << "0x" << std::hex << (intptr_t)this << std::dec
4863       << ", Offset: " << Offset
4864       << ", Size: " << Size
4865       << "\n";
4866
4867     O << Indent
4868       << TagString(Abbrev.getTag())
4869       << " "
4870       << ChildrenString(Abbrev.getChildrenFlag());
4871   } else {
4872     O << "Size: " << Size;
4873   }
4874   O << "\n";
4875
4876   const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4877
4878   IndentCount += 2;
4879   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4880     O << Indent;
4881
4882     if (!isBlock)
4883       O << AttributeString(Data[i].getAttribute());
4884     else
4885       O << "Blk[" << i << "]";
4886
4887     O <<  "  "
4888       << FormEncodingString(Data[i].getForm())
4889       << " ";
4890     Values[i]->print(O);
4891     O << "\n";
4892   }
4893   IndentCount -= 2;
4894
4895   for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4896     Children[j]->print(O, 4);
4897   }
4898
4899   if (!isBlock) O << "\n";
4900   IndentCount -= IncIndent;
4901 }
4902
4903 void DIE::dump() {
4904   print(cerr);
4905 }
4906 #endif
4907
4908 //===----------------------------------------------------------------------===//
4909 /// DwarfWriter Implementation
4910 ///
4911
4912 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4913 }
4914
4915 DwarfWriter::~DwarfWriter() {
4916   delete DE;
4917   delete DD;
4918 }
4919
4920 /// BeginModule - Emit all Dwarf sections that should come prior to the
4921 /// content.
4922 void DwarfWriter::BeginModule(Module *M,
4923                               MachineModuleInfo *MMI,
4924                               raw_ostream &OS, AsmPrinter *A,
4925                               const TargetAsmInfo *T) {
4926   DE = new DwarfException(OS, A, T);
4927   DD = new DwarfDebug(OS, A, T);
4928   DE->BeginModule(M);
4929   DD->BeginModule(M);
4930   DD->SetModuleInfo(MMI);
4931   DE->SetModuleInfo(MMI);
4932 }
4933
4934 /// EndModule - Emit all Dwarf sections that should come after the content.
4935 ///
4936 void DwarfWriter::EndModule() {
4937   DE->EndModule();
4938   DD->EndModule();
4939 }
4940
4941 /// BeginFunction - Gather pre-function debug information.  Assumes being
4942 /// emitted immediately after the function entry point.
4943 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4944   DE->BeginFunction(MF);
4945   DD->BeginFunction(MF);
4946 }
4947
4948 /// EndFunction - Gather and emit post-function debug information.
4949 ///
4950 void DwarfWriter::EndFunction(MachineFunction *MF) {
4951   DD->EndFunction(MF);
4952   DE->EndFunction();
4953
4954   if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4955     // Clear function debug information.
4956     MMI->EndFunction();
4957 }
4958
4959 /// RecordSourceLine - Records location information and associates it with a 
4960 /// label. Returns a unique label ID used to generate a label and provide
4961 /// correspondence to the source line list.
4962 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col, 
4963                                        unsigned Src) {
4964   return DD->RecordSourceLine(Line, Col, Src);
4965 }
4966
4967 /// RecordSource - Register a source file with debug info. Returns an source
4968 /// ID.
4969 unsigned DwarfWriter::RecordSource(const std::string &Dir, 
4970                                    const std::string &File) {
4971   return DD->RecordSource(Dir, File);
4972 }
4973
4974 /// RecordRegionStart - Indicate the start of a region.
4975 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4976   return DD->RecordRegionStart(V);
4977 }
4978
4979 /// RecordRegionEnd - Indicate the end of a region.
4980 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4981   return DD->RecordRegionEnd(V);
4982 }
4983
4984 /// getRecordSourceLineCount - Count source lines.
4985 unsigned DwarfWriter::getRecordSourceLineCount() {
4986   return DD->getRecordSourceLineCount();
4987 }