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