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