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