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