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