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