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