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