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