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