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