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