There is no need to maintain separate labelid list in the dwarf writer. It is not...
[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 /// SourceLineInfo - 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   
1254   // Accessors.
1255   DbgScope *getParent()        const { return Parent; }
1256   DIDescriptor *getDesc()       const { return Desc; }
1257   unsigned getStartLabelID()     const { return StartLabelID; }
1258   unsigned getEndLabelID()       const { return EndLabelID; }
1259   SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1260   SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1261   void setStartLabelID(unsigned S) { StartLabelID = S; }
1262   void setEndLabelID(unsigned E)   { EndLabelID = E; }
1263   
1264   /// AddScope - Add a scope to the scope.
1265   ///
1266   void AddScope(DbgScope *S) { Scopes.push_back(S); }
1267   
1268   /// AddVariable - Add a variable to the scope.
1269   ///
1270   void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1271 };
1272
1273 //===----------------------------------------------------------------------===//
1274 /// DwarfDebug - Emits Dwarf debug directives.
1275 ///
1276 class DwarfDebug : public Dwarf {
1277
1278 private:
1279   //===--------------------------------------------------------------------===//
1280   // Attributes used to construct specific Dwarf sections.
1281   //
1282
1283   /// CompileUnits - All the compile units involved in this build.  The index
1284   /// of each entry in this vector corresponds to the sources in MMI.
1285   std::vector<CompileUnit *> CompileUnits;
1286   DenseMap<Value *, CompileUnit *> DW_CUs;
1287
1288   /// AbbreviationsSet - Used to uniquely define abbreviations.
1289   ///
1290   FoldingSet<DIEAbbrev> AbbreviationsSet;
1291
1292   /// Abbreviations - A list of all the unique abbreviations in use.
1293   ///
1294   std::vector<DIEAbbrev *> Abbreviations;
1295
1296   /// ValuesSet - Used to uniquely define values.
1297   ///
1298   // Directories - Uniquing vector for directories.                                       
1299   UniqueVector<std::string> Directories;
1300
1301   // SourceFiles - Uniquing vector for source files.                                      
1302   UniqueVector<SrcFileInfo> SrcFiles;
1303
1304   // Lines - List of of source line correspondence.
1305   std::vector<SrcLineInfo> Lines;
1306
1307   FoldingSet<DIEValue> ValuesSet;
1308
1309   /// Values - A list of all the unique values in use.
1310   ///
1311   std::vector<DIEValue *> Values;
1312
1313   /// StringPool - A UniqueVector of strings used by indirect references.
1314   ///
1315   UniqueVector<std::string> StringPool;
1316
1317   /// UnitMap - Map debug information descriptor to compile unit.
1318   ///
1319   std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1320
1321   /// SectionMap - Provides a unique id per text section.
1322   ///
1323   UniqueVector<const Section*> SectionMap;
1324
1325   /// SectionSourceLines - Tracks line numbers per text section.
1326   ///
1327   std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1328
1329   /// didInitial - Flag to indicate if initial emission has been done.
1330   ///
1331   bool didInitial;
1332
1333   /// shouldEmit - Flag to indicate if debug information should be emitted.
1334   ///
1335   bool shouldEmit;
1336
1337   // RootScope - Top level scope for the current function.
1338   //
1339   DbgScope *RootDbgScope;
1340   
1341   // DbgScopeMap - Tracks the scopes in the current function.
1342   DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1343   
1344   struct FunctionDebugFrameInfo {
1345     unsigned Number;
1346     std::vector<MachineMove> Moves;
1347
1348     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1349       Number(Num), Moves(M) { }
1350   };
1351
1352   std::vector<FunctionDebugFrameInfo> DebugFrames;
1353
1354 public:
1355
1356   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1357   ///
1358   bool ShouldEmitDwarf() const { return shouldEmit; }
1359
1360   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1361   ///
1362   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1363     // Profile the node so that we can make it unique.
1364     FoldingSetNodeID ID;
1365     Abbrev.Profile(ID);
1366
1367     // Check the set for priors.
1368     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1369
1370     // If it's newly added.
1371     if (InSet == &Abbrev) {
1372       // Add to abbreviation list.
1373       Abbreviations.push_back(&Abbrev);
1374       // Assign the vector position + 1 as its number.
1375       Abbrev.setNumber(Abbreviations.size());
1376     } else {
1377       // Assign existing abbreviation number.
1378       Abbrev.setNumber(InSet->getNumber());
1379     }
1380   }
1381
1382   /// NewString - Add a string to the constant pool and returns a label.
1383   ///
1384   DWLabel NewString(const std::string &String) {
1385     unsigned StringID = StringPool.insert(String);
1386     return DWLabel("string", StringID);
1387   }
1388
1389   /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1390   /// entry.
1391   DIEntry *NewDIEntry(DIE *Entry = NULL) {
1392     DIEntry *Value;
1393
1394     if (Entry) {
1395       FoldingSetNodeID ID;
1396       DIEntry::Profile(ID, Entry);
1397       void *Where;
1398       Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1399
1400       if (Value) return Value;
1401
1402       Value = new DIEntry(Entry);
1403       ValuesSet.InsertNode(Value, Where);
1404     } else {
1405       Value = new DIEntry(Entry);
1406     }
1407
1408     Values.push_back(Value);
1409     return Value;
1410   }
1411
1412   /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1413   ///
1414   void SetDIEntry(DIEntry *Value, DIE *Entry) {
1415     Value->Entry = Entry;
1416     // Add to values set if not already there.  If it is, we merely have a
1417     // duplicate in the values list (no harm.)
1418     ValuesSet.GetOrInsertNode(Value);
1419   }
1420
1421   /// AddUInt - Add an unsigned integer attribute data and value.
1422   ///
1423   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1424     if (!Form) Form = DIEInteger::BestForm(false, Integer);
1425
1426     FoldingSetNodeID ID;
1427     DIEInteger::Profile(ID, Integer);
1428     void *Where;
1429     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1430     if (!Value) {
1431       Value = new DIEInteger(Integer);
1432       ValuesSet.InsertNode(Value, Where);
1433       Values.push_back(Value);
1434     }
1435
1436     Die->AddValue(Attribute, Form, Value);
1437   }
1438
1439   /// AddSInt - Add an signed integer attribute data and value.
1440   ///
1441   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1442     if (!Form) Form = DIEInteger::BestForm(true, Integer);
1443
1444     FoldingSetNodeID ID;
1445     DIEInteger::Profile(ID, (uint64_t)Integer);
1446     void *Where;
1447     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1448     if (!Value) {
1449       Value = new DIEInteger(Integer);
1450       ValuesSet.InsertNode(Value, Where);
1451       Values.push_back(Value);
1452     }
1453
1454     Die->AddValue(Attribute, Form, Value);
1455   }
1456
1457   /// AddString - Add a std::string attribute data and value.
1458   ///
1459   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1460                  const std::string &String) {
1461     FoldingSetNodeID ID;
1462     DIEString::Profile(ID, String);
1463     void *Where;
1464     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1465     if (!Value) {
1466       Value = new DIEString(String);
1467       ValuesSet.InsertNode(Value, Where);
1468       Values.push_back(Value);
1469     }
1470
1471     Die->AddValue(Attribute, Form, Value);
1472   }
1473
1474   /// AddLabel - Add a Dwarf label attribute data and value.
1475   ///
1476   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1477                      const DWLabel &Label) {
1478     FoldingSetNodeID ID;
1479     DIEDwarfLabel::Profile(ID, Label);
1480     void *Where;
1481     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1482     if (!Value) {
1483       Value = new DIEDwarfLabel(Label);
1484       ValuesSet.InsertNode(Value, Where);
1485       Values.push_back(Value);
1486     }
1487
1488     Die->AddValue(Attribute, Form, Value);
1489   }
1490
1491   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1492   ///
1493   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1494                       const std::string &Label) {
1495     FoldingSetNodeID ID;
1496     DIEObjectLabel::Profile(ID, Label);
1497     void *Where;
1498     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1499     if (!Value) {
1500       Value = new DIEObjectLabel(Label);
1501       ValuesSet.InsertNode(Value, Where);
1502       Values.push_back(Value);
1503     }
1504
1505     Die->AddValue(Attribute, Form, Value);
1506   }
1507
1508   /// AddSectionOffset - Add a section offset label attribute data and value.
1509   ///
1510   void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1511                         const DWLabel &Label, const DWLabel &Section,
1512                         bool isEH = false, bool useSet = true) {
1513     FoldingSetNodeID ID;
1514     DIESectionOffset::Profile(ID, Label, Section);
1515     void *Where;
1516     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1517     if (!Value) {
1518       Value = new DIESectionOffset(Label, Section, isEH, useSet);
1519       ValuesSet.InsertNode(Value, Where);
1520       Values.push_back(Value);
1521     }
1522
1523     Die->AddValue(Attribute, Form, Value);
1524   }
1525
1526   /// AddDelta - Add a label delta attribute data and value.
1527   ///
1528   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1529                           const DWLabel &Hi, const DWLabel &Lo) {
1530     FoldingSetNodeID ID;
1531     DIEDelta::Profile(ID, Hi, Lo);
1532     void *Where;
1533     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1534     if (!Value) {
1535       Value = new DIEDelta(Hi, Lo);
1536       ValuesSet.InsertNode(Value, Where);
1537       Values.push_back(Value);
1538     }
1539
1540     Die->AddValue(Attribute, Form, Value);
1541   }
1542
1543   /// AddDIEntry - Add a DIE attribute data and value.
1544   ///
1545   void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1546     Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1547   }
1548
1549   /// AddBlock - Add block data.
1550   ///
1551   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1552     Block->ComputeSize(*this);
1553     FoldingSetNodeID ID;
1554     Block->Profile(ID);
1555     void *Where;
1556     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1557     if (!Value) {
1558       Value = Block;
1559       ValuesSet.InsertNode(Value, Where);
1560       Values.push_back(Value);
1561     } else {
1562       // Already exists, reuse the previous one.
1563       delete Block;
1564       Block = cast<DIEBlock>(Value);
1565     }
1566
1567     Die->AddValue(Attribute, Block->BestForm(), Value);
1568   }
1569
1570 private:
1571
1572   /// AddSourceLine - Add location information to specified debug information
1573   /// entry.
1574   void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1575     if (File && Line) {
1576       CompileUnit *FileUnit = FindCompileUnit(File);
1577       unsigned FileID = FileUnit->getID();
1578       AddUInt(Die, DW_AT_decl_file, 0, FileID);
1579       AddUInt(Die, DW_AT_decl_line, 0, Line);
1580     }
1581   }
1582
1583   /// AddSourceLine - Add location information to specified debug information
1584   /// entry.
1585   void AddSourceLine(DIE *Die, DIVariable *V) {
1586     unsigned FileID = 0;
1587     unsigned Line = V->getLineNumber();
1588     if (V->getVersion() < DIDescriptor::Version7) {
1589       // Version6 or earlier. Use compile unit info to get file id.
1590       CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1591       FileID = Unit->getID();
1592     } else {
1593       // Version7 or newer, use filename and directory info from DIVariable
1594       // directly.
1595       unsigned DID = Directories.idFor(V->getDirectory());
1596       FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
1597     }
1598     AddUInt(Die, DW_AT_decl_file, 0, FileID);
1599     AddUInt(Die, DW_AT_decl_line, 0, Line);
1600   }
1601
1602   /// AddSourceLine - Add location information to specified debug information
1603   /// entry.
1604   void AddSourceLine(DIE *Die, DIGlobal *G) {
1605     unsigned FileID = 0;
1606     unsigned Line = G->getLineNumber();
1607     if (G->getVersion() < DIDescriptor::Version7) {
1608       // Version6 or earlier. Use compile unit info to get file id.
1609       CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1610       FileID = Unit->getID();
1611     } else {
1612       // Version7 or newer, use filename and directory info from DIGlobal
1613       // directly.
1614       unsigned DID = Directories.idFor(G->getDirectory());
1615       FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1616     }
1617     AddUInt(Die, DW_AT_decl_file, 0, FileID);
1618     AddUInt(Die, DW_AT_decl_line, 0, Line);
1619   }
1620
1621   void AddSourceLine(DIE *Die, DIType *G) {
1622     unsigned FileID = 0;
1623     unsigned Line = G->getLineNumber();
1624     if (G->getVersion() < DIDescriptor::Version7) {
1625       // Version6 or earlier. Use compile unit info to get file id.
1626       CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1627       FileID = Unit->getID();
1628     } else {
1629       // Version7 or newer, use filename and directory info from DIGlobal
1630       // directly.
1631       unsigned DID = Directories.idFor(G->getDirectory());
1632       FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1633     }
1634     AddUInt(Die, DW_AT_decl_file, 0, FileID);
1635     AddUInt(Die, DW_AT_decl_line, 0, Line);
1636   }
1637
1638   /// AddAddress - Add an address attribute to a die based on the location
1639   /// provided.
1640   void AddAddress(DIE *Die, unsigned Attribute,
1641                             const MachineLocation &Location) {
1642     unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1643     DIEBlock *Block = new DIEBlock();
1644
1645     if (Location.isReg()) {
1646       if (Reg < 32) {
1647         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1648       } else {
1649         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1650         AddUInt(Block, 0, DW_FORM_udata, Reg);
1651       }
1652     } else {
1653       if (Reg < 32) {
1654         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1655       } else {
1656         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1657         AddUInt(Block, 0, DW_FORM_udata, Reg);
1658       }
1659       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1660     }
1661
1662     AddBlock(Die, Attribute, 0, Block);
1663   }
1664
1665   /// AddBasicType - Add a new basic type attribute to the specified entity.
1666   ///
1667   void AddBasicType(DIE *Entity, CompileUnit *Unit,
1668                     const std::string &Name,
1669                     unsigned Encoding, unsigned Size) {
1670
1671     DIE Buffer(DW_TAG_base_type);
1672     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1673     AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1674     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1675     DIE *BasicTypeDie = Unit->AddDie(Buffer);
1676     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1677   }
1678
1679   /// AddPointerType - Add a new pointer type attribute to the specified entity.
1680   ///
1681   void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1682     DIE Buffer(DW_TAG_pointer_type);
1683     AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1684     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1685     DIE *PointerTypeDie =  Unit->AddDie(Buffer);
1686     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1687   }
1688
1689   /// AddType - Add a new type attribute to the specified entity.
1690   ///
1691   void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1692     if (!TyDesc) {
1693       AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1694     } else {
1695       // Check for pre-existence.
1696       DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1697
1698       // If it exists then use the existing value.
1699       if (Slot) {
1700         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1701         return;
1702       }
1703
1704       if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1705         // FIXME - Not sure why programs and variables are coming through here.
1706         // Short cut for handling subprogram types (not really a TyDesc.)
1707         AddPointerType(Entity, Unit, SubprogramTy->getName());
1708       } else if (GlobalVariableDesc *GlobalTy =
1709                                          dyn_cast<GlobalVariableDesc>(TyDesc)) {
1710         // FIXME - Not sure why programs and variables are coming through here.
1711         // Short cut for handling global variable types (not really a TyDesc.)
1712         AddPointerType(Entity, Unit, GlobalTy->getName());
1713       } else {
1714         // Set up proxy.
1715         Slot = NewDIEntry();
1716
1717         // Construct type.
1718         DIE Buffer(DW_TAG_base_type);
1719         ConstructType(Buffer, TyDesc, Unit);
1720
1721         // Add debug information entry to entity and unit.
1722         DIE *Die = Unit->AddDie(Buffer);
1723         SetDIEntry(Slot, Die);
1724         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1725       }
1726     }
1727   }
1728
1729   /// AddType - Add a new type attribute to the specified entity.
1730   void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1731     if (Ty.isNull()) {
1732       AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1733       return;
1734     }
1735
1736     // Check for pre-existence.
1737     DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1738     // If it exists then use the existing value.
1739     if (Slot) {
1740       Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1741       return;
1742     }
1743
1744     // Set up proxy. 
1745     Slot = NewDIEntry();
1746
1747     // Construct type.
1748     DIE Buffer(DW_TAG_base_type);
1749     if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1750       ConstructTypeDIE(DW_Unit, Buffer, BT);
1751     else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1752       ConstructTypeDIE(DW_Unit, Buffer, DT);
1753     else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1754       ConstructTypeDIE(DW_Unit, Buffer, CT);
1755
1756     // Add debug information entry to entity and unit.
1757     DIE *Die = DW_Unit->AddDie(Buffer);
1758     SetDIEntry(Slot, Die);
1759     Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1760   }
1761
1762   /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1763   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1764                         DIBasicType *BTy) {
1765     
1766     // Get core information.
1767     const std::string &Name = BTy->getName();
1768     Buffer.setTag(DW_TAG_base_type);
1769     AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BTy->getEncoding());
1770     // Add name if not anonymous or intermediate type.
1771     if (!Name.empty())
1772       AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1773     uint64_t Size = BTy->getSizeInBits() >> 3;
1774     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1775   }
1776
1777   /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1778   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1779                         DIDerivedType *DTy) {
1780
1781     // Get core information.
1782     const std::string &Name = DTy->getName();
1783     uint64_t Size = DTy->getSizeInBits() >> 3;
1784     unsigned Tag = DTy->getTag();
1785     // FIXME - Workaround for templates.
1786     if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1787
1788     Buffer.setTag(Tag);
1789     // Map to main type, void will not have a type.
1790     DIType FromTy = DTy->getTypeDerivedFrom();
1791     AddType(DW_Unit, &Buffer, FromTy);
1792
1793     // Add name if not anonymous or intermediate type.
1794     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1795
1796     // Add size if non-zero (derived types might be zero-sized.)
1797     if (Size)
1798       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1799
1800     // Add source line info if available and TyDesc is not a forward
1801     // declaration.
1802     // FIXME - Enable this. if (!DTy->isForwardDecl())
1803     // FIXME - Enable this.     AddSourceLine(&Buffer, *DTy);
1804   }
1805
1806   /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1807   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1808                         DICompositeType *CTy) {
1809
1810     // Get core information.                                                              
1811     const std::string &Name = CTy->getName();
1812     uint64_t Size = CTy->getSizeInBits() >> 3;
1813     unsigned Tag = CTy->getTag();
1814     switch (Tag) {
1815     case DW_TAG_vector_type:
1816     case DW_TAG_array_type:
1817       ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
1818       break;
1819     //FIXME - Enable this. 
1820     // case DW_TAG_enumeration_type:
1821     //  DIArray Elements = CTy->getTypeArray();
1822     //  // Add enumerators to enumeration type.
1823     //  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) 
1824     //   ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1825     //  break;
1826     case DW_TAG_subroutine_type: 
1827       {
1828         // Add prototype flag.
1829         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1830         DIArray Elements = CTy->getTypeArray();
1831         // Add return type.
1832         DIDescriptor RTy = Elements.getElement(0);
1833         if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
1834           AddType(DW_Unit, &Buffer, *BT);
1835         else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
1836           AddType(DW_Unit, &Buffer, *DT);
1837         else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
1838           AddType(DW_Unit, &Buffer, *CT);
1839
1840         //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1841         // Add arguments.
1842         for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1843           DIE *Arg = new DIE(DW_TAG_formal_parameter);
1844           DIDescriptor Ty = Elements.getElement(i);
1845           if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1846             AddType(DW_Unit, &Buffer, *BT);
1847           else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1848             AddType(DW_Unit, &Buffer, *DT);
1849           else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1850             AddType(DW_Unit, &Buffer, *CT);
1851           Buffer.AddChild(Arg);
1852         }
1853       }
1854       break;
1855     case DW_TAG_structure_type:
1856     case DW_TAG_union_type: 
1857       {
1858         // Add elements to structure type.
1859         DIArray Elements = CTy->getTypeArray();
1860         // Add elements to structure type.
1861         for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1862           DIDescriptor Element = Elements.getElement(i);
1863           if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
1864             ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
1865           else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
1866             ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1867           else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
1868             ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
1869         }
1870       }
1871       break;
1872     default:
1873       break;
1874     }
1875
1876     // Add name if not anonymous or intermediate type.
1877     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1878
1879     // Add size if non-zero (derived types might be zero-sized.)
1880     if (Size)
1881       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1882     else {
1883       // Add zero size even if it is not a forward declaration.
1884       // FIXME - Enable this.
1885       //      if (!CTy->isDefinition())
1886       //        AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1887       //      else
1888       //        AddUInt(&Buffer, DW_AT_byte_size, 0, 0); 
1889     }
1890
1891     // Add source line info if available and TyDesc is not a forward
1892     // declaration.
1893     // FIXME - Enable this.
1894     // if (CTy->isForwardDecl())                                            
1895     //   AddSourceLine(&Buffer, *CTy);                                    
1896   }
1897   
1898   // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1899   void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1900     int64_t L = SR->getLo();
1901     int64_t H = SR->getHi();
1902     DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1903     if (L != H) {
1904       AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1905       if (L)
1906         AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1907         AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1908     }
1909     Buffer.AddChild(DW_Subrange);
1910   }
1911
1912   /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1913   void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 
1914                              DICompositeType *CTy) {
1915     Buffer.setTag(DW_TAG_array_type);
1916     if (CTy->getTag() == DW_TAG_vector_type)
1917       AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1918     
1919     DIArray Elements = CTy->getTypeArray();
1920     // FIXME - Enable this. 
1921     AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1922
1923     // Construct an anonymous type for index type.
1924     DIE IdxBuffer(DW_TAG_base_type);
1925     AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1926     AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1927     DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1928
1929     // Add subranges to array type.
1930     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1931       DIDescriptor Element = Elements.getElement(i);
1932       if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
1933         ConstructSubrangeDIE(Buffer, SR, IndexTy);
1934     }
1935   }
1936
1937   /// ConstructEnumTypeDIE - Construct enum type DIE from 
1938   /// DIEnumerator.
1939   void ConstructEnumTypeDIE(CompileUnit *DW_Unit, 
1940                             DIE &Buffer, DIEnumerator *ETy) {
1941
1942     DIE *Enumerator = new DIE(DW_TAG_enumerator);
1943     AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1944     int64_t Value = ETy->getEnumValue();                             
1945     AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1946     Buffer.AddChild(Enumerator);
1947   }
1948
1949   /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1950   void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1951                              DIE &Buffer, DIGlobalVariable *V) {
1952
1953     DIE *VariableDie = new DIE(DW_TAG_variable);
1954     const std::string &LinkageName = V->getLinkageName();
1955     if (!LinkageName.empty())
1956       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1957                 LinkageName);
1958     // FIXME - Enable this. AddSourceLine(VariableDie, V);
1959     AddType(DW_Unit, VariableDie, V->getType());
1960     if (!V->isLocalToUnit())
1961       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1962     AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1963     Buffer.AddChild(VariableDie);
1964   }
1965
1966   /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1967   void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1968                              DIE &Buffer, DISubprogram *SP,
1969                              bool IsConstructor = false) {
1970     DIE *Method = new DIE(DW_TAG_subprogram);
1971     AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
1972     const std::string &LinkageName = SP->getLinkageName();
1973     if (!LinkageName.empty())
1974       AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1975     // FIXME - Enable this. AddSourceLine(Method, SP);
1976
1977     DICompositeType MTy = SP->getType();
1978     DIArray Args = MTy.getTypeArray();
1979
1980     // Add Return Type.
1981     if (!IsConstructor) {
1982       DIDescriptor Ty = Args.getElement(0);
1983       if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1984         AddType(DW_Unit, Method, *BT);
1985       else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1986         AddType(DW_Unit, Method, *DT);
1987       else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1988         AddType(DW_Unit, Method, *CT);
1989     }
1990
1991     // Add arguments.
1992     for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1993       DIE *Arg = new DIE(DW_TAG_formal_parameter);
1994       DIDescriptor Ty = Args.getElement(i);
1995       if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1996         AddType(DW_Unit, Method, *BT);
1997       else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1998         AddType(DW_Unit, Method, *DT);
1999       else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
2000         AddType(DW_Unit, Method, *CT);
2001       AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
2002       Method->AddChild(Arg);
2003     }
2004
2005     if (!SP->isLocalToUnit())
2006       AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);                     
2007     Buffer.AddChild(Method);
2008   }
2009
2010   /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
2011  void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
2012                             DIDerivedType *DTy) {
2013     unsigned Tag = DTy->getTag();
2014     DIE *MemberDie = new DIE(Tag);
2015     if (!DTy->getName().empty())
2016       AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
2017     // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
2018
2019     DIType FromTy = DTy->getTypeDerivedFrom();
2020     AddType(DW_Unit, MemberDie, FromTy);
2021
2022     uint64_t Size = DTy->getSizeInBits();
2023     uint64_t Offset = DTy->getOffsetInBits();
2024
2025     // FIXME Handle bitfields                                                      
2026
2027     // Add size.
2028     AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
2029     // Add computation for offset.                                                        
2030     DIEBlock *Block = new DIEBlock();
2031     AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2032     AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
2033     AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
2034
2035     // FIXME Handle DW_AT_accessibility.
2036
2037     Buffer.AddChild(MemberDie);
2038   }
2039
2040   /// ConstructType - Adds all the required attributes to the type.
2041   ///
2042   void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
2043     // Get core information.
2044     const std::string &Name = TyDesc->getName();
2045     uint64_t Size = TyDesc->getSize() >> 3;
2046
2047     if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
2048       // Fundamental types like int, float, bool
2049       Buffer.setTag(DW_TAG_base_type);
2050       AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BasicTy->getEncoding());
2051     } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
2052       // Fetch tag.
2053       unsigned Tag = DerivedTy->getTag();
2054       // FIXME - Workaround for templates.
2055       if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
2056       // Pointers, typedefs et al.
2057       Buffer.setTag(Tag);
2058       // Map to main type, void will not have a type.
2059       if (TypeDesc *FromTy = DerivedTy->getFromType())
2060         AddType(&Buffer, FromTy, Unit);
2061     } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
2062       // Fetch tag.
2063       unsigned Tag = CompTy->getTag();
2064
2065       // Set tag accordingly.
2066       if (Tag == DW_TAG_vector_type)
2067         Buffer.setTag(DW_TAG_array_type);
2068       else
2069         Buffer.setTag(Tag);
2070
2071       std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
2072
2073       switch (Tag) {
2074       case DW_TAG_vector_type:
2075         AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
2076         // Fall thru
2077       case DW_TAG_array_type: {
2078         // Add element type.
2079         if (TypeDesc *FromTy = CompTy->getFromType())
2080           AddType(&Buffer, FromTy, Unit);
2081
2082         // Don't emit size attribute.
2083         Size = 0;
2084
2085         // Construct an anonymous type for index type.
2086         DIE Buffer(DW_TAG_base_type);
2087         AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
2088         AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
2089         DIE *IndexTy = Unit->AddDie(Buffer);
2090
2091         // Add subranges to array type.
2092         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2093           SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
2094           int64_t Lo = SRD->getLo();
2095           int64_t Hi = SRD->getHi();
2096           DIE *Subrange = new DIE(DW_TAG_subrange_type);
2097
2098           // If a range is available.
2099           if (Lo != Hi) {
2100             AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
2101             // Only add low if non-zero.
2102             if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
2103             AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
2104           }
2105
2106           Buffer.AddChild(Subrange);
2107         }
2108         break;
2109       }
2110       case DW_TAG_structure_type:
2111       case DW_TAG_union_type: {
2112         // Add elements to structure type.
2113         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2114           DebugInfoDesc *Element = Elements[i];
2115
2116           if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
2117             // Add field or base class.
2118             unsigned Tag = MemberDesc->getTag();
2119
2120             // Extract the basic information.
2121             const std::string &Name = MemberDesc->getName();
2122             uint64_t Size = MemberDesc->getSize();
2123             uint64_t Align = MemberDesc->getAlign();
2124             uint64_t Offset = MemberDesc->getOffset();
2125
2126             // Construct member debug information entry.
2127             DIE *Member = new DIE(Tag);
2128
2129             // Add name if not "".
2130             if (!Name.empty())
2131               AddString(Member, DW_AT_name, DW_FORM_string, Name);
2132
2133             // Add location if available.
2134             AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
2135
2136             // Most of the time the field info is the same as the members.
2137             uint64_t FieldSize = Size;
2138             uint64_t FieldAlign = Align;
2139             uint64_t FieldOffset = Offset;
2140
2141             // Set the member type.
2142             TypeDesc *FromTy = MemberDesc->getFromType();
2143             AddType(Member, FromTy, Unit);
2144
2145             // Walk up typedefs until a real size is found.
2146             while (FromTy) {
2147               if (FromTy->getTag() != DW_TAG_typedef) {
2148                 FieldSize = FromTy->getSize();
2149                 FieldAlign = FromTy->getAlign();
2150                 break;
2151               }
2152
2153               FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
2154             }
2155
2156             // Unless we have a bit field.
2157             if (Tag == DW_TAG_member && FieldSize != Size) {
2158               // Construct the alignment mask.
2159               uint64_t AlignMask = ~(FieldAlign - 1);
2160               // Determine the high bit + 1 of the declared size.
2161               uint64_t HiMark = (Offset + FieldSize) & AlignMask;
2162               // Work backwards to determine the base offset of the field.
2163               FieldOffset = HiMark - FieldSize;
2164               // Now normalize offset to the field.
2165               Offset -= FieldOffset;
2166
2167               // Maybe we need to work from the other end.
2168               if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
2169
2170               // Add size and offset.
2171               AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
2172               AddUInt(Member, DW_AT_bit_size, 0, Size);
2173               AddUInt(Member, DW_AT_bit_offset, 0, Offset);
2174             }
2175
2176             // Add computation for offset.
2177             DIEBlock *Block = new DIEBlock();
2178             AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2179             AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
2180             AddBlock(Member, DW_AT_data_member_location, 0, Block);
2181
2182             // Add accessibility (public default unless is base class.
2183             if (MemberDesc->isProtected()) {
2184               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
2185             } else if (MemberDesc->isPrivate()) {
2186               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
2187             } else if (Tag == DW_TAG_inheritance) {
2188               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
2189             }
2190
2191             Buffer.AddChild(Member);
2192           } else if (GlobalVariableDesc *StaticDesc =
2193                                         dyn_cast<GlobalVariableDesc>(Element)) {
2194             // Add static member.
2195
2196             // Construct member debug information entry.
2197             DIE *Static = new DIE(DW_TAG_variable);
2198
2199             // Add name and mangled name.
2200             const std::string &Name = StaticDesc->getName();
2201             const std::string &LinkageName = StaticDesc->getLinkageName();
2202             AddString(Static, DW_AT_name, DW_FORM_string, Name);
2203             if (!LinkageName.empty()) {
2204               AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
2205                                 LinkageName);
2206             }
2207
2208             // Add location.
2209             AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
2210
2211             // Add type.
2212             if (TypeDesc *StaticTy = StaticDesc->getType())
2213               AddType(Static, StaticTy, Unit);
2214
2215             // Add flags.
2216             if (!StaticDesc->isStatic())
2217               AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
2218             AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
2219
2220             Buffer.AddChild(Static);
2221           } else if (SubprogramDesc *MethodDesc =
2222                                             dyn_cast<SubprogramDesc>(Element)) {
2223             // Add member function.
2224
2225             // Construct member debug information entry.
2226             DIE *Method = new DIE(DW_TAG_subprogram);
2227
2228             // Add name and mangled name.
2229             const std::string &Name = MethodDesc->getName();
2230             const std::string &LinkageName = MethodDesc->getLinkageName();
2231
2232             AddString(Method, DW_AT_name, DW_FORM_string, Name);
2233             bool IsCTor = TyDesc->getName() == Name;
2234
2235             if (!LinkageName.empty()) {
2236               AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
2237                                 LinkageName);
2238             }
2239
2240             // Add location.
2241             AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
2242
2243             // Add type.
2244             if (CompositeTypeDesc *MethodTy =
2245                    dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
2246               // Get argument information.
2247               std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
2248
2249               // If not a ctor.
2250               if (!IsCTor) {
2251                 // Add return type.
2252                 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
2253               }
2254
2255               // Add arguments.
2256               for (unsigned i = 1, N = Args.size(); i < N; ++i) {
2257                 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2258                 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
2259                 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
2260                 Method->AddChild(Arg);
2261               }
2262             }
2263
2264             // Add flags.
2265             if (!MethodDesc->isStatic())
2266               AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2267             AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
2268
2269             Buffer.AddChild(Method);
2270           }
2271         }
2272         break;
2273       }
2274       case DW_TAG_enumeration_type: {
2275         // Add enumerators to enumeration type.
2276         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2277           EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
2278           const std::string &Name = ED->getName();
2279           int64_t Value = ED->getValue();
2280           DIE *Enumerator = new DIE(DW_TAG_enumerator);
2281           AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
2282           AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
2283           Buffer.AddChild(Enumerator);
2284         }
2285
2286         break;
2287       }
2288       case DW_TAG_subroutine_type: {
2289         // Add prototype flag.
2290         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
2291         // Add return type.
2292         AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
2293
2294         // Add arguments.
2295         for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
2296           DIE *Arg = new DIE(DW_TAG_formal_parameter);
2297           AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
2298           Buffer.AddChild(Arg);
2299         }
2300
2301         break;
2302       }
2303       default: break;
2304       }
2305     }
2306
2307     // Add name if not anonymous or intermediate type.
2308     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
2309
2310     // Add size if non-zero (derived types might be zero-sized.)
2311     if (Size)
2312       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
2313     else if (isa<CompositeTypeDesc>(TyDesc)) {
2314       // If TyDesc is a composite type, then add size even if it's zero unless
2315       // it's a forward declaration.
2316       if (TyDesc->isForwardDecl())
2317         AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
2318       else
2319         AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
2320     }
2321
2322     // Add source line info if available and TyDesc is not a forward
2323     // declaration.
2324     if (!TyDesc->isForwardDecl())
2325       AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
2326   }
2327
2328   /// NewCompileUnit - Create new compile unit and it's debug information entry.
2329   ///
2330   CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
2331     // Construct debug information entry.
2332     DIE *Die = new DIE(DW_TAG_compile_unit);
2333     AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2334               DWLabel("section_line", 0), DWLabel("section_line", 0), false);
2335     AddString(Die, DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
2336     AddUInt  (Die, DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
2337     AddString(Die, DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
2338     if (!UnitDesc->getDirectory().empty())
2339       AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
2340
2341     // Construct compile unit.
2342     CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
2343
2344     // Add Unit to compile unit map.
2345     DescToUnitMap[UnitDesc] = Unit;
2346
2347     return Unit;
2348   }
2349
2350   /// GetBaseCompileUnit - Get the main compile unit.
2351   ///
2352   CompileUnit *GetBaseCompileUnit() const {
2353     CompileUnit *Unit = CompileUnits[0];
2354     assert(Unit && "Missing compile unit.");
2355     return Unit;
2356   }
2357
2358   /// FindCompileUnit - Get the compile unit for the given descriptor.
2359   ///
2360   CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
2361     CompileUnit *Unit = DescToUnitMap[UnitDesc];
2362     assert(Unit && "Missing compile unit.");
2363     return Unit;
2364   }
2365
2366   /// FindCompileUnit - Get the compile unit for the given descriptor.                    
2367   ///                                                                                     
2368   CompileUnit *FindCompileUnit(DICompileUnit Unit) {
2369     CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
2370     assert(DW_Unit && "Missing compile unit.");
2371     return DW_Unit;
2372   }
2373
2374   /// NewGlobalVariable - Add a new global variable DIE.
2375   ///
2376   DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
2377     // Get the compile unit context.
2378     CompileUnitDesc *UnitDesc =
2379       static_cast<CompileUnitDesc *>(GVD->getContext());
2380     CompileUnit *Unit = GetBaseCompileUnit();
2381
2382     // Check for pre-existence.
2383     DIE *&Slot = Unit->getDieMapSlotFor(GVD);
2384     if (Slot) return Slot;
2385
2386     // Get the global variable itself.
2387     GlobalVariable *GV = GVD->getGlobalVariable();
2388
2389     const std::string &Name = GVD->getName();
2390     const std::string &FullName = GVD->getFullName();
2391     const std::string &LinkageName = GVD->getLinkageName();
2392     // Create the global's variable DIE.
2393     DIE *VariableDie = new DIE(DW_TAG_variable);
2394     AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2395     if (!LinkageName.empty()) {
2396       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2397                              LinkageName);
2398     }
2399     AddType(VariableDie, GVD->getType(), Unit);
2400     if (!GVD->isStatic())
2401       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2402
2403     // Add source line info if available.
2404     AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
2405
2406     // Add address.
2407     DIEBlock *Block = new DIEBlock();
2408     AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2409     AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
2410     AddBlock(VariableDie, DW_AT_location, 0, Block);
2411
2412     // Add to map.
2413     Slot = VariableDie;
2414
2415     // Add to context owner.
2416     Unit->getDie()->AddChild(VariableDie);
2417
2418     // Expose as global.
2419     // FIXME - need to check external flag.
2420     Unit->AddGlobal(FullName, VariableDie);
2421
2422     return VariableDie;
2423   }
2424
2425   /// NewSubprogram - Add a new subprogram DIE.
2426   ///
2427   DIE *NewSubprogram(SubprogramDesc *SPD) {
2428     // Get the compile unit context.
2429     CompileUnitDesc *UnitDesc =
2430       static_cast<CompileUnitDesc *>(SPD->getContext());
2431     CompileUnit *Unit = GetBaseCompileUnit();
2432
2433     // Check for pre-existence.
2434     DIE *&Slot = Unit->getDieMapSlotFor(SPD);
2435     if (Slot) return Slot;
2436
2437     // Gather the details (simplify add attribute code.)
2438     const std::string &Name = SPD->getName();
2439     const std::string &FullName = SPD->getFullName();
2440     const std::string &LinkageName = SPD->getLinkageName();
2441
2442     DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2443     AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
2444     if (!LinkageName.empty()) {
2445       AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2446                                LinkageName);
2447     }
2448     if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
2449     if (!SPD->isStatic())
2450       AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2451     AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2452
2453     // Add source line info if available.
2454     AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2455
2456     // Add to map.
2457     Slot = SubprogramDie;
2458
2459     // Add to context owner.
2460     Unit->getDie()->AddChild(SubprogramDie);
2461
2462     // Expose as global.
2463     Unit->AddGlobal(FullName, SubprogramDie);
2464
2465     return SubprogramDie;
2466   }
2467
2468   /// NewScopeVariable - Create a new scope variable.
2469   ///
2470   DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2471     // Get the descriptor.
2472     VariableDesc *VD = DV->getDesc();
2473
2474     // Translate tag to proper Dwarf tag.  The result variable is dropped for
2475     // now.
2476     unsigned Tag;
2477     switch (VD->getTag()) {
2478     case DW_TAG_return_variable:  return NULL;
2479     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
2480     case DW_TAG_auto_variable:    // fall thru
2481     default:                      Tag = DW_TAG_variable; break;
2482     }
2483
2484     // Define variable debug information entry.
2485     DIE *VariableDie = new DIE(Tag);
2486     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2487
2488     // Add source line info if available.
2489     AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2490
2491     // Add variable type.
2492     AddType(VariableDie, VD->getType(), Unit);
2493
2494     // Add variable address.
2495     MachineLocation Location;
2496     Location.set(RI->getFrameRegister(*MF),
2497                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2498     AddAddress(VariableDie, DW_AT_location, Location);
2499
2500     return VariableDie;
2501   }
2502
2503   /// NewScopeVariable - Create a new scope variable.
2504   ///
2505   DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
2506     // Get the descriptor.
2507     DIVariable *VD = DV->getVariable();
2508
2509     // Translate tag to proper Dwarf tag.  The result variable is dropped for
2510     // now.
2511     unsigned Tag;
2512     switch (VD->getTag()) {
2513     case DW_TAG_return_variable:  return NULL;
2514     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
2515     case DW_TAG_auto_variable:    // fall thru
2516     default:                      Tag = DW_TAG_variable; break;
2517     }
2518
2519     // Define variable debug information entry.
2520     DIE *VariableDie = new DIE(Tag);
2521     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2522
2523     // Add source line info if available.
2524     AddSourceLine(VariableDie, VD);
2525
2526     // Add variable type.
2527     AddType(Unit, VariableDie, VD->getType());
2528
2529     // Add variable address.
2530     MachineLocation Location;
2531     Location.set(RI->getFrameRegister(*MF),
2532                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2533     AddAddress(VariableDie, DW_AT_location, Location);
2534
2535     return VariableDie;
2536   }
2537
2538   unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2539     CompileUnit *Unit = DW_CUs[V];
2540     assert (Unit && "Unable to find CompileUnit");
2541     unsigned ID = MMI->NextLabelID();
2542     Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2543     return ID;
2544   }
2545   
2546   unsigned getRecordSourceLineCount() {
2547     return Lines.size();
2548   }
2549                             
2550   unsigned RecordSource(const std::string &Directory,
2551                         const std::string &File) {
2552     unsigned DID = Directories.insert(Directory);
2553     return SrcFiles.insert(SrcFileInfo(DID,File));
2554   }
2555
2556   /// RecordRegionStart - Indicate the start of a region.
2557   ///
2558   unsigned RecordRegionStart(GlobalVariable *V) {
2559     DbgScope *Scope = getOrCreateScope(V);
2560     unsigned ID = MMI->NextLabelID();
2561     if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2562     return ID;
2563   }
2564
2565   /// RecordRegionEnd - Indicate the end of a region.
2566   ///
2567   unsigned RecordRegionEnd(GlobalVariable *V) {
2568     DbgScope *Scope = getOrCreateScope(V);
2569     unsigned ID = MMI->NextLabelID();
2570     Scope->setEndLabelID(ID);
2571     return ID;
2572   }
2573
2574   /// RecordVariable - Indicate the declaration of  a local variable.
2575   ///
2576   void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
2577     DbgScope *Scope = getOrCreateScope(GV);
2578     DIVariable *VD = new DIVariable(GV);
2579     DbgVariable *DV = new DbgVariable(VD, FrameIndex);
2580     Scope->AddVariable(DV);
2581   }
2582
2583   /// getOrCreateScope - Returns the scope associated with the given descriptor.
2584   ///
2585   DbgScope *getOrCreateScope(GlobalVariable *V) {
2586     DbgScope *&Slot = DbgScopeMap[V];
2587     if (!Slot) {
2588       // FIXME - breaks down when the context is an inlined function.
2589       DIDescriptor ParentDesc;
2590       DIDescriptor *DB = new DIBlock(V);
2591       if (DIBlock *Block = dyn_cast<DIBlock>(DB)) {
2592         ParentDesc = Block->getContext();
2593       }
2594       DbgScope *Parent = ParentDesc.isNull() ? 
2595         NULL : getOrCreateScope(ParentDesc.getGV());
2596       Slot = new DbgScope(Parent, DB);
2597       if (Parent) {
2598         Parent->AddScope(Slot);
2599       } else if (RootDbgScope) {
2600         // FIXME - Add inlined function scopes to the root so we can delete
2601         // them later.  Long term, handle inlined functions properly.
2602         RootDbgScope->AddScope(Slot);
2603       } else {
2604         // First function is top level function.
2605         RootDbgScope = Slot;
2606       }
2607     }
2608     return Slot;
2609   }
2610
2611   /// ConstructDbgScope - Construct the components of a scope.
2612   ///
2613   void ConstructDbgScope(DbgScope *ParentScope,
2614                          unsigned ParentStartID, unsigned ParentEndID,
2615                          DIE *ParentDie, CompileUnit *Unit) {
2616     // Add variables to scope.
2617     SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2618     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2619       DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2620       if (VariableDie) ParentDie->AddChild(VariableDie);
2621     }
2622
2623     // Add nested scopes.
2624     SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2625     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2626       // Define the Scope debug information entry.
2627       DbgScope *Scope = Scopes[j];
2628       // FIXME - Ignore inlined functions for the time being.
2629       if (!Scope->getParent()) continue;
2630
2631       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2632       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2633
2634       // Ignore empty scopes.
2635       if (StartID == EndID && StartID != 0) continue;
2636       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2637
2638       if (StartID == ParentStartID && EndID == ParentEndID) {
2639         // Just add stuff to the parent scope.
2640         ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2641       } else {
2642         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2643
2644         // Add the scope bounds.
2645         if (StartID) {
2646           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2647                              DWLabel("label", StartID));
2648         } else {
2649           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2650                              DWLabel("func_begin", SubprogramCount));
2651         }
2652         if (EndID) {
2653           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2654                              DWLabel("label", EndID));
2655         } else {
2656           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2657                              DWLabel("func_end", SubprogramCount));
2658         }
2659
2660         // Add the scope contents.
2661         ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2662         ParentDie->AddChild(ScopeDie);
2663       }
2664     }
2665   }
2666
2667   /// ConstructRootDbgScope - Construct the scope for the subprogram.
2668   ///
2669   void ConstructRootDbgScope(DbgScope *RootScope) {
2670     // Exit if there is no root scope.
2671     if (!RootScope) return;
2672
2673     // Get the subprogram debug information entry.
2674     DISubprogram *SPD = cast<DISubprogram>(RootScope->getDesc());
2675
2676     // Get the compile unit context.
2677     CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2678
2679     // Get the subprogram die.
2680     DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2681     assert(SPDie && "Missing subprogram descriptor");
2682
2683     // Add the function bounds.
2684     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2685                     DWLabel("func_begin", SubprogramCount));
2686     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2687                     DWLabel("func_end", SubprogramCount));
2688     MachineLocation Location(RI->getFrameRegister(*MF));
2689     AddAddress(SPDie, DW_AT_frame_base, Location);
2690
2691     ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2692   }
2693
2694   /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2695   ///
2696   void ConstructDefaultDbgScope(MachineFunction *MF) {
2697     // Find the correct subprogram descriptor.
2698     std::string SPName = "llvm.dbg.subprograms";
2699     std::vector<GlobalVariable*> Result;
2700     getGlobalVariablesUsing(*M, SPName, Result);
2701     for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2702            E = Result.end(); I != E; ++I) {
2703
2704       DISubprogram *SPD = new DISubprogram(*I);
2705
2706       if (SPD->getName() == MF->getFunction()->getName()) {
2707         // Get the compile unit context.
2708         CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2709
2710         // Get the subprogram die.
2711         DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2712         assert(SPDie && "Missing subprogram descriptor");
2713
2714         // Add the function bounds.
2715         AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2716                  DWLabel("func_begin", SubprogramCount));
2717         AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2718                  DWLabel("func_end", SubprogramCount));
2719
2720         MachineLocation Location(RI->getFrameRegister(*MF));
2721         AddAddress(SPDie, DW_AT_frame_base, Location);
2722         return;
2723       }
2724     }
2725 #if 0
2726     // FIXME: This is causing an abort because C++ mangled names are compared
2727     // with their unmangled counterparts. See PR2885. Don't do this assert.
2728     assert(0 && "Couldn't find DIE for machine function!");
2729 #endif
2730   }
2731
2732   /// ConstructScope - Construct the components of a scope.
2733   ///
2734   void ConstructScope(DebugScope *ParentScope,
2735                       unsigned ParentStartID, unsigned ParentEndID,
2736                       DIE *ParentDie, CompileUnit *Unit) {
2737     // Add variables to scope.
2738     std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2739     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2740       DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2741       if (VariableDie) ParentDie->AddChild(VariableDie);
2742     }
2743
2744     // Add nested scopes.
2745     std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2746     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2747       // Define the Scope debug information entry.
2748       DebugScope *Scope = Scopes[j];
2749       // FIXME - Ignore inlined functions for the time being.
2750       if (!Scope->getParent()) continue;
2751
2752       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2753       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2754
2755       // Ignore empty scopes.
2756       if (StartID == EndID && StartID != 0) continue;
2757       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2758
2759       if (StartID == ParentStartID && EndID == ParentEndID) {
2760         // Just add stuff to the parent scope.
2761         ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2762       } else {
2763         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2764
2765         // Add the scope bounds.
2766         if (StartID) {
2767           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2768                              DWLabel("label", StartID));
2769         } else {
2770           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2771                              DWLabel("func_begin", SubprogramCount));
2772         }
2773         if (EndID) {
2774           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2775                              DWLabel("label", EndID));
2776         } else {
2777           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2778                              DWLabel("func_end", SubprogramCount));
2779         }
2780
2781         // Add the scope contents.
2782         ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2783         ParentDie->AddChild(ScopeDie);
2784       }
2785     }
2786   }
2787
2788   /// ConstructRootScope - Construct the scope for the subprogram.
2789   ///
2790   void ConstructRootScope(DebugScope *RootScope) {
2791     // Exit if there is no root scope.
2792     if (!RootScope) return;
2793
2794     // Get the subprogram debug information entry.
2795     SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2796
2797     // Get the compile unit context.
2798     CompileUnit *Unit = GetBaseCompileUnit();
2799
2800     // Get the subprogram die.
2801     DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2802     assert(SPDie && "Missing subprogram descriptor");
2803
2804     // Add the function bounds.
2805     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2806                     DWLabel("func_begin", SubprogramCount));
2807     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2808                     DWLabel("func_end", SubprogramCount));
2809     MachineLocation Location(RI->getFrameRegister(*MF));
2810     AddAddress(SPDie, DW_AT_frame_base, Location);
2811
2812     ConstructScope(RootScope, 0, 0, SPDie, Unit);
2813   }
2814
2815   /// ConstructDefaultScope - Construct a default scope for the subprogram.
2816   ///
2817   void ConstructDefaultScope(MachineFunction *MF) {
2818     // Find the correct subprogram descriptor.
2819     std::vector<SubprogramDesc *> Subprograms;
2820     MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2821
2822     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2823       SubprogramDesc *SPD = Subprograms[i];
2824
2825       if (SPD->getName() == MF->getFunction()->getName()) {
2826         // Get the compile unit context.
2827         CompileUnit *Unit = GetBaseCompileUnit();
2828
2829         // Get the subprogram die.
2830         DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2831         assert(SPDie && "Missing subprogram descriptor");
2832
2833         // Add the function bounds.
2834         AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2835                  DWLabel("func_begin", SubprogramCount));
2836         AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2837                  DWLabel("func_end", SubprogramCount));
2838
2839         MachineLocation Location(RI->getFrameRegister(*MF));
2840         AddAddress(SPDie, DW_AT_frame_base, Location);
2841         return;
2842       }
2843     }
2844 #if 0
2845     // FIXME: This is causing an abort because C++ mangled names are compared
2846     // with their unmangled counterparts. See PR2885. Don't do this assert.
2847     assert(0 && "Couldn't find DIE for machine function!");
2848 #endif
2849   }
2850
2851   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
2852   /// tools to recognize the object file contains Dwarf information.
2853   void EmitInitial() {
2854     // Check to see if we already emitted intial headers.
2855     if (didInitial) return;
2856     didInitial = true;
2857
2858     // Dwarf sections base addresses.
2859     if (TAI->doesDwarfRequireFrameSection()) {
2860       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2861       EmitLabel("section_debug_frame", 0);
2862     }
2863     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2864     EmitLabel("section_info", 0);
2865     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2866     EmitLabel("section_abbrev", 0);
2867     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2868     EmitLabel("section_aranges", 0);
2869     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2870     EmitLabel("section_macinfo", 0);
2871     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2872     EmitLabel("section_line", 0);
2873     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2874     EmitLabel("section_loc", 0);
2875     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2876     EmitLabel("section_pubnames", 0);
2877     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2878     EmitLabel("section_str", 0);
2879     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2880     EmitLabel("section_ranges", 0);
2881
2882     Asm->SwitchToSection(TAI->getTextSection());
2883     EmitLabel("text_begin", 0);
2884     Asm->SwitchToSection(TAI->getDataSection());
2885     EmitLabel("data_begin", 0);
2886   }
2887
2888   /// EmitDIE - Recusively Emits a debug information entry.
2889   ///
2890   void EmitDIE(DIE *Die) {
2891     // Get the abbreviation for this DIE.
2892     unsigned AbbrevNumber = Die->getAbbrevNumber();
2893     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2894
2895     Asm->EOL();
2896
2897     // Emit the code (index) for the abbreviation.
2898     Asm->EmitULEB128Bytes(AbbrevNumber);
2899
2900     if (VerboseAsm)
2901       Asm->EOL(std::string("Abbrev [" +
2902                            utostr(AbbrevNumber) +
2903                            "] 0x" + utohexstr(Die->getOffset()) +
2904                            ":0x" + utohexstr(Die->getSize()) + " " +
2905                            TagString(Abbrev->getTag())));
2906     else
2907       Asm->EOL();
2908
2909     SmallVector<DIEValue*, 32> &Values = Die->getValues();
2910     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2911
2912     // Emit the DIE attribute values.
2913     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2914       unsigned Attr = AbbrevData[i].getAttribute();
2915       unsigned Form = AbbrevData[i].getForm();
2916       assert(Form && "Too many attributes for DIE (check abbreviation)");
2917
2918       switch (Attr) {
2919       case DW_AT_sibling: {
2920         Asm->EmitInt32(Die->SiblingOffset());
2921         break;
2922       }
2923       default: {
2924         // Emit an attribute using the defined form.
2925         Values[i]->EmitValue(*this, Form);
2926         break;
2927       }
2928       }
2929
2930       Asm->EOL(AttributeString(Attr));
2931     }
2932
2933     // Emit the DIE children if any.
2934     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2935       const std::vector<DIE *> &Children = Die->getChildren();
2936
2937       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2938         EmitDIE(Children[j]);
2939       }
2940
2941       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2942     }
2943   }
2944
2945   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2946   ///
2947   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2948     // Get the children.
2949     const std::vector<DIE *> &Children = Die->getChildren();
2950
2951     // If not last sibling and has children then add sibling offset attribute.
2952     if (!Last && !Children.empty()) Die->AddSiblingOffset();
2953
2954     // Record the abbreviation.
2955     AssignAbbrevNumber(Die->getAbbrev());
2956
2957     // Get the abbreviation for this DIE.
2958     unsigned AbbrevNumber = Die->getAbbrevNumber();
2959     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2960
2961     // Set DIE offset
2962     Die->setOffset(Offset);
2963
2964     // Start the size with the size of abbreviation code.
2965     Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2966
2967     const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2968     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2969
2970     // Size the DIE attribute values.
2971     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2972       // Size attribute value.
2973       Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2974     }
2975
2976     // Size the DIE children if any.
2977     if (!Children.empty()) {
2978       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2979              "Children flag not set");
2980
2981       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2982         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2983       }
2984
2985       // End of children marker.
2986       Offset += sizeof(int8_t);
2987     }
2988
2989     Die->setSize(Offset - Die->getOffset());
2990     return Offset;
2991   }
2992
2993   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2994   ///
2995   void SizeAndOffsets() {
2996     // Process base compile unit.
2997     CompileUnit *Unit = GetBaseCompileUnit();
2998     // Compute size of compile unit header
2999     unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
3000                       sizeof(int16_t) + // DWARF version number
3001                       sizeof(int32_t) + // Offset Into Abbrev. Section
3002                       sizeof(int8_t);   // Pointer Size (in bytes)
3003     SizeAndOffsetDie(Unit->getDie(), Offset, true);
3004   }
3005
3006   /// EmitDebugInfo - Emit the debug info section.
3007   ///
3008   void EmitDebugInfo() {
3009     // Start debug info section.
3010     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
3011
3012     CompileUnit *Unit = GetBaseCompileUnit();
3013     DIE *Die = Unit->getDie();
3014     // Emit the compile units header.
3015     EmitLabel("info_begin", Unit->getID());
3016     // Emit size of content not including length itself
3017     unsigned ContentSize = Die->getSize() +
3018                            sizeof(int16_t) + // DWARF version number
3019                            sizeof(int32_t) + // Offset Into Abbrev. Section
3020                            sizeof(int8_t) +  // Pointer Size (in bytes)
3021                            sizeof(int32_t);  // FIXME - extra pad for gdb bug.
3022
3023     Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
3024     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3025     EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
3026     Asm->EOL("Offset Into Abbrev. Section");
3027     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
3028
3029     EmitDIE(Die);
3030     // FIXME - extra padding for gdb bug.
3031     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3032     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3033     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3034     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3035     EmitLabel("info_end", Unit->getID());
3036
3037     Asm->EOL();
3038   }
3039
3040   /// EmitAbbreviations - Emit the abbreviation section.
3041   ///
3042   void EmitAbbreviations() const {
3043     // Check to see if it is worth the effort.
3044     if (!Abbreviations.empty()) {
3045       // Start the debug abbrev section.
3046       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
3047
3048       EmitLabel("abbrev_begin", 0);
3049
3050       // For each abbrevation.
3051       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3052         // Get abbreviation data
3053         const DIEAbbrev *Abbrev = Abbreviations[i];
3054
3055         // Emit the abbrevations code (base 1 index.)
3056         Asm->EmitULEB128Bytes(Abbrev->getNumber());
3057         Asm->EOL("Abbreviation Code");
3058
3059         // Emit the abbreviations data.
3060         Abbrev->Emit(*this);
3061
3062         Asm->EOL();
3063       }
3064
3065       // Mark end of abbreviations.
3066       Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
3067
3068       EmitLabel("abbrev_end", 0);
3069
3070       Asm->EOL();
3071     }
3072   }
3073
3074   /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
3075   /// the line matrix.
3076   ///
3077   void EmitEndOfLineMatrix(unsigned SectionEnd) {
3078     // Define last address of section.
3079     Asm->EmitInt8(0); Asm->EOL("Extended Op");
3080     Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3081     Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3082     EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
3083
3084     // Mark end of matrix.
3085     Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
3086     Asm->EmitULEB128Bytes(1); Asm->EOL();
3087     Asm->EmitInt8(1); Asm->EOL();
3088   }
3089
3090   /// EmitDebugLines - Emit source line information.
3091   ///
3092   void EmitDebugLines() {
3093     // If the target is using .loc/.file, the assembler will be emitting the
3094     // .debug_line table automatically.
3095     if (TAI->hasDotLocAndDotFile())
3096       return;
3097
3098     // Minimum line delta, thus ranging from -10..(255-10).
3099     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
3100     // Maximum line delta, thus ranging from -10..(255-10).
3101     const int MaxLineDelta = 255 + MinLineDelta;
3102
3103     // Start the dwarf line section.
3104     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
3105
3106     // Construct the section header.
3107
3108     EmitDifference("line_end", 0, "line_begin", 0, true);
3109     Asm->EOL("Length of Source Line Info");
3110     EmitLabel("line_begin", 0);
3111
3112     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3113
3114     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
3115     Asm->EOL("Prolog Length");
3116     EmitLabel("line_prolog_begin", 0);
3117
3118     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
3119
3120     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
3121
3122     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
3123
3124     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
3125
3126     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
3127
3128     // Line number standard opcode encodings argument count
3129     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
3130     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
3131     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
3132     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
3133     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
3134     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
3135     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
3136     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
3137     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
3138
3139     const UniqueVector<std::string> &Directories = MMI->getDirectories();
3140     const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3141
3142     // Emit directories.
3143     for (unsigned DirectoryID = 1, NDID = Directories.size();
3144                   DirectoryID <= NDID; ++DirectoryID) {
3145       Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
3146     }
3147     Asm->EmitInt8(0); Asm->EOL("End of directories");
3148
3149     // Emit files.
3150     for (unsigned SourceID = 1, NSID = SourceFiles.size();
3151                  SourceID <= NSID; ++SourceID) {
3152       const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3153       Asm->EmitString(SourceFile.getName());
3154       Asm->EOL("Source");
3155       Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
3156       Asm->EOL("Directory #");
3157       Asm->EmitULEB128Bytes(0);
3158       Asm->EOL("Mod date");
3159       Asm->EmitULEB128Bytes(0);
3160       Asm->EOL("File size");
3161     }
3162     Asm->EmitInt8(0); Asm->EOL("End of files");
3163
3164     EmitLabel("line_prolog_end", 0);
3165
3166     // A sequence for each text section.
3167     unsigned SecSrcLinesSize = SectionSourceLines.size();
3168
3169     for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3170       // Isolate current sections line info.
3171       const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
3172
3173       if (VerboseAsm) {
3174         const Section* S = SectionMap[j + 1];
3175         Asm->EOL(std::string("Section ") + S->getName());
3176       } else
3177         Asm->EOL();
3178
3179       // Dwarf assumes we start with first line of first source file.
3180       unsigned Source = 1;
3181       unsigned Line = 1;
3182
3183       // Construct rows of the address, source, line, column matrix.
3184       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3185         const SourceLineInfo &LineInfo = LineInfos[i];
3186         unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
3187         if (!LabelID) continue;
3188
3189         unsigned SourceID = LineInfo.getSourceID();
3190         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3191         unsigned DirectoryID = SourceFile.getDirectoryID();
3192         if (VerboseAsm)
3193           Asm->EOL(Directories[DirectoryID]
3194                    + SourceFile.getName()
3195                    + ":"
3196                    + utostr_32(LineInfo.getLine()));
3197         else
3198           Asm->EOL();
3199
3200         // Define the line address.
3201         Asm->EmitInt8(0); Asm->EOL("Extended Op");
3202         Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3203         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3204         EmitReference("label",  LabelID); Asm->EOL("Location label");
3205
3206         // If change of source, then switch to the new source.
3207         if (Source != LineInfo.getSourceID()) {
3208           Source = LineInfo.getSourceID();
3209           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
3210           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
3211         }
3212
3213         // If change of line.
3214         if (Line != LineInfo.getLine()) {
3215           // Determine offset.
3216           int Offset = LineInfo.getLine() - Line;
3217           int Delta = Offset - MinLineDelta;
3218
3219           // Update line.
3220           Line = LineInfo.getLine();
3221
3222           // If delta is small enough and in range...
3223           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3224             // ... then use fast opcode.
3225             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
3226           } else {
3227             // ... otherwise use long hand.
3228             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
3229             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
3230             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3231           }
3232         } else {
3233           // Copy the previous row (different address or source)
3234           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3235         }
3236       }
3237
3238       EmitEndOfLineMatrix(j + 1);
3239     }
3240
3241     if (SecSrcLinesSize == 0)
3242       // Because we're emitting a debug_line section, we still need a line
3243       // table. The linker and friends expect it to exist. If there's nothing to
3244       // put into it, emit an empty table.
3245       EmitEndOfLineMatrix(1);
3246
3247     EmitLabel("line_end", 0);
3248
3249     Asm->EOL();
3250   }
3251
3252   /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
3253   ///
3254   void EmitCommonDebugFrame() {
3255     if (!TAI->doesDwarfRequireFrameSection())
3256       return;
3257
3258     int stackGrowth =
3259         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3260           TargetFrameInfo::StackGrowsUp ?
3261         TD->getPointerSize() : -TD->getPointerSize();
3262
3263     // Start the dwarf frame section.
3264     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3265
3266     EmitLabel("debug_frame_common", 0);
3267     EmitDifference("debug_frame_common_end", 0,
3268                    "debug_frame_common_begin", 0, true);
3269     Asm->EOL("Length of Common Information Entry");
3270
3271     EmitLabel("debug_frame_common_begin", 0);
3272     Asm->EmitInt32((int)DW_CIE_ID);
3273     Asm->EOL("CIE Identifier Tag");
3274     Asm->EmitInt8(DW_CIE_VERSION);
3275     Asm->EOL("CIE Version");
3276     Asm->EmitString("");
3277     Asm->EOL("CIE Augmentation");
3278     Asm->EmitULEB128Bytes(1);
3279     Asm->EOL("CIE Code Alignment Factor");
3280     Asm->EmitSLEB128Bytes(stackGrowth);
3281     Asm->EOL("CIE Data Alignment Factor");
3282     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3283     Asm->EOL("CIE RA Column");
3284
3285     std::vector<MachineMove> Moves;
3286     RI->getInitialFrameState(Moves);
3287
3288     EmitFrameMoves(NULL, 0, Moves, false);
3289
3290     Asm->EmitAlignment(2, 0, 0, false);
3291     EmitLabel("debug_frame_common_end", 0);
3292
3293     Asm->EOL();
3294   }
3295
3296   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
3297   /// section.
3298   void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3299     if (!TAI->doesDwarfRequireFrameSection())
3300       return;
3301
3302     // Start the dwarf frame section.
3303     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3304
3305     EmitDifference("debug_frame_end", DebugFrameInfo.Number,
3306                    "debug_frame_begin", DebugFrameInfo.Number, true);
3307     Asm->EOL("Length of Frame Information Entry");
3308
3309     EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
3310
3311     EmitSectionOffset("debug_frame_common", "section_debug_frame",
3312                       0, 0, true, false);
3313     Asm->EOL("FDE CIE offset");
3314
3315     EmitReference("func_begin", DebugFrameInfo.Number);
3316     Asm->EOL("FDE initial location");
3317     EmitDifference("func_end", DebugFrameInfo.Number,
3318                    "func_begin", DebugFrameInfo.Number);
3319     Asm->EOL("FDE address range");
3320
3321     EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
3322
3323     Asm->EmitAlignment(2, 0, 0, false);
3324     EmitLabel("debug_frame_end", DebugFrameInfo.Number);
3325
3326     Asm->EOL();
3327   }
3328
3329   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
3330   ///
3331   void EmitDebugPubNames() {
3332     // Start the dwarf pubnames section.
3333     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
3334
3335     CompileUnit *Unit = GetBaseCompileUnit();
3336
3337     EmitDifference("pubnames_end", Unit->getID(),
3338                    "pubnames_begin", Unit->getID(), true);
3339     Asm->EOL("Length of Public Names Info");
3340
3341     EmitLabel("pubnames_begin", Unit->getID());
3342
3343     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
3344
3345     EmitSectionOffset("info_begin", "section_info",
3346                       Unit->getID(), 0, true, false);
3347     Asm->EOL("Offset of Compilation Unit Info");
3348
3349     EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
3350     Asm->EOL("Compilation Unit Length");
3351
3352     std::map<std::string, DIE *> &Globals = Unit->getGlobals();
3353
3354     for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
3355                                                 GE = Globals.end();
3356          GI != GE; ++GI) {
3357       const std::string &Name = GI->first;
3358       DIE * Entity = GI->second;
3359
3360       Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
3361       Asm->EmitString(Name); Asm->EOL("External Name");
3362     }
3363
3364     Asm->EmitInt32(0); Asm->EOL("End Mark");
3365     EmitLabel("pubnames_end", Unit->getID());
3366
3367     Asm->EOL();
3368   }
3369
3370   /// EmitDebugStr - Emit visible names into a debug str section.
3371   ///
3372   void EmitDebugStr() {
3373     // Check to see if it is worth the effort.
3374     if (!StringPool.empty()) {
3375       // Start the dwarf str section.
3376       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
3377
3378       // For each of strings in the string pool.
3379       for (unsigned StringID = 1, N = StringPool.size();
3380            StringID <= N; ++StringID) {
3381         // Emit a label for reference from debug information entries.
3382         EmitLabel("string", StringID);
3383         // Emit the string itself.
3384         const std::string &String = StringPool[StringID];
3385         Asm->EmitString(String); Asm->EOL();
3386       }
3387
3388       Asm->EOL();
3389     }
3390   }
3391
3392   /// EmitDebugLoc - Emit visible names into a debug loc section.
3393   ///
3394   void EmitDebugLoc() {
3395     // Start the dwarf loc section.
3396     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
3397
3398     Asm->EOL();
3399   }
3400
3401   /// EmitDebugARanges - Emit visible names into a debug aranges section.
3402   ///
3403   void EmitDebugARanges() {
3404     // Start the dwarf aranges section.
3405     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
3406
3407     // FIXME - Mock up
3408 #if 0
3409     CompileUnit *Unit = GetBaseCompileUnit();
3410
3411     // Don't include size of length
3412     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
3413
3414     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
3415
3416     EmitReference("info_begin", Unit->getID());
3417     Asm->EOL("Offset of Compilation Unit Info");
3418
3419     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
3420
3421     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
3422
3423     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
3424     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
3425
3426     // Range 1
3427     EmitReference("text_begin", 0); Asm->EOL("Address");
3428     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
3429
3430     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
3431     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
3432 #endif
3433
3434     Asm->EOL();
3435   }
3436
3437   /// EmitDebugRanges - Emit visible names into a debug ranges section.
3438   ///
3439   void EmitDebugRanges() {
3440     // Start the dwarf ranges section.
3441     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
3442
3443     Asm->EOL();
3444   }
3445
3446   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
3447   ///
3448   void EmitDebugMacInfo() {
3449     // Start the dwarf macinfo section.
3450     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
3451
3452     Asm->EOL();
3453   }
3454
3455   /// ConstructCompileUnits - Create a compile unit DIEs.
3456   void ConstructCompileUnits() {
3457     std::string CUName = "llvm.dbg.compile_units";
3458     std::vector<GlobalVariable*> Result;
3459     getGlobalVariablesUsing(*M, CUName, Result);
3460     for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3461            RE = Result.end(); RI != RE; ++RI) {
3462       DICompileUnit *DIUnit = new DICompileUnit(*RI);
3463       unsigned ID = RecordSource(DIUnit->getDirectory(),
3464                                  DIUnit->getFilename());
3465
3466       DIE *Die = new DIE(DW_TAG_compile_unit);
3467       AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
3468                        DWLabel("section_line", 0), DWLabel("section_line", 0),
3469                        false);
3470       AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit->getProducer());
3471       AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit->getLanguage());
3472       AddString(Die, DW_AT_name, DW_FORM_string, DIUnit->getFilename());
3473       if (!DIUnit->getDirectory().empty())
3474         AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit->getDirectory());
3475
3476       CompileUnit *Unit = new CompileUnit(ID, Die);
3477       DW_CUs[DIUnit->getGV()] = Unit;
3478     }
3479   }
3480
3481   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
3482   /// header file.
3483   void ConstructCompileUnitDIEs() {
3484     const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
3485
3486     for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
3487       unsigned ID = MMI->RecordSource(CUW[i]);
3488       CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
3489       CompileUnits.push_back(Unit);
3490     }
3491   }
3492
3493   /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally 
3494   /// visible global variables.
3495   void ConstructGlobalVariableDIEs() {
3496     std::string GVName = "llvm.dbg.global_variables";
3497     std::vector<GlobalVariable*> Result;
3498     getGlobalVariablesUsing(*M, GVName, Result);
3499     for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
3500            GVE = Result.end(); GVI != GVE; ++GVI) {
3501       DIGlobalVariable *DI_GV = new DIGlobalVariable(*GVI);
3502       CompileUnit *DW_Unit = FindCompileUnit(DI_GV->getCompileUnit());
3503
3504       // Check for pre-existence.
3505       DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV->getGV());
3506       if (Slot) continue;
3507
3508       DIE *VariableDie = new DIE(DW_TAG_variable);
3509       AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV->getName());
3510       const std::string &LinkageName  = DI_GV->getLinkageName();
3511       if (!LinkageName.empty())
3512         AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3513                   LinkageName);
3514       AddType(DW_Unit, VariableDie, DI_GV->getType());
3515
3516       if (!DI_GV->isLocalToUnit())
3517         AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);              
3518
3519       // Add source line info, if available.
3520       AddSourceLine(VariableDie, DI_GV);
3521
3522       // Add address.
3523       DIEBlock *Block = new DIEBlock();
3524       AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
3525       AddObjectLabel(Block, 0, DW_FORM_udata,
3526                      Asm->getGlobalLinkName(DI_GV->getGV()));
3527       AddBlock(VariableDie, DW_AT_location, 0, Block);
3528
3529       //Add to map.
3530       Slot = VariableDie;
3531
3532       //Add to context owner.
3533       DW_Unit->getDie()->AddChild(VariableDie);
3534
3535       //Expose as global. FIXME - need to check external flag.
3536       DW_Unit->AddGlobal(DI_GV->getName(), VariableDie);
3537     }
3538   }
3539
3540   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
3541   /// global variables.
3542   void ConstructGlobalDIEs() {
3543     std::vector<GlobalVariableDesc *> GlobalVariables;
3544     MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
3545
3546     for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
3547       GlobalVariableDesc *GVD = GlobalVariables[i];
3548       NewGlobalVariable(GVD);
3549     }
3550   }
3551
3552   /// ConstructSubprograms - Create DIEs for each of the externally visible
3553   /// subprograms.
3554   void ConstructSubprograms() {
3555
3556     std::string SPName = "llvm.dbg.subprograms";
3557     std::vector<GlobalVariable*> Result;
3558     getGlobalVariablesUsing(*M, SPName, Result);
3559     for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3560            RE = Result.end(); RI != RE; ++RI) {
3561
3562       DISubprogram *SP = new DISubprogram(*RI);
3563       CompileUnit *Unit = FindCompileUnit(SP->getCompileUnit());
3564
3565       // Check for pre-existence.                                                         
3566       DIE *&Slot = Unit->getDieMapSlotFor(SP->getGV());
3567       if (Slot) continue;
3568
3569       DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
3570       AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP->getName());
3571       const std::string &LinkageName = SP->getLinkageName();
3572       if (!LinkageName.empty())
3573         AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3574                   LinkageName);
3575       DIType SPTy = SP->getType();
3576       AddType(Unit, SubprogramDie, SPTy);
3577       if (!SP->isLocalToUnit())
3578         AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
3579       AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
3580
3581       AddSourceLine(SubprogramDie, SP);
3582       //Add to map.
3583       Slot = SubprogramDie;
3584       //Add to context owner.
3585       Unit->getDie()->AddChild(SubprogramDie);
3586       //Expose as global.
3587       Unit->AddGlobal(SP->getName(), SubprogramDie);
3588     }
3589   }
3590
3591   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
3592   /// subprograms.
3593   void ConstructSubprogramDIEs() {
3594     std::vector<SubprogramDesc *> Subprograms;
3595     MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
3596
3597     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
3598       SubprogramDesc *SPD = Subprograms[i];
3599       NewSubprogram(SPD);
3600     }
3601   }
3602
3603 public:
3604   //===--------------------------------------------------------------------===//
3605   // Main entry points.
3606   //
3607   DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3608   : Dwarf(OS, A, T, "dbg")
3609   , CompileUnits()
3610   , AbbreviationsSet(InitAbbreviationsSetSize)
3611   , Abbreviations()
3612   , ValuesSet(InitValuesSetSize)
3613   , Values()
3614   , StringPool()
3615   , DescToUnitMap()
3616   , SectionMap()
3617   , SectionSourceLines()
3618   , didInitial(false)
3619   , shouldEmit(false)
3620   , RootDbgScope(NULL)
3621   {
3622   }
3623   virtual ~DwarfDebug() {
3624     for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
3625       delete CompileUnits[i];
3626     for (unsigned j = 0, M = Values.size(); j < M; ++j)
3627       delete Values[j];
3628   }
3629
3630   /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3631   /// This is inovked by the target AsmPrinter.
3632   void SetDebugInfo() {
3633     // FIXME - Check if the module has debug info or not.
3634       // Create all the compile unit DIEs.
3635       ConstructCompileUnits();
3636
3637       // Create DIEs for each of the externally visible global variables.
3638       ConstructGlobalVariableDIEs();
3639
3640       // Create DIEs for each of the externally visible subprograms.
3641       ConstructSubprograms();
3642
3643       // Prime section data.
3644       SectionMap.insert(TAI->getTextSection());
3645
3646       // Print out .file directives to specify files for .loc directives. These
3647       // are printed out early so that they precede any .loc directives.
3648       if (TAI->hasDotLocAndDotFile()) {
3649         for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
3650           sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
3651           bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
3652           assert(AppendOk && "Could not append filename to directory!");
3653           AppendOk = false;
3654           Asm->EmitFile(i, FullPath.toString());
3655           Asm->EOL();
3656         }
3657       }
3658
3659       // Emit initial sections
3660       EmitInitial();
3661   }
3662
3663   /// SetModuleInfo - Set machine module information when it's known that pass
3664   /// manager has created it.  Set by the target AsmPrinter.
3665   void SetModuleInfo(MachineModuleInfo *mmi) {
3666     // Make sure initial declarations are made.
3667     if (!MMI && mmi->hasDebugInfo()) {
3668       MMI = mmi;
3669       shouldEmit = true;
3670
3671       // Create all the compile unit DIEs.
3672       ConstructCompileUnitDIEs();
3673
3674       // Create DIEs for each of the externally visible global variables.
3675       ConstructGlobalDIEs();
3676
3677       // Create DIEs for each of the externally visible subprograms.
3678       ConstructSubprogramDIEs();
3679
3680       // Prime section data.
3681       SectionMap.insert(TAI->getTextSection());
3682
3683       // Print out .file directives to specify files for .loc directives. These
3684       // are printed out early so that they precede any .loc directives.
3685       if (TAI->hasDotLocAndDotFile()) {
3686         const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3687         const UniqueVector<std::string> &Directories = MMI->getDirectories();
3688         for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
3689           sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
3690           bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
3691           assert(AppendOk && "Could not append filename to directory!");
3692           AppendOk = false;
3693           Asm->EmitFile(i, FullPath.toString());
3694           Asm->EOL();
3695         }
3696       }
3697
3698       // Emit initial sections
3699       EmitInitial();
3700     }
3701   }
3702
3703   /// BeginModule - Emit all Dwarf sections that should come prior to the
3704   /// content.
3705   void BeginModule(Module *M) {
3706     this->M = M;
3707   }
3708
3709   /// EndModule - Emit all Dwarf sections that should come after the content.
3710   ///
3711   void EndModule() {
3712     if (!ShouldEmitDwarf()) return;
3713
3714     // Standard sections final addresses.
3715     Asm->SwitchToSection(TAI->getTextSection());
3716     EmitLabel("text_end", 0);
3717     Asm->SwitchToSection(TAI->getDataSection());
3718     EmitLabel("data_end", 0);
3719
3720     // End text sections.
3721     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3722       Asm->SwitchToSection(SectionMap[i]);
3723       EmitLabel("section_end", i);
3724     }
3725
3726     // Emit common frame information.
3727     EmitCommonDebugFrame();
3728
3729     // Emit function debug frame information
3730     for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3731            E = DebugFrames.end(); I != E; ++I)
3732       EmitFunctionDebugFrame(*I);
3733
3734     // Compute DIE offsets and sizes.
3735     SizeAndOffsets();
3736
3737     // Emit all the DIEs into a debug info section
3738     EmitDebugInfo();
3739
3740     // Corresponding abbreviations into a abbrev section.
3741     EmitAbbreviations();
3742
3743     // Emit source line correspondence into a debug line section.
3744     EmitDebugLines();
3745
3746     // Emit info into a debug pubnames section.
3747     EmitDebugPubNames();
3748
3749     // Emit info into a debug str section.
3750     EmitDebugStr();
3751
3752     // Emit info into a debug loc section.
3753     EmitDebugLoc();
3754
3755     // Emit info into a debug aranges section.
3756     EmitDebugARanges();
3757
3758     // Emit info into a debug ranges section.
3759     EmitDebugRanges();
3760
3761     // Emit info into a debug macinfo section.
3762     EmitDebugMacInfo();
3763   }
3764
3765   /// BeginFunction - Gather pre-function debug information.  Assumes being
3766   /// emitted immediately after the function entry point.
3767   void BeginFunction(MachineFunction *MF) {
3768     this->MF = MF;
3769
3770     if (!ShouldEmitDwarf()) return;
3771
3772     // Begin accumulating function debug information.
3773     MMI->BeginFunction(MF);
3774
3775     // Assumes in correct section after the entry point.
3776     EmitLabel("func_begin", ++SubprogramCount);
3777
3778     // Emit label for the implicitly defined dbg.stoppoint at the start of
3779     // the function.
3780     const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3781     if (!LineInfos.empty()) {
3782       const SourceLineInfo &LineInfo = LineInfos[0];
3783       Asm->printLabel(LineInfo.getLabelID());
3784     }
3785   }
3786
3787   /// EndFunction - Gather and emit post-function debug information.
3788   ///
3789   void EndFunction(MachineFunction *MF) {
3790     if (!ShouldEmitDwarf()) return;
3791
3792     // Define end label for subprogram.
3793     EmitLabel("func_end", SubprogramCount);
3794
3795     // Get function line info.
3796     const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3797
3798     if (!LineInfos.empty()) {
3799       // Get section line info.
3800       unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3801       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3802       std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3803       // Append the function info to section info.
3804       SectionLineInfos.insert(SectionLineInfos.end(),
3805                               LineInfos.begin(), LineInfos.end());
3806     }
3807
3808     // Construct scopes for subprogram.
3809     if (MMI->getRootScope())
3810       ConstructRootScope(MMI->getRootScope());
3811     else
3812       // FIXME: This is wrong. We are essentially getting past a problem with
3813       // debug information not being able to handle unreachable blocks that have
3814       // debug information in them. In particular, those unreachable blocks that
3815       // have "region end" info in them. That situation results in the "root
3816       // scope" not being created. If that's the case, then emit a "default"
3817       // scope, i.e., one that encompasses the whole function. This isn't
3818       // desirable. And a better way of handling this (and all of the debugging
3819       // information) needs to be explored.
3820       ConstructDefaultScope(MF);
3821
3822     DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3823                                                  MMI->getFrameMoves()));
3824   }
3825 };
3826
3827 //===----------------------------------------------------------------------===//
3828 /// DwarfException - Emits Dwarf exception handling directives.
3829 ///
3830 class DwarfException : public Dwarf  {
3831
3832 private:
3833   struct FunctionEHFrameInfo {
3834     std::string FnName;
3835     unsigned Number;
3836     unsigned PersonalityIndex;
3837     bool hasCalls;
3838     bool hasLandingPads;
3839     std::vector<MachineMove> Moves;
3840     const Function * function;
3841
3842     FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3843                         bool hC, bool hL,
3844                         const std::vector<MachineMove> &M,
3845                         const Function *f):
3846       FnName(FN), Number(Num), PersonalityIndex(P),
3847       hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3848   };
3849
3850   std::vector<FunctionEHFrameInfo> EHFrames;
3851
3852   /// shouldEmitTable - Per-function flag to indicate if EH tables should
3853   /// be emitted.
3854   bool shouldEmitTable;
3855
3856   /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3857   /// should be emitted.
3858   bool shouldEmitMoves;
3859
3860   /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3861   /// should be emitted.
3862   bool shouldEmitTableModule;
3863
3864   /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3865   /// should be emitted.
3866   bool shouldEmitMovesModule;
3867
3868   /// EmitCommonEHFrame - Emit the common eh unwind frame.
3869   ///
3870   void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3871     // Size and sign of stack growth.
3872     int stackGrowth =
3873         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3874           TargetFrameInfo::StackGrowsUp ?
3875         TD->getPointerSize() : -TD->getPointerSize();
3876
3877     // Begin eh frame section.
3878     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3879
3880     if (!TAI->doesRequireNonLocalEHFrameLabel())
3881       O << TAI->getEHGlobalPrefix();
3882     O << "EH_frame" << Index << ":\n";
3883     EmitLabel("section_eh_frame", Index);
3884
3885     // Define base labels.
3886     EmitLabel("eh_frame_common", Index);
3887
3888     // Define the eh frame length.
3889     EmitDifference("eh_frame_common_end", Index,
3890                    "eh_frame_common_begin", Index, true);
3891     Asm->EOL("Length of Common Information Entry");
3892
3893     // EH frame header.
3894     EmitLabel("eh_frame_common_begin", Index);
3895     Asm->EmitInt32((int)0);
3896     Asm->EOL("CIE Identifier Tag");
3897     Asm->EmitInt8(DW_CIE_VERSION);
3898     Asm->EOL("CIE Version");
3899
3900     // The personality presence indicates that language specific information
3901     // will show up in the eh frame.
3902     Asm->EmitString(Personality ? "zPLR" : "zR");
3903     Asm->EOL("CIE Augmentation");
3904
3905     // Round out reader.
3906     Asm->EmitULEB128Bytes(1);
3907     Asm->EOL("CIE Code Alignment Factor");
3908     Asm->EmitSLEB128Bytes(stackGrowth);
3909     Asm->EOL("CIE Data Alignment Factor");
3910     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3911     Asm->EOL("CIE Return Address Column");
3912
3913     // If there is a personality, we need to indicate the functions location.
3914     if (Personality) {
3915       Asm->EmitULEB128Bytes(7);
3916       Asm->EOL("Augmentation Size");
3917
3918       if (TAI->getNeedsIndirectEncoding()) {
3919         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3920         Asm->EOL("Personality (pcrel sdata4 indirect)");
3921       } else {
3922         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3923         Asm->EOL("Personality (pcrel sdata4)");
3924       }
3925
3926       PrintRelDirective(true);
3927       O << TAI->getPersonalityPrefix();
3928       Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3929       O << TAI->getPersonalitySuffix();
3930       if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3931         O << "-" << TAI->getPCSymbol();
3932       Asm->EOL("Personality");
3933
3934       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3935       Asm->EOL("LSDA Encoding (pcrel sdata4)");
3936
3937       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3938       Asm->EOL("FDE Encoding (pcrel sdata4)");
3939    } else {
3940       Asm->EmitULEB128Bytes(1);
3941       Asm->EOL("Augmentation Size");
3942
3943       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3944       Asm->EOL("FDE Encoding (pcrel sdata4)");
3945     }
3946
3947     // Indicate locations of general callee saved registers in frame.
3948     std::vector<MachineMove> Moves;
3949     RI->getInitialFrameState(Moves);
3950     EmitFrameMoves(NULL, 0, Moves, true);
3951
3952     // On Darwin the linker honors the alignment of eh_frame, which means it
3953     // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise
3954     // you get holes which confuse readers of eh_frame.
3955     Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3956                        0, 0, false);
3957     EmitLabel("eh_frame_common_end", Index);
3958
3959     Asm->EOL();
3960   }
3961
3962   /// EmitEHFrame - Emit function exception frame information.
3963   ///
3964   void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3965     Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3966
3967     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3968
3969     // Externally visible entry into the functions eh frame info.
3970     // If the corresponding function is static, this should not be
3971     // externally visible.
3972     if (linkage != Function::InternalLinkage) {
3973       if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3974         O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3975     }
3976
3977     // If corresponding function is weak definition, this should be too.
3978     if ((linkage == Function::WeakLinkage ||
3979          linkage == Function::LinkOnceLinkage) &&
3980         TAI->getWeakDefDirective())
3981       O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3982
3983     // If there are no calls then you can't unwind.  This may mean we can
3984     // omit the EH Frame, but some environments do not handle weak absolute
3985     // symbols.
3986     // If UnwindTablesMandatory is set we cannot do this optimization; the
3987     // unwind info is to be available for non-EH uses.
3988     if (!EHFrameInfo.hasCalls &&
3989         !UnwindTablesMandatory &&
3990         ((linkage != Function::WeakLinkage &&
3991           linkage != Function::LinkOnceLinkage) ||
3992          !TAI->getWeakDefDirective() ||
3993          TAI->getSupportsWeakOmittedEHFrame()))
3994     {
3995       O << EHFrameInfo.FnName << " = 0\n";
3996       // This name has no connection to the function, so it might get
3997       // dead-stripped when the function is not, erroneously.  Prohibit
3998       // dead-stripping unconditionally.
3999       if (const char *UsedDirective = TAI->getUsedDirective())
4000         O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4001     } else {
4002       O << EHFrameInfo.FnName << ":\n";
4003
4004       // EH frame header.
4005       EmitDifference("eh_frame_end", EHFrameInfo.Number,
4006                      "eh_frame_begin", EHFrameInfo.Number, true);
4007       Asm->EOL("Length of Frame Information Entry");
4008
4009       EmitLabel("eh_frame_begin", EHFrameInfo.Number);
4010
4011       if (TAI->doesRequireNonLocalEHFrameLabel()) {
4012         PrintRelDirective(true, true);
4013         PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
4014
4015         if (!TAI->isAbsoluteEHSectionOffsets())
4016           O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
4017       } else {
4018         EmitSectionOffset("eh_frame_begin", "eh_frame_common",
4019                           EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
4020                           true, true, false);
4021       }
4022
4023       Asm->EOL("FDE CIE offset");
4024
4025       EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
4026       Asm->EOL("FDE initial location");
4027       EmitDifference("eh_func_end", EHFrameInfo.Number,
4028                      "eh_func_begin", EHFrameInfo.Number, true);
4029       Asm->EOL("FDE address range");
4030
4031       // If there is a personality and landing pads then point to the language
4032       // specific data area in the exception table.
4033       if (EHFrameInfo.PersonalityIndex) {
4034         Asm->EmitULEB128Bytes(4);
4035         Asm->EOL("Augmentation size");
4036
4037         if (EHFrameInfo.hasLandingPads)
4038           EmitReference("exception", EHFrameInfo.Number, true, true);
4039         else
4040           Asm->EmitInt32((int)0);
4041         Asm->EOL("Language Specific Data Area");
4042       } else {
4043         Asm->EmitULEB128Bytes(0);
4044         Asm->EOL("Augmentation size");
4045       }
4046
4047       // Indicate locations of function specific  callee saved registers in
4048       // frame.
4049       EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
4050
4051       // On Darwin the linker honors the alignment of eh_frame, which means it
4052       // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise
4053       // you get holes which confuse readers of eh_frame.
4054       Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
4055                          0, 0, false);
4056       EmitLabel("eh_frame_end", EHFrameInfo.Number);
4057
4058       // If the function is marked used, this table should be also.  We cannot
4059       // make the mark unconditional in this case, since retaining the table
4060       // also retains the function in this case, and there is code around
4061       // that depends on unused functions (calling undefined externals) being
4062       // dead-stripped to link correctly.  Yes, there really is.
4063       if (MMI->getUsedFunctions().count(EHFrameInfo.function))
4064         if (const char *UsedDirective = TAI->getUsedDirective())
4065           O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4066     }
4067   }
4068
4069   /// EmitExceptionTable - Emit landing pads and actions.
4070   ///
4071   /// The general organization of the table is complex, but the basic concepts
4072   /// are easy.  First there is a header which describes the location and
4073   /// organization of the three components that follow.
4074   ///  1. The landing pad site information describes the range of code covered
4075   ///     by the try.  In our case it's an accumulation of the ranges covered
4076   ///     by the invokes in the try.  There is also a reference to the landing
4077   ///     pad that handles the exception once processed.  Finally an index into
4078   ///     the actions table.
4079   ///  2. The action table, in our case, is composed of pairs of type ids
4080   ///     and next action offset.  Starting with the action index from the
4081   ///     landing pad site, each type Id is checked for a match to the current
4082   ///     exception.  If it matches then the exception and type id are passed
4083   ///     on to the landing pad.  Otherwise the next action is looked up.  This
4084   ///     chain is terminated with a next action of zero.  If no type id is
4085   ///     found the the frame is unwound and handling continues.
4086   ///  3. Type id table contains references to all the C++ typeinfo for all
4087   ///     catches in the function.  This tables is reversed indexed base 1.
4088
4089   /// SharedTypeIds - How many leading type ids two landing pads have in common.
4090   static unsigned SharedTypeIds(const LandingPadInfo *L,
4091                                 const LandingPadInfo *R) {
4092     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4093     unsigned LSize = LIds.size(), RSize = RIds.size();
4094     unsigned MinSize = LSize < RSize ? LSize : RSize;
4095     unsigned Count = 0;
4096
4097     for (; Count != MinSize; ++Count)
4098       if (LIds[Count] != RIds[Count])
4099         return Count;
4100
4101     return Count;
4102   }
4103
4104   /// PadLT - Order landing pads lexicographically by type id.
4105   static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
4106     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4107     unsigned LSize = LIds.size(), RSize = RIds.size();
4108     unsigned MinSize = LSize < RSize ? LSize : RSize;
4109
4110     for (unsigned i = 0; i != MinSize; ++i)
4111       if (LIds[i] != RIds[i])
4112         return LIds[i] < RIds[i];
4113
4114     return LSize < RSize;
4115   }
4116
4117   struct KeyInfo {
4118     static inline unsigned getEmptyKey() { return -1U; }
4119     static inline unsigned getTombstoneKey() { return -2U; }
4120     static unsigned getHashValue(const unsigned &Key) { return Key; }
4121     static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
4122     static bool isPod() { return true; }
4123   };
4124
4125   /// ActionEntry - Structure describing an entry in the actions table.
4126   struct ActionEntry {
4127     int ValueForTypeID; // The value to write - may not be equal to the type id.
4128     int NextAction;
4129     struct ActionEntry *Previous;
4130   };
4131
4132   /// PadRange - Structure holding a try-range and the associated landing pad.
4133   struct PadRange {
4134     // The index of the landing pad.
4135     unsigned PadIndex;
4136     // The index of the begin and end labels in the landing pad's label lists.
4137     unsigned RangeIndex;
4138   };
4139
4140   typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
4141
4142   /// CallSiteEntry - Structure describing an entry in the call-site table.
4143   struct CallSiteEntry {
4144     // The 'try-range' is BeginLabel .. EndLabel.
4145     unsigned BeginLabel; // zero indicates the start of the function.
4146     unsigned EndLabel;   // zero indicates the end of the function.
4147     // The landing pad starts at PadLabel.
4148     unsigned PadLabel;   // zero indicates that there is no landing pad.
4149     unsigned Action;
4150   };
4151
4152   void EmitExceptionTable() {
4153     const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
4154     const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
4155     const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
4156     if (PadInfos.empty()) return;
4157
4158     // Sort the landing pads in order of their type ids.  This is used to fold
4159     // duplicate actions.
4160     SmallVector<const LandingPadInfo *, 64> LandingPads;
4161     LandingPads.reserve(PadInfos.size());
4162     for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
4163       LandingPads.push_back(&PadInfos[i]);
4164     std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
4165
4166     // Negative type ids index into FilterIds, positive type ids index into
4167     // TypeInfos.  The value written for a positive type id is just the type
4168     // id itself.  For a negative type id, however, the value written is the
4169     // (negative) byte offset of the corresponding FilterIds entry.  The byte
4170     // offset is usually equal to the type id, because the FilterIds entries
4171     // are written using a variable width encoding which outputs one byte per
4172     // entry as long as the value written is not too large, but can differ.
4173     // This kind of complication does not occur for positive type ids because
4174     // type infos are output using a fixed width encoding.
4175     // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
4176     SmallVector<int, 16> FilterOffsets;
4177     FilterOffsets.reserve(FilterIds.size());
4178     int Offset = -1;
4179     for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
4180         E = FilterIds.end(); I != E; ++I) {
4181       FilterOffsets.push_back(Offset);
4182       Offset -= TargetAsmInfo::getULEB128Size(*I);
4183     }
4184
4185     // Compute the actions table and gather the first action index for each
4186     // landing pad site.
4187     SmallVector<ActionEntry, 32> Actions;
4188     SmallVector<unsigned, 64> FirstActions;
4189     FirstActions.reserve(LandingPads.size());
4190
4191     int FirstAction = 0;
4192     unsigned SizeActions = 0;
4193     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4194       const LandingPadInfo *LP = LandingPads[i];
4195       const std::vector<int> &TypeIds = LP->TypeIds;
4196       const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
4197       unsigned SizeSiteActions = 0;
4198
4199       if (NumShared < TypeIds.size()) {
4200         unsigned SizeAction = 0;
4201         ActionEntry *PrevAction = 0;
4202
4203         if (NumShared) {
4204           const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
4205           assert(Actions.size());
4206           PrevAction = &Actions.back();
4207           SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
4208             TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4209           for (unsigned j = NumShared; j != SizePrevIds; ++j) {
4210             SizeAction -=
4211               TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4212             SizeAction += -PrevAction->NextAction;
4213             PrevAction = PrevAction->Previous;
4214           }
4215         }
4216
4217         // Compute the actions.
4218         for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
4219           int TypeID = TypeIds[I];
4220           assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
4221           int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
4222           unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
4223
4224           int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
4225           SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
4226           SizeSiteActions += SizeAction;
4227
4228           ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
4229           Actions.push_back(Action);
4230
4231           PrevAction = &Actions.back();
4232         }
4233
4234         // Record the first action of the landing pad site.
4235         FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
4236       } // else identical - re-use previous FirstAction
4237
4238       FirstActions.push_back(FirstAction);
4239
4240       // Compute this sites contribution to size.
4241       SizeActions += SizeSiteActions;
4242     }
4243
4244     // Compute the call-site table.  The entry for an invoke has a try-range
4245     // containing the call, a non-zero landing pad and an appropriate action.
4246     // The entry for an ordinary call has a try-range containing the call and
4247     // zero for the landing pad and the action.  Calls marked 'nounwind' have
4248     // no entry and must not be contained in the try-range of any entry - they
4249     // form gaps in the table.  Entries must be ordered by try-range address.
4250     SmallVector<CallSiteEntry, 64> CallSites;
4251
4252     RangeMapType PadMap;
4253     // Invokes and nounwind calls have entries in PadMap (due to being bracketed
4254     // by try-range labels when lowered).  Ordinary calls do not, so appropriate
4255     // try-ranges for them need be deduced.
4256     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4257       const LandingPadInfo *LandingPad = LandingPads[i];
4258       for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
4259         unsigned BeginLabel = LandingPad->BeginLabels[j];
4260         assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
4261         PadRange P = { i, j };
4262         PadMap[BeginLabel] = P;
4263       }
4264     }
4265
4266     // The end label of the previous invoke or nounwind try-range.
4267     unsigned LastLabel = 0;
4268
4269     // Whether there is a potentially throwing instruction (currently this means
4270     // an ordinary call) between the end of the previous try-range and now.
4271     bool SawPotentiallyThrowing = false;
4272
4273     // Whether the last callsite entry was for an invoke.
4274     bool PreviousIsInvoke = false;
4275
4276     // Visit all instructions in order of address.
4277     for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
4278          I != E; ++I) {
4279       for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
4280            MI != E; ++MI) {
4281         if (!MI->isLabel()) {
4282           SawPotentiallyThrowing |= MI->getDesc().isCall();
4283           continue;
4284         }
4285
4286         unsigned BeginLabel = MI->getOperand(0).getImm();
4287         assert(BeginLabel && "Invalid label!");
4288
4289         // End of the previous try-range?
4290         if (BeginLabel == LastLabel)
4291           SawPotentiallyThrowing = false;
4292
4293         // Beginning of a new try-range?
4294         RangeMapType::iterator L = PadMap.find(BeginLabel);
4295         if (L == PadMap.end())
4296           // Nope, it was just some random label.
4297           continue;
4298
4299         PadRange P = L->second;
4300         const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
4301
4302         assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
4303                "Inconsistent landing pad map!");
4304
4305         // If some instruction between the previous try-range and this one may
4306         // throw, create a call-site entry with no landing pad for the region
4307         // between the try-ranges.
4308         if (SawPotentiallyThrowing) {
4309           CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
4310           CallSites.push_back(Site);
4311           PreviousIsInvoke = false;
4312         }
4313
4314         LastLabel = LandingPad->EndLabels[P.RangeIndex];
4315         assert(BeginLabel && LastLabel && "Invalid landing pad!");
4316
4317         if (LandingPad->LandingPadLabel) {
4318           // This try-range is for an invoke.
4319           CallSiteEntry Site = {BeginLabel, LastLabel,
4320             LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
4321
4322           // Try to merge with the previous call-site.
4323           if (PreviousIsInvoke) {
4324             CallSiteEntry &Prev = CallSites.back();
4325             if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
4326               // Extend the range of the previous entry.
4327               Prev.EndLabel = Site.EndLabel;
4328               continue;
4329             }
4330           }
4331
4332           // Otherwise, create a new call-site.
4333           CallSites.push_back(Site);
4334           PreviousIsInvoke = true;
4335         } else {
4336           // Create a gap.
4337           PreviousIsInvoke = false;
4338         }
4339       }
4340     }
4341     // If some instruction between the previous try-range and the end of the
4342     // function may throw, create a call-site entry with no landing pad for the
4343     // region following the try-range.
4344     if (SawPotentiallyThrowing) {
4345       CallSiteEntry Site = {LastLabel, 0, 0, 0};
4346       CallSites.push_back(Site);
4347     }
4348
4349     // Final tallies.
4350
4351     // Call sites.
4352     const unsigned SiteStartSize  = sizeof(int32_t); // DW_EH_PE_udata4
4353     const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
4354     const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
4355     unsigned SizeSites = CallSites.size() * (SiteStartSize +
4356                                              SiteLengthSize +
4357                                              LandingPadSize);
4358     for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
4359       SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
4360
4361     // Type infos.
4362     const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
4363     unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
4364
4365     unsigned TypeOffset = sizeof(int8_t) + // Call site format
4366            TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
4367                           SizeSites + SizeActions + SizeTypes;
4368
4369     unsigned TotalSize = sizeof(int8_t) + // LPStart format
4370                          sizeof(int8_t) + // TType format
4371            TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
4372                          TypeOffset;
4373
4374     unsigned SizeAlign = (4 - TotalSize) & 3;
4375
4376     // Begin the exception table.
4377     Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
4378     Asm->EmitAlignment(2, 0, 0, false);
4379     O << "GCC_except_table" << SubprogramCount << ":\n";
4380     for (unsigned i = 0; i != SizeAlign; ++i) {
4381       Asm->EmitInt8(0);
4382       Asm->EOL("Padding");
4383     }
4384     EmitLabel("exception", SubprogramCount);
4385
4386     // Emit the header.
4387     Asm->EmitInt8(DW_EH_PE_omit);
4388     Asm->EOL("LPStart format (DW_EH_PE_omit)");
4389     Asm->EmitInt8(DW_EH_PE_absptr);
4390     Asm->EOL("TType format (DW_EH_PE_absptr)");
4391     Asm->EmitULEB128Bytes(TypeOffset);
4392     Asm->EOL("TType base offset");
4393     Asm->EmitInt8(DW_EH_PE_udata4);
4394     Asm->EOL("Call site format (DW_EH_PE_udata4)");
4395     Asm->EmitULEB128Bytes(SizeSites);
4396     Asm->EOL("Call-site table length");
4397
4398     // Emit the landing pad site information.
4399     for (unsigned i = 0; i < CallSites.size(); ++i) {
4400       CallSiteEntry &S = CallSites[i];
4401       const char *BeginTag;
4402       unsigned BeginNumber;
4403
4404       if (!S.BeginLabel) {
4405         BeginTag = "eh_func_begin";
4406         BeginNumber = SubprogramCount;
4407       } else {
4408         BeginTag = "label";
4409         BeginNumber = S.BeginLabel;
4410       }
4411
4412       EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4413                         true, true);
4414       Asm->EOL("Region start");
4415
4416       if (!S.EndLabel) {
4417         EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4418                        true);
4419       } else {
4420         EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4421       }
4422       Asm->EOL("Region length");
4423
4424       if (!S.PadLabel)
4425         Asm->EmitInt32(0);
4426       else
4427         EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4428                           true, true);
4429       Asm->EOL("Landing pad");
4430
4431       Asm->EmitULEB128Bytes(S.Action);
4432       Asm->EOL("Action");
4433     }
4434
4435     // Emit the actions.
4436     for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4437       ActionEntry &Action = Actions[I];
4438
4439       Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4440       Asm->EOL("TypeInfo index");
4441       Asm->EmitSLEB128Bytes(Action.NextAction);
4442       Asm->EOL("Next action");
4443     }
4444
4445     // Emit the type ids.
4446     for (unsigned M = TypeInfos.size(); M; --M) {
4447       GlobalVariable *GV = TypeInfos[M - 1];
4448
4449       PrintRelDirective();
4450
4451       if (GV)
4452         O << Asm->getGlobalLinkName(GV);
4453       else
4454         O << "0";
4455
4456       Asm->EOL("TypeInfo");
4457     }
4458
4459     // Emit the filter typeids.
4460     for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4461       unsigned TypeID = FilterIds[j];
4462       Asm->EmitULEB128Bytes(TypeID);
4463       Asm->EOL("Filter TypeInfo index");
4464     }
4465
4466     Asm->EmitAlignment(2, 0, 0, false);
4467   }
4468
4469 public:
4470   //===--------------------------------------------------------------------===//
4471   // Main entry points.
4472   //
4473   DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4474   : Dwarf(OS, A, T, "eh")
4475   , shouldEmitTable(false)
4476   , shouldEmitMoves(false)
4477   , shouldEmitTableModule(false)
4478   , shouldEmitMovesModule(false)
4479   {}
4480
4481   virtual ~DwarfException() {}
4482
4483   /// SetModuleInfo - Set machine module information when it's known that pass
4484   /// manager has created it.  Set by the target AsmPrinter.
4485   void SetModuleInfo(MachineModuleInfo *mmi) {
4486     MMI = mmi;
4487   }
4488
4489   /// BeginModule - Emit all exception information that should come prior to the
4490   /// content.
4491   void BeginModule(Module *M) {
4492     this->M = M;
4493   }
4494
4495   /// EndModule - Emit all exception information that should come after the
4496   /// content.
4497   void EndModule() {
4498     if (shouldEmitMovesModule || shouldEmitTableModule) {
4499       const std::vector<Function *> Personalities = MMI->getPersonalities();
4500       for (unsigned i =0; i < Personalities.size(); ++i)
4501         EmitCommonEHFrame(Personalities[i], i);
4502
4503       for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4504              E = EHFrames.end(); I != E; ++I)
4505         EmitEHFrame(*I);
4506     }
4507   }
4508
4509   /// BeginFunction - Gather pre-function exception information.  Assumes being
4510   /// emitted immediately after the function entry point.
4511   void BeginFunction(MachineFunction *MF) {
4512     this->MF = MF;
4513     shouldEmitTable = shouldEmitMoves = false;
4514     if (MMI && TAI->doesSupportExceptionHandling()) {
4515
4516       // Map all labels and get rid of any dead landing pads.
4517       MMI->TidyLandingPads();
4518       // If any landing pads survive, we need an EH table.
4519       if (MMI->getLandingPads().size())
4520         shouldEmitTable = true;
4521
4522       // See if we need frame move info.
4523       if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4524         shouldEmitMoves = true;
4525
4526       if (shouldEmitMoves || shouldEmitTable)
4527         // Assumes in correct section after the entry point.
4528         EmitLabel("eh_func_begin", ++SubprogramCount);
4529     }
4530     shouldEmitTableModule |= shouldEmitTable;
4531     shouldEmitMovesModule |= shouldEmitMoves;
4532   }
4533
4534   /// EndFunction - Gather and emit post-function exception information.
4535   ///
4536   void EndFunction() {
4537     if (shouldEmitMoves || shouldEmitTable) {
4538       EmitLabel("eh_func_end", SubprogramCount);
4539       EmitExceptionTable();
4540
4541       // Save EH frame information
4542       EHFrames.
4543         push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4544                                     SubprogramCount,
4545                                     MMI->getPersonalityIndex(),
4546                                     MF->getFrameInfo()->hasCalls(),
4547                                     !MMI->getLandingPads().empty(),
4548                                     MMI->getFrameMoves(),
4549                                     MF->getFunction()));
4550       }
4551   }
4552 };
4553
4554 } // End of namespace llvm
4555
4556 //===----------------------------------------------------------------------===//
4557
4558 /// Emit - Print the abbreviation using the specified Dwarf writer.
4559 ///
4560 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4561   // Emit its Dwarf tag type.
4562   DD.getAsm()->EmitULEB128Bytes(Tag);
4563   DD.getAsm()->EOL(TagString(Tag));
4564
4565   // Emit whether it has children DIEs.
4566   DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4567   DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4568
4569   // For each attribute description.
4570   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4571     const DIEAbbrevData &AttrData = Data[i];
4572
4573     // Emit attribute type.
4574     DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4575     DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4576
4577     // Emit form type.
4578     DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4579     DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4580   }
4581
4582   // Mark end of abbreviation.
4583   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4584   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4585 }
4586
4587 #ifndef NDEBUG
4588 void DIEAbbrev::print(std::ostream &O) {
4589   O << "Abbreviation @"
4590     << std::hex << (intptr_t)this << std::dec
4591     << "  "
4592     << TagString(Tag)
4593     << " "
4594     << ChildrenString(ChildrenFlag)
4595     << "\n";
4596
4597   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4598     O << "  "
4599       << AttributeString(Data[i].getAttribute())
4600       << "  "
4601       << FormEncodingString(Data[i].getForm())
4602       << "\n";
4603   }
4604 }
4605 void DIEAbbrev::dump() { print(cerr); }
4606 #endif
4607
4608 //===----------------------------------------------------------------------===//
4609
4610 #ifndef NDEBUG
4611 void DIEValue::dump() {
4612   print(cerr);
4613 }
4614 #endif
4615
4616 //===----------------------------------------------------------------------===//
4617
4618 /// EmitValue - Emit integer of appropriate size.
4619 ///
4620 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4621   switch (Form) {
4622   case DW_FORM_flag:  // Fall thru
4623   case DW_FORM_ref1:  // Fall thru
4624   case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer);         break;
4625   case DW_FORM_ref2:  // Fall thru
4626   case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer);        break;
4627   case DW_FORM_ref4:  // Fall thru
4628   case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer);        break;
4629   case DW_FORM_ref8:  // Fall thru
4630   case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer);        break;
4631   case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4632   case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4633   default: assert(0 && "DIE Value form not supported yet");   break;
4634   }
4635 }
4636
4637 /// SizeOf - Determine size of integer value in bytes.
4638 ///
4639 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4640   switch (Form) {
4641   case DW_FORM_flag:  // Fall thru
4642   case DW_FORM_ref1:  // Fall thru
4643   case DW_FORM_data1: return sizeof(int8_t);
4644   case DW_FORM_ref2:  // Fall thru
4645   case DW_FORM_data2: return sizeof(int16_t);
4646   case DW_FORM_ref4:  // Fall thru
4647   case DW_FORM_data4: return sizeof(int32_t);
4648   case DW_FORM_ref8:  // Fall thru
4649   case DW_FORM_data8: return sizeof(int64_t);
4650   case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4651   case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4652   default: assert(0 && "DIE Value form not supported yet"); break;
4653   }
4654   return 0;
4655 }
4656
4657 //===----------------------------------------------------------------------===//
4658
4659 /// EmitValue - Emit string value.
4660 ///
4661 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4662   DD.getAsm()->EmitString(String);
4663 }
4664
4665 //===----------------------------------------------------------------------===//
4666
4667 /// EmitValue - Emit label value.
4668 ///
4669 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4670   bool IsSmall = Form == DW_FORM_data4;
4671   DD.EmitReference(Label, false, IsSmall);
4672 }
4673
4674 /// SizeOf - Determine size of label value in bytes.
4675 ///
4676 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4677   if (Form == DW_FORM_data4) return 4;
4678   return DD.getTargetData()->getPointerSize();
4679 }
4680
4681 //===----------------------------------------------------------------------===//
4682
4683 /// EmitValue - Emit label value.
4684 ///
4685 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4686   bool IsSmall = Form == DW_FORM_data4;
4687   DD.EmitReference(Label, false, IsSmall);
4688 }
4689
4690 /// SizeOf - Determine size of label value in bytes.
4691 ///
4692 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4693   if (Form == DW_FORM_data4) return 4;
4694   return DD.getTargetData()->getPointerSize();
4695 }
4696
4697 //===----------------------------------------------------------------------===//
4698
4699 /// EmitValue - Emit delta value.
4700 ///
4701 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4702   bool IsSmall = Form == DW_FORM_data4;
4703   DD.EmitSectionOffset(Label.Tag, Section.Tag,
4704                        Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4705 }
4706
4707 /// SizeOf - Determine size of delta value in bytes.
4708 ///
4709 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4710   if (Form == DW_FORM_data4) return 4;
4711   return DD.getTargetData()->getPointerSize();
4712 }
4713
4714 //===----------------------------------------------------------------------===//
4715
4716 /// EmitValue - Emit delta value.
4717 ///
4718 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4719   bool IsSmall = Form == DW_FORM_data4;
4720   DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4721 }
4722
4723 /// SizeOf - Determine size of delta value in bytes.
4724 ///
4725 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4726   if (Form == DW_FORM_data4) return 4;
4727   return DD.getTargetData()->getPointerSize();
4728 }
4729
4730 //===----------------------------------------------------------------------===//
4731
4732 /// EmitValue - Emit debug information entry offset.
4733 ///
4734 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4735   DD.getAsm()->EmitInt32(Entry->getOffset());
4736 }
4737
4738 //===----------------------------------------------------------------------===//
4739
4740 /// ComputeSize - calculate the size of the block.
4741 ///
4742 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4743   if (!Size) {
4744     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4745
4746     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4747       Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4748     }
4749   }
4750   return Size;
4751 }
4752
4753 /// EmitValue - Emit block data.
4754 ///
4755 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4756   switch (Form) {
4757   case DW_FORM_block1: DD.getAsm()->EmitInt8(Size);         break;
4758   case DW_FORM_block2: DD.getAsm()->EmitInt16(Size);        break;
4759   case DW_FORM_block4: DD.getAsm()->EmitInt32(Size);        break;
4760   case DW_FORM_block:  DD.getAsm()->EmitULEB128Bytes(Size); break;
4761   default: assert(0 && "Improper form for block");          break;
4762   }
4763
4764   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4765
4766   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4767     DD.getAsm()->EOL();
4768     Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4769   }
4770 }
4771
4772 /// SizeOf - Determine size of block data in bytes.
4773 ///
4774 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4775   switch (Form) {
4776   case DW_FORM_block1: return Size + sizeof(int8_t);
4777   case DW_FORM_block2: return Size + sizeof(int16_t);
4778   case DW_FORM_block4: return Size + sizeof(int32_t);
4779   case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4780   default: assert(0 && "Improper form for block"); break;
4781   }
4782   return 0;
4783 }
4784
4785 //===----------------------------------------------------------------------===//
4786 /// DIE Implementation
4787
4788 DIE::~DIE() {
4789   for (unsigned i = 0, N = Children.size(); i < N; ++i)
4790     delete Children[i];
4791 }
4792
4793 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4794 ///
4795 void DIE::AddSiblingOffset() {
4796   DIEInteger *DI = new DIEInteger(0);
4797   Values.insert(Values.begin(), DI);
4798   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4799 }
4800
4801 /// Profile - Used to gather unique data for the value folding set.
4802 ///
4803 void DIE::Profile(FoldingSetNodeID &ID) {
4804   Abbrev.Profile(ID);
4805
4806   for (unsigned i = 0, N = Children.size(); i < N; ++i)
4807     ID.AddPointer(Children[i]);
4808
4809   for (unsigned j = 0, M = Values.size(); j < M; ++j)
4810     ID.AddPointer(Values[j]);
4811 }
4812
4813 #ifndef NDEBUG
4814 void DIE::print(std::ostream &O, unsigned IncIndent) {
4815   static unsigned IndentCount = 0;
4816   IndentCount += IncIndent;
4817   const std::string Indent(IndentCount, ' ');
4818   bool isBlock = Abbrev.getTag() == 0;
4819
4820   if (!isBlock) {
4821     O << Indent
4822       << "Die: "
4823       << "0x" << std::hex << (intptr_t)this << std::dec
4824       << ", Offset: " << Offset
4825       << ", Size: " << Size
4826       << "\n";
4827
4828     O << Indent
4829       << TagString(Abbrev.getTag())
4830       << " "
4831       << ChildrenString(Abbrev.getChildrenFlag());
4832   } else {
4833     O << "Size: " << Size;
4834   }
4835   O << "\n";
4836
4837   const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4838
4839   IndentCount += 2;
4840   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4841     O << Indent;
4842
4843     if (!isBlock)
4844       O << AttributeString(Data[i].getAttribute());
4845     else
4846       O << "Blk[" << i << "]";
4847
4848     O <<  "  "
4849       << FormEncodingString(Data[i].getForm())
4850       << " ";
4851     Values[i]->print(O);
4852     O << "\n";
4853   }
4854   IndentCount -= 2;
4855
4856   for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4857     Children[j]->print(O, 4);
4858   }
4859
4860   if (!isBlock) O << "\n";
4861   IndentCount -= IncIndent;
4862 }
4863
4864 void DIE::dump() {
4865   print(cerr);
4866 }
4867 #endif
4868
4869 //===----------------------------------------------------------------------===//
4870 /// DwarfWriter Implementation
4871 ///
4872
4873 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4874 }
4875
4876 DwarfWriter::~DwarfWriter() {
4877   delete DE;
4878   delete DD;
4879 }
4880
4881 /// BeginModule - Emit all Dwarf sections that should come prior to the
4882 /// content.
4883 void DwarfWriter::BeginModule(Module *M,
4884                               MachineModuleInfo *MMI,
4885                               raw_ostream &OS, AsmPrinter *A,
4886                               const TargetAsmInfo *T) {
4887   DE = new DwarfException(OS, A, T);
4888   DD = new DwarfDebug(OS, A, T);
4889   DE->BeginModule(M);
4890   DD->BeginModule(M);
4891   DD->SetModuleInfo(MMI);
4892   DE->SetModuleInfo(MMI);
4893 }
4894
4895 /// EndModule - Emit all Dwarf sections that should come after the content.
4896 ///
4897 void DwarfWriter::EndModule() {
4898   DE->EndModule();
4899   DD->EndModule();
4900 }
4901
4902 /// BeginFunction - Gather pre-function debug information.  Assumes being
4903 /// emitted immediately after the function entry point.
4904 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4905   DE->BeginFunction(MF);
4906   DD->BeginFunction(MF);
4907 }
4908
4909 /// EndFunction - Gather and emit post-function debug information.
4910 ///
4911 void DwarfWriter::EndFunction(MachineFunction *MF) {
4912   DD->EndFunction(MF);
4913   DE->EndFunction();
4914
4915   if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4916     // Clear function debug information.
4917     MMI->EndFunction();
4918 }