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