LLVM API Documentation

DwarfWriter.cpp

Go to the documentation of this file.
00001 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by James M. Laskey and is distributed under the
00006 // University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains support for writing dwarf debug info into asm files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/DwarfWriter.h"
00015 
00016 #include "llvm/ADT/StringExtras.h"
00017 #include "llvm/Module.h"
00018 #include "llvm/Type.h"
00019 #include "llvm/CodeGen/AsmPrinter.h"
00020 #include "llvm/CodeGen/MachineDebugInfo.h"
00021 #include "llvm/CodeGen/MachineFrameInfo.h"
00022 #include "llvm/CodeGen/MachineLocation.h"
00023 #include "llvm/Support/Dwarf.h"
00024 #include "llvm/Support/CommandLine.h"
00025 #include "llvm/Support/Mangler.h"
00026 #include "llvm/Target/MRegisterInfo.h"
00027 #include "llvm/Target/TargetData.h"
00028 #include "llvm/Target/TargetMachine.h"
00029 #include "llvm/Target/TargetFrameInfo.h"
00030 
00031 #include <iostream>
00032 
00033 using namespace llvm;
00034 using namespace llvm::dwarf;
00035 
00036 static cl::opt<bool>
00037 DwarfVerbose("dwarf-verbose", cl::Hidden,
00038                                 cl::desc("Add comments to Dwarf directives."));
00039 
00040 namespace llvm {
00041 
00042 //===----------------------------------------------------------------------===//
00043 // Forward declarations.
00044 //
00045 class DIE;
00046 
00047 //===----------------------------------------------------------------------===//
00048 // CompileUnit - This dwarf writer support class manages information associate
00049 // with a source file.
00050 class CompileUnit {
00051 private:
00052   CompileUnitDesc *Desc;                // Compile unit debug descriptor.
00053   unsigned ID;                          // File ID for source.
00054   DIE *Die;                             // Compile unit debug information entry.
00055   std::map<std::string, DIE *> Globals; // A map of globally visible named
00056                                         // entities for this unit.
00057   std::map<DebugInfoDesc *, DIE *> DescToDieMap;
00058                                         // Tracks the mapping of unit level
00059                                         // debug informaton descriptors to debug
00060                                         // information entries.
00061 
00062 public:
00063   CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
00064   : Desc(CUD)
00065   , ID(I)
00066   , Die(D)
00067   , Globals()
00068   , DescToDieMap()
00069   {}
00070   
00071   ~CompileUnit();
00072   
00073   // Accessors.
00074   CompileUnitDesc *getDesc() const { return Desc; }
00075   unsigned getID()           const { return ID; }
00076   DIE* getDie()              const { return Die; }
00077   std::map<std::string, DIE *> &getGlobals() { return Globals; }
00078   
00079   /// hasContent - Return true if this compile unit has something to write out.
00080   ///
00081   bool hasContent() const;
00082   
00083   /// AddGlobal - Add a new global entity to the compile unit.
00084   ///
00085   void AddGlobal(const std::string &Name, DIE *Die);
00086   
00087   /// getDieMapSlotFor - Returns the debug information entry map slot for the
00088   /// specified debug descriptor.
00089   DIE *&getDieMapSlotFor(DebugInfoDesc *DD) {
00090     return DescToDieMap[DD];
00091   }
00092 };
00093 
00094 //===----------------------------------------------------------------------===//
00095 // DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
00096 // Dwarf abbreviation.
00097 class DIEAbbrevData {
00098 private:
00099   unsigned Attribute;                 // Dwarf attribute code.
00100   unsigned Form;                      // Dwarf form code.
00101   
00102 public:
00103   DIEAbbrevData(unsigned A, unsigned F)
00104   : Attribute(A)
00105   , Form(F)
00106   {}
00107   
00108   // Accessors.
00109   unsigned getAttribute() const { return Attribute; }
00110   unsigned getForm()      const { return Form; }
00111   
00112   /// operator== - Used by DIEAbbrev to locate entry.
00113   ///
00114   bool operator==(const DIEAbbrevData &DAD) const {
00115     return Attribute == DAD.Attribute && Form == DAD.Form;
00116   }
00117 
00118   /// operator!= - Used by DIEAbbrev to locate entry.
00119   ///
00120   bool operator!=(const DIEAbbrevData &DAD) const {
00121     return Attribute != DAD.Attribute || Form != DAD.Form;
00122   }
00123   
00124   /// operator< - Used by DIEAbbrev to locate entry.
00125   ///
00126   bool operator<(const DIEAbbrevData &DAD) const {
00127     return Attribute < DAD.Attribute ||
00128           (Attribute == DAD.Attribute && Form < DAD.Form);
00129   }
00130 };
00131 
00132 //===----------------------------------------------------------------------===//
00133 // DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
00134 // information object.
00135 class DIEAbbrev {
00136 private:
00137   unsigned Tag;                       // Dwarf tag code.
00138   unsigned ChildrenFlag;              // Dwarf children flag.
00139   std::vector<DIEAbbrevData> Data;    // Raw data bytes for abbreviation.
00140 
00141 public:
00142 
00143   DIEAbbrev(unsigned T, unsigned C)
00144   : Tag(T)
00145   , ChildrenFlag(C)
00146   , Data()
00147   {}
00148   ~DIEAbbrev() {}
00149   
00150   // Accessors.
00151   unsigned getTag()                           const { return Tag; }
00152   unsigned getChildrenFlag()                  const { return ChildrenFlag; }
00153   const std::vector<DIEAbbrevData> &getData() const { return Data; }
00154   void setChildrenFlag(unsigned CF)                 { ChildrenFlag = CF; }
00155 
00156   /// operator== - Used by UniqueVector to locate entry.
00157   ///
00158   bool operator==(const DIEAbbrev &DA) const;
00159 
00160   /// operator< - Used by UniqueVector to locate entry.
00161   ///
00162   bool operator<(const DIEAbbrev &DA) const;
00163 
00164   /// AddAttribute - Adds another set of attribute information to the
00165   /// abbreviation.
00166   void AddAttribute(unsigned Attribute, unsigned Form) {
00167     Data.push_back(DIEAbbrevData(Attribute, Form));
00168   }
00169   
00170   /// AddFirstAttribute - Adds a set of attribute information to the front
00171   /// of the abbreviation.
00172   void AddFirstAttribute(unsigned Attribute, unsigned Form) {
00173     Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
00174   }
00175   
00176   /// Emit - Print the abbreviation using the specified Dwarf writer.
00177   ///
00178   void Emit(const DwarfWriter &DW) const; 
00179       
00180 #ifndef NDEBUG
00181   void print(std::ostream &O);
00182   void dump();
00183 #endif
00184 };
00185 
00186 //===----------------------------------------------------------------------===//
00187 // DIEValue - A debug information entry value.
00188 //
00189 class DIEValue {
00190 public:
00191   enum {
00192     isInteger,
00193     isString,
00194     isLabel,
00195     isAsIsLabel,
00196     isDelta,
00197     isEntry,
00198     isBlock
00199   };
00200   
00201   unsigned Type;                      // Type of the value
00202   
00203   DIEValue(unsigned T) : Type(T) {}
00204   virtual ~DIEValue() {}
00205   
00206   // Implement isa/cast/dyncast.
00207   static bool classof(const DIEValue *) { return true; }
00208   
00209   /// EmitValue - Emit value via the Dwarf writer.
00210   ///
00211   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const = 0;
00212   
00213   /// SizeOf - Return the size of a value in bytes.
00214   ///
00215   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const = 0;
00216 };
00217 
00218 //===----------------------------------------------------------------------===//
00219 // DWInteger - An integer value DIE.
00220 // 
00221 class DIEInteger : public DIEValue {
00222 private:
00223   uint64_t Integer;
00224   
00225 public:
00226   DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
00227 
00228   // Implement isa/cast/dyncast.
00229   static bool classof(const DIEInteger *) { return true; }
00230   static bool classof(const DIEValue *I)  { return I->Type == isInteger; }
00231   
00232   /// BestForm - Choose the best form for integer.
00233   ///
00234   unsigned BestForm(bool IsSigned);
00235 
00236   /// EmitValue - Emit integer of appropriate size.
00237   ///
00238   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
00239   
00240   /// SizeOf - Determine size of integer value in bytes.
00241   ///
00242   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
00243 };
00244 
00245 //===----------------------------------------------------------------------===//
00246 // DIEString - A string value DIE.
00247 // 
00248 struct DIEString : public DIEValue {
00249   const std::string String;
00250   
00251   DIEString(const std::string &S) : DIEValue(isString), String(S) {}
00252 
00253   // Implement isa/cast/dyncast.
00254   static bool classof(const DIEString *) { return true; }
00255   static bool classof(const DIEValue *S) { return S->Type == isString; }
00256   
00257   /// EmitValue - Emit string value.
00258   ///
00259   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
00260   
00261   /// SizeOf - Determine size of string value in bytes.
00262   ///
00263   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
00264 };
00265 
00266 //===----------------------------------------------------------------------===//
00267 // DIEDwarfLabel - A Dwarf internal label expression DIE.
00268 //
00269 struct DIEDwarfLabel : public DIEValue {
00270   const DWLabel Label;
00271   
00272   DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
00273 
00274   // Implement isa/cast/dyncast.
00275   static bool classof(const DIEDwarfLabel *)  { return true; }
00276   static bool classof(const DIEValue *L) { return L->Type == isLabel; }
00277   
00278   /// EmitValue - Emit label value.
00279   ///
00280   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
00281   
00282   /// SizeOf - Determine size of label value in bytes.
00283   ///
00284   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
00285 };
00286 
00287 
00288 //===----------------------------------------------------------------------===//
00289 // DIEObjectLabel - A label to an object in code or data.
00290 //
00291 struct DIEObjectLabel : public DIEValue {
00292   const std::string Label;
00293   
00294   DIEObjectLabel(const std::string &L) : DIEValue(isAsIsLabel), Label(L) {}
00295 
00296   // Implement isa/cast/dyncast.
00297   static bool classof(const DIEObjectLabel *) { return true; }
00298   static bool classof(const DIEValue *L)    { return L->Type == isAsIsLabel; }
00299   
00300   /// EmitValue - Emit label value.
00301   ///
00302   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
00303   
00304   /// SizeOf - Determine size of label value in bytes.
00305   ///
00306   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
00307 };
00308 
00309 //===----------------------------------------------------------------------===//
00310 // DIEDelta - A simple label difference DIE.
00311 // 
00312 struct DIEDelta : public DIEValue {
00313   const DWLabel LabelHi;
00314   const DWLabel LabelLo;
00315   
00316   DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
00317   : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
00318 
00319   // Implement isa/cast/dyncast.
00320   static bool classof(const DIEDelta *)  { return true; }
00321   static bool classof(const DIEValue *D) { return D->Type == isDelta; }
00322   
00323   /// EmitValue - Emit delta value.
00324   ///
00325   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
00326   
00327   /// SizeOf - Determine size of delta value in bytes.
00328   ///
00329   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
00330 };
00331 
00332 //===----------------------------------------------------------------------===//
00333 // DIEntry - A pointer to a debug information entry.
00334 // 
00335 struct DIEntry : public DIEValue {
00336   DIE *Entry;
00337   
00338   DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
00339 
00340   // Implement isa/cast/dyncast.
00341   static bool classof(const DIEntry *)   { return true; }
00342   static bool classof(const DIEValue *E) { return E->Type == isEntry; }
00343   
00344   /// EmitValue - Emit debug information entry offset.
00345   ///
00346   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
00347   
00348   /// SizeOf - Determine size of debug information entry in bytes.
00349   ///
00350   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
00351 };
00352 
00353 //===----------------------------------------------------------------------===//
00354 // DIEBlock - A block of values.  Primarily used for location expressions.
00355 //
00356 struct DIEBlock : public DIEValue {
00357   unsigned Size;                        // Size in bytes excluding size header.
00358   std::vector<unsigned> Forms;          // Data forms.
00359   std::vector<DIEValue *> Values;       // Block values.
00360   
00361   DIEBlock()
00362   : DIEValue(isBlock)
00363   , Size(0)
00364   , Forms()
00365   , Values()
00366   {}
00367   ~DIEBlock();
00368 
00369   // Implement isa/cast/dyncast.
00370   static bool classof(const DIEBlock *)  { return true; }
00371   static bool classof(const DIEValue *E) { return E->Type == isBlock; }
00372   
00373   /// ComputeSize - calculate the size of the block.
00374   ///
00375   unsigned ComputeSize(DwarfWriter &DW);
00376   
00377   /// BestForm - Choose the best form for data.
00378   ///
00379   unsigned BestForm();
00380 
00381   /// EmitValue - Emit block data.
00382   ///
00383   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
00384   
00385   /// SizeOf - Determine size of block data in bytes.
00386   ///
00387   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
00388 
00389   /// AddUInt - Add an unsigned integer value.
00390   ///
00391   void AddUInt(unsigned Form, uint64_t Integer);
00392 
00393   /// AddSInt - Add an signed integer value.
00394   ///
00395   void AddSInt(unsigned Form, int64_t Integer);
00396       
00397   /// AddString - Add a std::string value.
00398   ///
00399   void AddString(unsigned Form, const std::string &String);
00400       
00401   /// AddLabel - Add a Dwarf label value.
00402   ///
00403   void AddLabel(unsigned Form, const DWLabel &Label);
00404       
00405   /// AddObjectLabel - Add a non-Dwarf label value.
00406   ///
00407   void AddObjectLabel(unsigned Form, const std::string &Label);
00408       
00409   /// AddDelta - Add a label delta value.
00410   ///
00411   void AddDelta(unsigned Form, const DWLabel &Hi, const DWLabel &Lo);
00412       
00413   /// AddDIEntry - Add a DIE value.
00414   ///
00415   void AddDIEntry(unsigned Form, DIE *Entry);
00416 
00417 };
00418 
00419 //===----------------------------------------------------------------------===//
00420 // DIE - A structured debug information entry.  Has an abbreviation which
00421 // describes it's organization.
00422 class DIE {
00423 private:
00424   DIEAbbrev *Abbrev;                    // Temporary buffer for abbreviation.
00425   unsigned AbbrevID;                    // Decribing abbreviation ID.
00426   unsigned Offset;                      // Offset in debug info section.
00427   unsigned Size;                        // Size of instance + children.
00428   std::vector<DIE *> Children;          // Children DIEs.
00429   std::vector<DIEValue *> Values;       // Attributes values.
00430   
00431 public:
00432   DIE(unsigned Tag);
00433   ~DIE();
00434   
00435   // Accessors.
00436   unsigned   getAbbrevID()                   const { return AbbrevID; }
00437   unsigned   getOffset()                     const { return Offset; }
00438   unsigned   getSize()                       const { return Size; }
00439   const std::vector<DIE *> &getChildren()    const { return Children; }
00440   const std::vector<DIEValue *> &getValues() const { return Values; }
00441   void setOffset(unsigned O)                 { Offset = O; }
00442   void setSize(unsigned S)                   { Size = S; }
00443   
00444   /// SiblingOffset - Return the offset of the debug information entry's
00445   /// sibling.
00446   unsigned SiblingOffset() const { return Offset + Size; }
00447   
00448   /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
00449   ///
00450   void AddSiblingOffset();
00451 
00452   /// AddUInt - Add an unsigned integer attribute data and value.
00453   ///
00454   void AddUInt(unsigned Attribute, unsigned Form, uint64_t Integer);
00455 
00456   /// AddSInt - Add an signed integer attribute data and value.
00457   ///
00458   void AddSInt(unsigned Attribute, unsigned Form, int64_t Integer);
00459       
00460   /// AddString - Add a std::string attribute data and value.
00461   ///
00462   void AddString(unsigned Attribute, unsigned Form,
00463                  const std::string &String);
00464       
00465   /// AddLabel - Add a Dwarf label attribute data and value.
00466   ///
00467   void AddLabel(unsigned Attribute, unsigned Form, const DWLabel &Label);
00468       
00469   /// AddObjectLabel - Add a non-Dwarf label attribute data and value.
00470   ///
00471   void AddObjectLabel(unsigned Attribute, unsigned Form,
00472                       const std::string &Label);
00473       
00474   /// AddDelta - Add a label delta attribute data and value.
00475   ///
00476   void AddDelta(unsigned Attribute, unsigned Form,
00477                 const DWLabel &Hi, const DWLabel &Lo);
00478       
00479   /// AddDIEntry - Add a DIE attribute data and value.
00480   ///
00481   void AddDIEntry(unsigned Attribute, unsigned Form, DIE *Entry);
00482 
00483   /// AddBlock - Add block data.
00484   ///
00485   void AddBlock(unsigned Attribute, unsigned Form, DIEBlock *Block);
00486 
00487   /// Complete - Indicate that all attributes have been added and
00488   /// ready to get an abbreviation ID.
00489   ///
00490   void Complete(DwarfWriter &DW);
00491   
00492   /// AddChild - Add a child to the DIE.
00493   void AddChild(DIE *Child);
00494 };
00495 
00496 } // End of namespace llvm
00497 
00498 //===----------------------------------------------------------------------===//
00499 
00500 CompileUnit::~CompileUnit() {
00501   delete Die;
00502 }
00503 
00504 /// hasContent - Return true if this compile unit has something to write out.
00505 ///
00506 bool CompileUnit::hasContent() const {
00507   return !Die->getChildren().empty();
00508 }
00509 
00510 /// AddGlobal - Add a new global entity to the compile unit.
00511 ///
00512 void CompileUnit::AddGlobal(const std::string &Name, DIE *Die) {
00513   Globals[Name] = Die;
00514 }
00515 
00516 //===----------------------------------------------------------------------===//
00517 
00518 /// operator== - Used by UniqueVector to locate entry.
00519 ///
00520 bool DIEAbbrev::operator==(const DIEAbbrev &DA) const {
00521   if (Tag != DA.Tag) return false;
00522   if (ChildrenFlag != DA.ChildrenFlag) return false;
00523   if (Data.size() != DA.Data.size()) return false;
00524   
00525   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
00526     if (Data[i] != DA.Data[i]) return false;
00527   }
00528   
00529   return true;
00530 }
00531 
00532 /// operator< - Used by UniqueVector to locate entry.
00533 ///
00534 bool DIEAbbrev::operator<(const DIEAbbrev &DA) const {
00535   if (Tag != DA.Tag) return Tag < DA.Tag;
00536   if (ChildrenFlag != DA.ChildrenFlag) return ChildrenFlag < DA.ChildrenFlag;
00537   if (Data.size() != DA.Data.size()) return Data.size() < DA.Data.size();
00538   
00539   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
00540     if (Data[i] != DA.Data[i]) return Data[i] < DA.Data[i];
00541   }
00542   
00543   return false;
00544 }
00545     
00546 /// Emit - Print the abbreviation using the specified Dwarf writer.
00547 ///
00548 void DIEAbbrev::Emit(const DwarfWriter &DW) const {
00549   // Emit its Dwarf tag type.
00550   DW.EmitULEB128Bytes(Tag);
00551   DW.EOL(TagString(Tag));
00552   
00553   // Emit whether it has children DIEs.
00554   DW.EmitULEB128Bytes(ChildrenFlag);
00555   DW.EOL(ChildrenString(ChildrenFlag));
00556   
00557   // For each attribute description.
00558   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
00559     const DIEAbbrevData &AttrData = Data[i];
00560     
00561     // Emit attribute type.
00562     DW.EmitULEB128Bytes(AttrData.getAttribute());
00563     DW.EOL(AttributeString(AttrData.getAttribute()));
00564     
00565     // Emit form type.
00566     DW.EmitULEB128Bytes(AttrData.getForm());
00567     DW.EOL(FormEncodingString(AttrData.getForm()));
00568   }
00569 
00570   // Mark end of abbreviation.
00571   DW.EmitULEB128Bytes(0); DW.EOL("EOM(1)");
00572   DW.EmitULEB128Bytes(0); DW.EOL("EOM(2)");
00573 }
00574 
00575 #ifndef NDEBUG
00576   void DIEAbbrev::print(std::ostream &O) {
00577     O << "Abbreviation @"
00578       << std::hex << (intptr_t)this << std::dec
00579       << "  "
00580       << TagString(Tag)
00581       << " "
00582       << ChildrenString(ChildrenFlag)
00583       << "\n";
00584     
00585     for (unsigned i = 0, N = Data.size(); i < N; ++i) {
00586       O << "  "
00587         << AttributeString(Data[i].getAttribute())
00588         << "  "
00589         << FormEncodingString(Data[i].getForm())
00590         << "\n";
00591     }
00592   }
00593   void DIEAbbrev::dump() { print(std::cerr); }
00594 #endif
00595 
00596 //===----------------------------------------------------------------------===//
00597 
00598 /// BestForm - Choose the best form for integer.
00599 ///
00600 unsigned DIEInteger::BestForm(bool IsSigned) {
00601   if (IsSigned) {
00602     if ((char)Integer == (signed)Integer)   return DW_FORM_data1;
00603     if ((short)Integer == (signed)Integer)  return DW_FORM_data2;
00604     if ((int)Integer == (signed)Integer)    return DW_FORM_data4;
00605   } else {
00606     if ((unsigned char)Integer == Integer)  return DW_FORM_data1;
00607     if ((unsigned short)Integer == Integer) return DW_FORM_data2;
00608     if ((unsigned int)Integer == Integer)   return DW_FORM_data4;
00609   }
00610   return DW_FORM_data8;
00611 }
00612     
00613 /// EmitValue - Emit integer of appropriate size.
00614 ///
00615 void DIEInteger::EmitValue(const DwarfWriter &DW, unsigned Form) const {
00616   switch (Form) {
00617   case DW_FORM_flag:  // Fall thru
00618   case DW_FORM_ref1:  // Fall thru
00619   case DW_FORM_data1: DW.EmitInt8(Integer);         break;
00620   case DW_FORM_ref2:  // Fall thru
00621   case DW_FORM_data2: DW.EmitInt16(Integer);        break;
00622   case DW_FORM_ref4:  // Fall thru
00623   case DW_FORM_data4: DW.EmitInt32(Integer);        break;
00624   case DW_FORM_ref8:  // Fall thru
00625   case DW_FORM_data8: DW.EmitInt64(Integer);        break;
00626   case DW_FORM_udata: DW.EmitULEB128Bytes(Integer); break;
00627   case DW_FORM_sdata: DW.EmitSLEB128Bytes(Integer); break;
00628   default: assert(0 && "DIE Value form not supported yet"); break;
00629   }
00630 }
00631 
00632 /// SizeOf - Determine size of integer value in bytes.
00633 ///
00634 unsigned DIEInteger::SizeOf(const DwarfWriter &DW, unsigned Form) const {
00635   switch (Form) {
00636   case DW_FORM_flag:  // Fall thru
00637   case DW_FORM_ref1:  // Fall thru
00638   case DW_FORM_data1: return sizeof(int8_t);
00639   case DW_FORM_ref2:  // Fall thru
00640   case DW_FORM_data2: return sizeof(int16_t);
00641   case DW_FORM_ref4:  // Fall thru
00642   case DW_FORM_data4: return sizeof(int32_t);
00643   case DW_FORM_ref8:  // Fall thru
00644   case DW_FORM_data8: return sizeof(int64_t);
00645   case DW_FORM_udata: return DW.SizeULEB128(Integer);
00646   case DW_FORM_sdata: return DW.SizeSLEB128(Integer);
00647   default: assert(0 && "DIE Value form not supported yet"); break;
00648   }
00649   return 0;
00650 }
00651 
00652 //===----------------------------------------------------------------------===//
00653 
00654 /// EmitValue - Emit string value.
00655 ///
00656 void DIEString::EmitValue(const DwarfWriter &DW, unsigned Form) const {
00657   DW.EmitString(String);
00658 }
00659 
00660 /// SizeOf - Determine size of string value in bytes.
00661 ///
00662 unsigned DIEString::SizeOf(const DwarfWriter &DW, unsigned Form) const {
00663   return String.size() + sizeof(char); // sizeof('\0');
00664 }
00665 
00666 //===----------------------------------------------------------------------===//
00667 
00668 /// EmitValue - Emit label value.
00669 ///
00670 void DIEDwarfLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
00671   DW.EmitReference(Label);
00672 }
00673 
00674 /// SizeOf - Determine size of label value in bytes.
00675 ///
00676 unsigned DIEDwarfLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
00677   return DW.getAddressSize();
00678 }
00679     
00680 //===----------------------------------------------------------------------===//
00681 
00682 /// EmitValue - Emit label value.
00683 ///
00684 void DIEObjectLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
00685   DW.EmitReference(Label);
00686 }
00687 
00688 /// SizeOf - Determine size of label value in bytes.
00689 ///
00690 unsigned DIEObjectLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
00691   return DW.getAddressSize();
00692 }
00693     
00694 //===----------------------------------------------------------------------===//
00695 
00696 /// EmitValue - Emit delta value.
00697 ///
00698 void DIEDelta::EmitValue(const DwarfWriter &DW, unsigned Form) const {
00699   DW.EmitDifference(LabelHi, LabelLo);
00700 }
00701 
00702 /// SizeOf - Determine size of delta value in bytes.
00703 ///
00704 unsigned DIEDelta::SizeOf(const DwarfWriter &DW, unsigned Form) const {
00705   return DW.getAddressSize();
00706 }
00707 
00708 //===----------------------------------------------------------------------===//
00709 /// EmitValue - Emit debug information entry offset.
00710 ///
00711 void DIEntry::EmitValue(const DwarfWriter &DW, unsigned Form) const {
00712   DW.EmitInt32(Entry->getOffset());
00713 }
00714 
00715 /// SizeOf - Determine size of debug information entry value in bytes.
00716 ///
00717 unsigned DIEntry::SizeOf(const DwarfWriter &DW, unsigned Form) const {
00718   return sizeof(int32_t);
00719 }
00720     
00721 //===----------------------------------------------------------------------===//
00722 
00723 DIEBlock::~DIEBlock() {
00724   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
00725     delete Values[i];
00726   }
00727 }
00728 
00729 /// ComputeSize - calculate the size of the block.
00730 ///
00731 unsigned DIEBlock::ComputeSize(DwarfWriter &DW) {
00732   Size = 0;
00733   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
00734     Size += Values[i]->SizeOf(DW, Forms[i]);
00735   }
00736   return Size;
00737 }
00738 
00739 /// BestForm - Choose the best form for data.
00740 ///
00741 unsigned DIEBlock::BestForm() {
00742   if ((unsigned char)Size == Size)  return DW_FORM_block1;
00743   if ((unsigned short)Size == Size) return DW_FORM_block2;
00744   if ((unsigned int)Size == Size)   return DW_FORM_block4;
00745   return DW_FORM_block;
00746 }
00747 
00748 /// EmitValue - Emit block data.
00749 ///
00750 void DIEBlock::EmitValue(const DwarfWriter &DW, unsigned Form) const {
00751   switch (Form) {
00752   case DW_FORM_block1: DW.EmitInt8(Size);         break;
00753   case DW_FORM_block2: DW.EmitInt16(Size);        break;
00754   case DW_FORM_block4: DW.EmitInt32(Size);        break;
00755   case DW_FORM_block:  DW.EmitULEB128Bytes(Size); break;
00756   default: assert(0 && "Improper form for block"); break;
00757   }
00758   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
00759     DW.EOL("");
00760     Values[i]->EmitValue(DW, Forms[i]);
00761   }
00762 }
00763 
00764 /// SizeOf - Determine size of block data in bytes.
00765 ///
00766 unsigned DIEBlock::SizeOf(const DwarfWriter &DW, unsigned Form) const {
00767   switch (Form) {
00768   case DW_FORM_block1: return Size + sizeof(int8_t);
00769   case DW_FORM_block2: return Size + sizeof(int16_t);
00770   case DW_FORM_block4: return Size + sizeof(int32_t);
00771   case DW_FORM_block: return Size + DW.SizeULEB128(Size);
00772   default: assert(0 && "Improper form for block"); break;
00773   }
00774   return 0;
00775 }
00776 
00777 /// AddUInt - Add an unsigned integer value.
00778 ///
00779 void DIEBlock::AddUInt(unsigned Form, uint64_t Integer) {
00780   DIEInteger *DI = new DIEInteger(Integer);
00781   Values.push_back(DI);
00782   if (Form == 0) Form = DI->BestForm(false);
00783   Forms.push_back(Form);
00784 }
00785 
00786 /// AddSInt - Add an signed integer value.
00787 ///
00788 void DIEBlock::AddSInt(unsigned Form, int64_t Integer) {
00789   DIEInteger *DI = new DIEInteger(Integer);
00790   Values.push_back(DI);
00791   if (Form == 0) Form = DI->BestForm(true);
00792   Forms.push_back(Form);
00793 }
00794     
00795 /// AddString - Add a std::string value.
00796 ///
00797 void DIEBlock::AddString(unsigned Form, const std::string &String) {
00798   Values.push_back(new DIEString(String));
00799   Forms.push_back(Form);
00800 }
00801     
00802 /// AddLabel - Add a Dwarf label value.
00803 ///
00804 void DIEBlock::AddLabel(unsigned Form, const DWLabel &Label) {
00805   Values.push_back(new DIEDwarfLabel(Label));
00806   Forms.push_back(Form);
00807 }
00808     
00809 /// AddObjectLabel - Add a non-Dwarf label value.
00810 ///
00811 void DIEBlock::AddObjectLabel(unsigned Form, const std::string &Label) {
00812   Values.push_back(new DIEObjectLabel(Label));
00813   Forms.push_back(Form);
00814 }
00815     
00816 /// AddDelta - Add a label delta value.
00817 ///
00818 void DIEBlock::AddDelta(unsigned Form, const DWLabel &Hi, const DWLabel &Lo) {
00819   Values.push_back(new DIEDelta(Hi, Lo));
00820   Forms.push_back(Form);
00821 }
00822     
00823 /// AddDIEntry - Add a DIE value.
00824 ///
00825 void DIEBlock::AddDIEntry(unsigned Form, DIE *Entry) {
00826   Values.push_back(new DIEntry(Entry));
00827   Forms.push_back(Form);
00828 }
00829 
00830 //===----------------------------------------------------------------------===//
00831 
00832 DIE::DIE(unsigned Tag)
00833 : Abbrev(new DIEAbbrev(Tag, DW_CHILDREN_no))
00834 , AbbrevID(0)
00835 , Offset(0)
00836 , Size(0)
00837 , Children()
00838 , Values()
00839 {}
00840 
00841 DIE::~DIE() {
00842   if (Abbrev) delete Abbrev;
00843   
00844   for (unsigned i = 0, N = Children.size(); i < N; ++i) {
00845     delete Children[i];
00846   }
00847 
00848   for (unsigned j = 0, M = Values.size(); j < M; ++j) {
00849     delete Values[j];
00850   }
00851 }
00852     
00853 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
00854 ///
00855 void DIE::AddSiblingOffset() {
00856   DIEInteger *DI = new DIEInteger(0);
00857   Values.insert(Values.begin(), DI);
00858   Abbrev->AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
00859 }
00860 
00861 /// AddUInt - Add an unsigned integer attribute data and value.
00862 ///
00863 void DIE::AddUInt(unsigned Attribute, unsigned Form, uint64_t Integer) {
00864   DIEInteger *DI = new DIEInteger(Integer);
00865   Values.push_back(DI);
00866   if (!Form) Form = DI->BestForm(false);
00867   Abbrev->AddAttribute(Attribute, Form);
00868 }
00869     
00870 /// AddSInt - Add an signed integer attribute data and value.
00871 ///
00872 void DIE::AddSInt(unsigned Attribute, unsigned Form, int64_t Integer) {
00873   DIEInteger *DI = new DIEInteger(Integer);
00874   Values.push_back(DI);
00875   if (!Form) Form = DI->BestForm(true);
00876   Abbrev->AddAttribute(Attribute, Form);
00877 }
00878     
00879 /// AddString - Add a std::string attribute data and value.
00880 ///
00881 void DIE::AddString(unsigned Attribute, unsigned Form,
00882                     const std::string &String) {
00883   Values.push_back(new DIEString(String));
00884   Abbrev->AddAttribute(Attribute, Form);
00885 }
00886     
00887 /// AddLabel - Add a Dwarf label attribute data and value.
00888 ///
00889 void DIE::AddLabel(unsigned Attribute, unsigned Form,
00890                    const DWLabel &Label) {
00891   Values.push_back(new DIEDwarfLabel(Label));
00892   Abbrev->AddAttribute(Attribute, Form);
00893 }
00894     
00895 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
00896 ///
00897 void DIE::AddObjectLabel(unsigned Attribute, unsigned Form,
00898                          const std::string &Label) {
00899   Values.push_back(new DIEObjectLabel(Label));
00900   Abbrev->AddAttribute(Attribute, Form);
00901 }
00902     
00903 /// AddDelta - Add a label delta attribute data and value.
00904 ///
00905 void DIE::AddDelta(unsigned Attribute, unsigned Form,
00906                    const DWLabel &Hi, const DWLabel &Lo) {
00907   Values.push_back(new DIEDelta(Hi, Lo));
00908   Abbrev->AddAttribute(Attribute, Form);
00909 }
00910     
00911 /// AddDIEntry - Add a DIE attribute data and value.
00912 ///
00913 void DIE::AddDIEntry(unsigned Attribute, unsigned Form, DIE *Entry) {
00914   Values.push_back(new DIEntry(Entry));
00915   Abbrev->AddAttribute(Attribute, Form);
00916 }
00917 
00918 /// AddBlock - Add block data.
00919 ///
00920 void DIE::AddBlock(unsigned Attribute, unsigned Form, DIEBlock *Block) {
00921   assert(Block->Size && "Block size has not been computed");
00922   Values.push_back(Block);
00923   if (!Form) Form = Block->BestForm();
00924   Abbrev->AddAttribute(Attribute, Form);
00925 }
00926 
00927 /// Complete - Indicate that all attributes have been added and ready to get an
00928 /// abbreviation ID.
00929 void DIE::Complete(DwarfWriter &DW) {
00930   AbbrevID = DW.NewAbbreviation(Abbrev);
00931   delete Abbrev;
00932   Abbrev = NULL;
00933 }
00934 
00935 /// AddChild - Add a child to the DIE.
00936 ///
00937 void DIE::AddChild(DIE *Child) {
00938   assert(Abbrev && "Adding children without an abbreviation");
00939   Abbrev->setChildrenFlag(DW_CHILDREN_yes);
00940   Children.push_back(Child);
00941 }
00942 
00943 //===----------------------------------------------------------------------===//
00944 
00945 /// DWContext
00946 
00947 //===----------------------------------------------------------------------===//
00948 
00949 /// PrintHex - Print a value as a hexidecimal value.
00950 ///
00951 void DwarfWriter::PrintHex(int Value) const { 
00952   O << "0x" << std::hex << Value << std::dec;
00953 }
00954 
00955 /// EOL - Print a newline character to asm stream.  If a comment is present
00956 /// then it will be printed first.  Comments should not contain '\n'.
00957 void DwarfWriter::EOL(const std::string &Comment) const {
00958   if (DwarfVerbose && !Comment.empty()) {
00959     O << "\t"
00960       << Asm->CommentString
00961       << " "
00962       << Comment;
00963   }
00964   O << "\n";
00965 }
00966 
00967 /// EmitAlign - Print a align directive.
00968 ///
00969 void DwarfWriter::EmitAlign(unsigned Alignment) const {
00970   O << Asm->AlignDirective << Alignment << "\n";
00971 }
00972 
00973 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
00974 /// unsigned leb128 value.
00975 void DwarfWriter::EmitULEB128Bytes(unsigned Value) const {
00976   if (hasLEB128) {
00977     O << "\t.uleb128\t"
00978       << Value;
00979   } else {
00980     O << Asm->Data8bitsDirective;
00981     PrintULEB128(Value);
00982   }
00983 }
00984 
00985 /// EmitSLEB128Bytes - Emit an assembler byte data directive to compose a
00986 /// signed leb128 value.
00987 void DwarfWriter::EmitSLEB128Bytes(int Value) const {
00988   if (hasLEB128) {
00989     O << "\t.sleb128\t"
00990       << Value;
00991   } else {
00992     O << Asm->Data8bitsDirective;
00993     PrintSLEB128(Value);
00994   }
00995 }
00996 
00997 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
00998 /// representing an unsigned leb128 value.
00999 void DwarfWriter::PrintULEB128(unsigned Value) const {
01000   do {
01001     unsigned Byte = Value & 0x7f;
01002     Value >>= 7;
01003     if (Value) Byte |= 0x80;
01004     PrintHex(Byte);
01005     if (Value) O << ", ";
01006   } while (Value);
01007 }
01008 
01009 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
01010 /// value.
01011 unsigned DwarfWriter::SizeULEB128(unsigned Value) {
01012   unsigned Size = 0;
01013   do {
01014     Value >>= 7;
01015     Size += sizeof(int8_t);
01016   } while (Value);
01017   return Size;
01018 }
01019 
01020 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
01021 /// representing a signed leb128 value.
01022 void DwarfWriter::PrintSLEB128(int Value) const {
01023   int Sign = Value >> (8 * sizeof(Value) - 1);
01024   bool IsMore;
01025   
01026   do {
01027     unsigned Byte = Value & 0x7f;
01028     Value >>= 7;
01029     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
01030     if (IsMore) Byte |= 0x80;
01031     PrintHex(Byte);
01032     if (IsMore) O << ", ";
01033   } while (IsMore);
01034 }
01035 
01036 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
01037 /// value.
01038 unsigned DwarfWriter::SizeSLEB128(int Value) {
01039   unsigned Size = 0;
01040   int Sign = Value >> (8 * sizeof(Value) - 1);
01041   bool IsMore;
01042   
01043   do {
01044     unsigned Byte = Value & 0x7f;
01045     Value >>= 7;
01046     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
01047     Size += sizeof(int8_t);
01048   } while (IsMore);
01049   return Size;
01050 }
01051 
01052 /// EmitInt8 - Emit a byte directive and value.
01053 ///
01054 void DwarfWriter::EmitInt8(int Value) const {
01055   O << Asm->Data8bitsDirective;
01056   PrintHex(Value & 0xFF);
01057 }
01058 
01059 /// EmitInt16 - Emit a short directive and value.
01060 ///
01061 void DwarfWriter::EmitInt16(int Value) const {
01062   O << Asm->Data16bitsDirective;
01063   PrintHex(Value & 0xFFFF);
01064 }
01065 
01066 /// EmitInt32 - Emit a long directive and value.
01067 ///
01068 void DwarfWriter::EmitInt32(int Value) const {
01069   O << Asm->Data32bitsDirective;
01070   PrintHex(Value);
01071 }
01072 
01073 /// EmitInt64 - Emit a long long directive and value.
01074 ///
01075 void DwarfWriter::EmitInt64(uint64_t Value) const {
01076   if (Asm->Data64bitsDirective) {
01077     O << Asm->Data64bitsDirective << "0x" << std::hex << Value << std::dec;
01078   } else {
01079     if (TD->isBigEndian()) {
01080       EmitInt32(unsigned(Value >> 32)); O << "\n";
01081       EmitInt32(unsigned(Value));
01082     } else {
01083       EmitInt32(unsigned(Value)); O << "\n";
01084       EmitInt32(unsigned(Value >> 32));
01085     }
01086   }
01087 }
01088 
01089 /// EmitString - Emit a string with quotes and a null terminator.
01090 /// Special characters are emitted properly. (Eg. '\t')
01091 void DwarfWriter::EmitString(const std::string &String) const {
01092   O << Asm->AsciiDirective
01093     << "\"";
01094   for (unsigned i = 0, N = String.size(); i < N; ++i) {
01095     unsigned char C = String[i];
01096     
01097     if (!isascii(C) || iscntrl(C)) {
01098       switch(C) {
01099       case '\b': O << "\\b"; break;
01100       case '\f': O << "\\f"; break;
01101       case '\n': O << "\\n"; break;
01102       case '\r': O << "\\r"; break;
01103       case '\t': O << "\\t"; break;
01104       default:
01105         O << '\\';
01106         O << char('0' + (C >> 6));
01107         O << char('0' + (C >> 3));
01108         O << char('0' + (C >> 0));
01109         break;
01110       }
01111     } else if (C == '\"') {
01112       O << "\\\"";
01113     } else if (C == '\'') {
01114       O << "\\\'";
01115     } else {
01116      O << C;
01117     }
01118   }
01119   O << "\\0\"";
01120 }
01121 
01122 /// PrintLabelName - Print label name in form used by Dwarf writer.
01123 ///
01124 void DwarfWriter::PrintLabelName(const char *Tag, unsigned Number) const {
01125   O << Asm->PrivateGlobalPrefix
01126     << "debug_"
01127     << Tag;
01128   if (Number) O << Number;
01129 }
01130 
01131 /// EmitLabel - Emit location label for internal use by Dwarf.
01132 ///
01133 void DwarfWriter::EmitLabel(const char *Tag, unsigned Number) const {
01134   PrintLabelName(Tag, Number);
01135   O << ":\n";
01136 }
01137 
01138 /// EmitReference - Emit a reference to a label.
01139 ///
01140 void DwarfWriter::EmitReference(const char *Tag, unsigned Number) const {
01141   if (AddressSize == 4)
01142     O << Asm->Data32bitsDirective;
01143   else
01144     O << Asm->Data64bitsDirective;
01145     
01146   PrintLabelName(Tag, Number);
01147 }
01148 void DwarfWriter::EmitReference(const std::string &Name) const {
01149   if (AddressSize == 4)
01150     O << Asm->Data32bitsDirective;
01151   else
01152     O << Asm->Data64bitsDirective;
01153     
01154   O << Name;
01155 }
01156 
01157 /// EmitDifference - Emit an label difference as sizeof(pointer) value.  Some
01158 /// assemblers do not accept absolute expressions with data directives, so there 
01159 /// is an option (needsSet) to use an intermediary 'set' expression.
01160 void DwarfWriter::EmitDifference(const char *TagHi, unsigned NumberHi,
01161                                  const char *TagLo, unsigned NumberLo) const {
01162   if (needsSet) {
01163     static unsigned SetCounter = 0;
01164     
01165     O << "\t.set\t";
01166     PrintLabelName("set", SetCounter);
01167     O << ",";
01168     PrintLabelName(TagHi, NumberHi);
01169     O << "-";
01170     PrintLabelName(TagLo, NumberLo);
01171     O << "\n";
01172     
01173     if (AddressSize == sizeof(int32_t))
01174       O << Asm->Data32bitsDirective;
01175     else
01176       O << Asm->Data64bitsDirective;
01177       
01178     PrintLabelName("set", SetCounter);
01179     
01180     ++SetCounter;
01181   } else {
01182     if (AddressSize == sizeof(int32_t))
01183       O << Asm->Data32bitsDirective;
01184     else
01185       O << Asm->Data64bitsDirective;
01186       
01187     PrintLabelName(TagHi, NumberHi);
01188     O << "-";
01189     PrintLabelName(TagLo, NumberLo);
01190   }
01191 }
01192 
01193 /// NewAbbreviation - Add the abbreviation to the Abbreviation vector.
01194 ///  
01195 unsigned DwarfWriter::NewAbbreviation(DIEAbbrev *Abbrev) {
01196   return Abbreviations.insert(*Abbrev);
01197 }
01198 
01199 /// NewString - Add a string to the constant pool and returns a label.
01200 ///
01201 DWLabel DwarfWriter::NewString(const std::string &String) {
01202   unsigned StringID = StringPool.insert(String);
01203   return DWLabel("string", StringID);
01204 }
01205 
01206 /// AddSourceLine - Add location information to specified debug information
01207 /// entry.
01208 void DwarfWriter::AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line){
01209   if (File && Line) {
01210     CompileUnit *FileUnit = FindCompileUnit(File);
01211     unsigned FileID = FileUnit->getID();
01212     Die->AddUInt(DW_AT_decl_file, 0, FileID);
01213     Die->AddUInt(DW_AT_decl_line, 0, Line);
01214   }
01215 }
01216 
01217 /// AddAddress - Add an address attribute to a die based on the location
01218 /// provided.
01219 void DwarfWriter::AddAddress(DIE *Die, unsigned Attribute,
01220                              const MachineLocation &Location) {
01221   DIEBlock *Block = new DIEBlock();
01222   if (Location.isRegister()) {
01223     Block->AddUInt(DW_FORM_data1,
01224                    DW_OP_reg0 + RI->getDwarfRegNum(Location.getRegister()));
01225   } else {
01226     Block->AddUInt(DW_FORM_data1,
01227                    DW_OP_breg0 + RI->getDwarfRegNum(Location.getRegister()));
01228     Block->AddUInt(DW_FORM_sdata, Location.getOffset());
01229   }
01230   Block->ComputeSize(*this);
01231   Die->AddBlock(Attribute, 0, Block);
01232 }
01233 
01234 /// getDieMapSlotFor - Returns the debug information entry map slot for the
01235 /// specified debug descriptor.
01236 DIE *&DwarfWriter::getDieMapSlotFor(DebugInfoDesc *DD) {
01237   return DescToDieMap[DD];
01238 }
01239                                  
01240 /// NewType - Create a new type DIE.
01241 ///
01242 DIE *DwarfWriter::NewType(DIE *Context, TypeDesc *TyDesc, CompileUnit *Unit) {
01243   if (!TyDesc) {
01244     // FIXME - Hack for missing types
01245     DIE *Die = new DIE(DW_TAG_base_type);
01246     Die->AddUInt(DW_AT_byte_size, 0, 4);
01247     Die->AddUInt(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
01248     Unit->getDie()->AddChild(Die);
01249     return Die;
01250   }
01251   
01252   // FIXME - Should handle other contexts that compile units.
01253 
01254   // Check for pre-existence.
01255   DIE *&Slot = Unit->getDieMapSlotFor(TyDesc);
01256   if (Slot) return Slot;
01257 
01258   // Get core information.
01259   const std::string &Name = TyDesc->getName();
01260   uint64_t Size = TyDesc->getSize() >> 3;
01261   
01262   DIE *Ty = NULL;
01263   
01264   if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
01265     // Fundamental types like int, float, bool
01266     Slot = Ty = new DIE(DW_TAG_base_type);
01267     unsigned Encoding = BasicTy->getEncoding();
01268     Ty->AddUInt(DW_AT_encoding,  DW_FORM_data1, Encoding);
01269   } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
01270     // Create specific DIE.
01271     Slot = Ty = new DIE(DerivedTy->getTag());
01272     
01273     // Map to main type, void will not have a type.
01274     if (TypeDesc *FromTy = DerivedTy->getFromType()) {
01275       Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
01276                      NewType(Context, FromTy, Unit));
01277     }
01278   } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)) {
01279     // Fetch tag
01280     unsigned Tag = CompTy->getTag();
01281     
01282     // Create specific DIE.
01283     Slot = Ty = Tag == DW_TAG_vector_type ? new DIE(DW_TAG_array_type) :
01284                                             new DIE(Tag);
01285     
01286     std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
01287     
01288     switch (Tag) {
01289     case DW_TAG_vector_type: Ty->AddUInt(DW_AT_GNU_vector, DW_FORM_flag, 1);
01290       // Fall thru
01291     case DW_TAG_array_type: {
01292       // Add element type.
01293       if (TypeDesc *FromTy = CompTy->getFromType()) {
01294         Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
01295                        NewType(Context, FromTy, Unit));
01296       }
01297       
01298       // Don't emit size attribute.
01299       Size = 0;
01300       
01301       // Construct an anonymous type for index type.
01302       DIE *IndexTy = new DIE(DW_TAG_base_type);
01303       IndexTy->AddUInt(DW_AT_byte_size, 0, 4);
01304       IndexTy->AddUInt(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
01305       // Add to context.
01306       Context->AddChild(IndexTy);
01307     
01308       // Add subranges to array type.
01309       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
01310         SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
01311         int64_t Lo = SRD->getLo();
01312         int64_t Hi = SRD->getHi();
01313         DIE *Subrange = new DIE(DW_TAG_subrange_type);
01314         
01315         // If a range is available.
01316         if (Lo != Hi) {
01317           Subrange->AddDIEntry(DW_AT_type, DW_FORM_ref4, IndexTy);
01318           // Only add low if non-zero.
01319           if (Lo) Subrange->AddSInt(DW_AT_lower_bound, 0, Lo);
01320           Subrange->AddSInt(DW_AT_upper_bound, 0, Hi);
01321         }
01322         Ty->AddChild(Subrange);
01323       }
01324       
01325       break;
01326     }
01327     case DW_TAG_structure_type:
01328     case DW_TAG_union_type: {
01329       // FIXME - this is just the basics.
01330       // Add elements to structure type.
01331       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
01332         DerivedTypeDesc *MemberDesc = cast<DerivedTypeDesc>(Elements[i]);
01333         
01334         // Extract the basic information.
01335         const std::string &Name = MemberDesc->getName();
01336         TypeDesc *MemTy = MemberDesc->getFromType();
01337         uint64_t Size = MemberDesc->getSize();
01338         uint64_t Align = MemberDesc->getAlign();
01339         uint64_t Offset = MemberDesc->getOffset();
01340    
01341         // Construct member debug information entry.
01342         DIE *Member = new DIE(DW_TAG_member);
01343         
01344         // Add name if not "".
01345         if (!Name.empty()) Member->AddString(DW_AT_name, DW_FORM_string, Name);
01346         // Add location if available.
01347         AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
01348         
01349         // Most of the time the field info is the same as the members.
01350         uint64_t FieldSize = Size;
01351         uint64_t FieldAlign = Align;
01352         uint64_t FieldOffset = Offset;
01353         
01354         if (TypeDesc *FromTy = MemberDesc->getFromType()) {
01355           Member->AddDIEntry(DW_AT_type, DW_FORM_ref4,
01356                              NewType(Context, FromTy, Unit));
01357           FieldSize = FromTy->getSize();
01358           FieldAlign = FromTy->getSize();
01359         }
01360         
01361         // Unless we have a bit field.
01362         if (FieldSize != Size) {
01363           // Construct the alignment mask.
01364           uint64_t AlignMask = ~(FieldAlign - 1);
01365           // Determine the high bit + 1 of the declared size.
01366           uint64_t HiMark = (Offset + FieldSize) & AlignMask;
01367           // Work backwards to determine the base offset of the field.
01368           FieldOffset = HiMark - FieldSize;
01369           // Now normalize offset to the field.
01370           Offset -= FieldOffset;
01371           
01372           // Maybe we need to work from the other end.
01373           if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
01374           
01375           Member->AddUInt(DW_AT_byte_size, 0, FieldSize >> 3);
01376           Member->AddUInt(DW_AT_bit_size, 0, Size);
01377           Member->AddUInt(DW_AT_bit_offset, 0, Offset);
01378         }
01379         
01380         // Add computation for offset.
01381         DIEBlock *Block = new DIEBlock();
01382         Block->AddUInt(DW_FORM_data1, DW_OP_plus_uconst);
01383         Block->AddUInt(DW_FORM_udata, FieldOffset >> 3);
01384         Block->ComputeSize(*this);
01385         Member->AddBlock(DW_AT_data_member_location, 0, Block);
01386 
01387         if (MemberDesc->isProtected()) {
01388           Member->AddUInt(DW_AT_accessibility, 0, DW_ACCESS_protected);
01389         } else if (MemberDesc->isPrivate()) {
01390           Member->AddUInt(DW_AT_accessibility, 0, DW_ACCESS_private);
01391         }
01392         
01393         Ty->AddChild(Member);
01394       }
01395       break;
01396     }
01397     case DW_TAG_enumeration_type: {
01398       // Add enumerators to enumeration type.
01399       for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
01400         EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
01401         const std::string &Name = ED->getName();
01402         int64_t Value = ED->getValue();
01403         DIE *Enumerator = new DIE(DW_TAG_enumerator);
01404         Enumerator->AddString(DW_AT_name, DW_FORM_string, Name);
01405         Enumerator->AddSInt(DW_AT_const_value, DW_FORM_sdata, Value);
01406         Ty->AddChild(Enumerator);
01407       }
01408 
01409       break;
01410     }
01411     case DW_TAG_subroutine_type: {
01412       // Add prototype flag.
01413       Ty->AddUInt(DW_AT_prototyped, DW_FORM_flag, 1);
01414       // Add return type.
01415       Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
01416                      NewType(Context, dyn_cast<TypeDesc>(Elements[0]), Unit));
01417       
01418       // Add arguments.
01419       for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
01420         DIE *Arg = new DIE(DW_TAG_formal_parameter);
01421         Arg->AddDIEntry(DW_AT_type, DW_FORM_ref4,
01422                         NewType(Context, cast<TypeDesc>(Elements[i]), Unit));
01423         Ty->AddChild(Arg);
01424       }
01425       
01426       break;
01427     }
01428     default: break;
01429     }
01430   }
01431   
01432   assert(Ty && "Type not supported yet");
01433  
01434   // Add size if non-zero (derived types don't have a size.)
01435   if (Size) Ty->AddUInt(DW_AT_byte_size, 0, Size);
01436   // Add name if not anonymous or intermediate type.
01437   if (!Name.empty()) Ty->AddString(DW_AT_name, DW_FORM_string, Name);
01438   // Add source line info if available.
01439   AddSourceLine(Ty, TyDesc->getFile(), TyDesc->getLine());
01440 
01441   // Add to context owner.
01442   Context->AddChild(Ty);
01443   
01444   return Slot;
01445 }
01446 
01447 /// NewCompileUnit - Create new compile unit and it's debug information entry.
01448 ///
01449 CompileUnit *DwarfWriter::NewCompileUnit(CompileUnitDesc *UnitDesc,
01450                                          unsigned ID) {
01451   // Construct debug information entry.
01452   DIE *Die = new DIE(DW_TAG_compile_unit);
01453   Die->AddDelta (DW_AT_stmt_list, DW_FORM_data4,  DWLabel("line", 0),
01454                                                   DWLabel("section_line", 0));
01455 //  Die->AddLabel (DW_AT_high_pc,   DW_FORM_addr,   DWLabel("text_end", 0));
01456 //  Die->AddLabel (DW_AT_low_pc,    DW_FORM_addr,   DWLabel("text_begin", 0));
01457   Die->AddString(DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
01458   Die->AddUInt  (DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
01459   Die->AddString(DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
01460   Die->AddString(DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
01461   
01462   // Add debug information entry to descriptor map.
01463   DIE *&Slot = getDieMapSlotFor(UnitDesc);
01464   Slot = Die;
01465   
01466   // Construct compile unit.
01467   CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
01468   
01469   // Add Unit to compile unit map.
01470   DescToUnitMap[UnitDesc] = Unit;
01471   
01472   return Unit;
01473 }
01474 
01475 /// FindCompileUnit - Get the compile unit for the given descriptor.
01476 ///
01477 CompileUnit *DwarfWriter::FindCompileUnit(CompileUnitDesc *UnitDesc) {
01478   CompileUnit *Unit = DescToUnitMap[UnitDesc];
01479   assert(Unit && "Missing compile unit.");
01480   return Unit;
01481 }
01482 
01483 /// NewGlobalVariable - Add a new global variable DIE.
01484 ///
01485 DIE *DwarfWriter::NewGlobalVariable(GlobalVariableDesc *GVD) {
01486   // Get the compile unit context.
01487   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(GVD->getContext());
01488   CompileUnit *Unit = FindCompileUnit(UnitDesc);
01489 
01490   // Check for pre-existence.
01491   DIE *&Slot = Unit->getDieMapSlotFor(GVD);
01492   if (Slot) return Slot;
01493   
01494   // Get the global variable itself.
01495   GlobalVariable *GV = GVD->getGlobalVariable();
01496   // Generate the mangled name.
01497   std::string MangledName = Asm->Mang->getValueName(GV);
01498 
01499   // Gather the details (simplify add attribute code.)
01500   const std::string &Name = GVD->getName();
01501   
01502   // Get the global's type.
01503   DIE *Type = NewType(Unit->getDie(), GVD->getType(), Unit); 
01504 
01505   // Create the globale variable DIE.
01506   DIE *VariableDie = new DIE(DW_TAG_variable);
01507   VariableDie->AddString     (DW_AT_name,      DW_FORM_string, Name);
01508   VariableDie->AddDIEntry    (DW_AT_type,      DW_FORM_ref4,   Type);
01509   VariableDie->AddUInt       (DW_AT_external,  DW_FORM_flag,   1);
01510   
01511   // Add source line info if available.
01512   AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
01513 
01514   // Add address.
01515   DIEBlock *Block = new DIEBlock();
01516   Block->AddUInt(DW_FORM_data1, DW_OP_addr);
01517   Block->AddObjectLabel(DW_FORM_udata, MangledName);
01518   Block->ComputeSize(*this);
01519   VariableDie->AddBlock(DW_AT_location,  0, Block);
01520   
01521   // Add to map.
01522   Slot = VariableDie;
01523  
01524   // Add to context owner.
01525   Unit->getDie()->AddChild(VariableDie);
01526   
01527   // Expose as global.
01528   // FIXME - need to check external flag.
01529   Unit->AddGlobal(Name, VariableDie);
01530   
01531   return VariableDie;
01532 }
01533 
01534 /// NewSubprogram - Add a new subprogram DIE.
01535 ///
01536 DIE *DwarfWriter::NewSubprogram(SubprogramDesc *SPD) {
01537   // Get the compile unit context.
01538   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
01539   CompileUnit *Unit = FindCompileUnit(UnitDesc);
01540 
01541   // Check for pre-existence.
01542   DIE *&Slot = Unit->getDieMapSlotFor(SPD);
01543   if (Slot) return Slot;
01544   
01545   // Gather the details (simplify add attribute code.)
01546   const std::string &Name = SPD->getName();
01547   DIE *Type = NewType(Unit->getDie(), SPD->getType(), Unit); 
01548   unsigned IsExternal = SPD->isStatic() ? 0 : 1;
01549                                     
01550   DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
01551   SubprogramDie->AddString     (DW_AT_name,      DW_FORM_string, Name);
01552   if (Type) {
01553     SubprogramDie->AddDIEntry    (DW_AT_type,      DW_FORM_ref4,   Type);
01554   }
01555   SubprogramDie->AddUInt       (DW_AT_external,    DW_FORM_flag,   IsExternal);
01556   SubprogramDie->AddUInt       (DW_AT_prototyped,  DW_FORM_flag,   1);
01557   
01558   // Add source line info if available.
01559   AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
01560 
01561   // Add to map.
01562   Slot = SubprogramDie;
01563  
01564   // Add to context owner.
01565   Unit->getDie()->AddChild(SubprogramDie);
01566   
01567   // Expose as global.
01568   Unit->AddGlobal(Name, SubprogramDie);
01569   
01570   return SubprogramDie;
01571 }
01572 
01573 /// NewScopeVariable - Create a new scope variable.
01574 ///
01575 DIE *DwarfWriter::NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
01576   // Get the descriptor.
01577   VariableDesc *VD = DV->getDesc();
01578 
01579   // Translate tag to proper Dwarf tag.  The result variable is dropped for now.
01580   unsigned Tag;
01581   switch (VD->getTag()) {
01582   case DW_TAG_return_variable:  return NULL;
01583   case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
01584   case DW_TAG_auto_variable:    // fall thru
01585   default:                      Tag = DW_TAG_variable; break;
01586   }
01587 
01588   // Define variable debug information entry.
01589   DIE *VariableDie = new DIE(Tag);
01590   VariableDie->AddString(DW_AT_name, DW_FORM_string, VD->getName());
01591 
01592   // Add source line info if available.
01593   AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
01594   
01595   // Add variable type.
01596   DIE *Type = NewType(Unit->getDie(), VD->getType(), Unit); 
01597   VariableDie->AddDIEntry(DW_AT_type, DW_FORM_ref4, Type);
01598   
01599   // Add variable address.
01600   MachineLocation Location;
01601   RI->getLocation(*MF, DV->getFrameIndex(), Location);
01602   AddAddress(VariableDie, DW_AT_location, Location);
01603   
01604   return VariableDie;
01605 }
01606 
01607 /// ConstructScope - Construct the components of a scope.
01608 ///
01609 void DwarfWriter::ConstructScope(DebugScope *ParentScope,
01610                                  DIE *ParentDie, CompileUnit *Unit) {
01611   // Add variables to scope.
01612   std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
01613   for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
01614     DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
01615     if (VariableDie) ParentDie->AddChild(VariableDie);
01616   }
01617   
01618   // Add nested scopes.
01619   std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
01620   for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
01621     // Define the Scope debug information entry.
01622     DebugScope *Scope = Scopes[j];
01623     // FIXME - Ignore inlined functions for the time being.
01624     if (!Scope->getParent()) continue;
01625     
01626     DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
01627     
01628     // Add the scope bounds.
01629     if (unsigned StartID = Scope->getStartLabelID()) {
01630       ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
01631                          DWLabel("loc", StartID));
01632     } else {
01633       ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
01634                          DWLabel("func_begin", SubprogramCount));
01635     }
01636     if (unsigned EndID = Scope->getEndLabelID()) {
01637       ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
01638                          DWLabel("loc", EndID));
01639     } else {
01640       ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
01641                          DWLabel("func_end", SubprogramCount));
01642     }
01643                        
01644     // Add the scope contents.
01645     ConstructScope(Scope, ScopeDie, Unit);
01646     ParentDie->AddChild(ScopeDie);
01647   }
01648 }
01649 
01650 /// ConstructRootScope - Construct the scope for the subprogram.
01651 ///
01652 void DwarfWriter::ConstructRootScope(DebugScope *RootScope) {
01653   // Exit if there is no root scope.
01654   if (!RootScope) return;
01655   
01656   // Get the subprogram debug information entry. 
01657   SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
01658   
01659   // Get the compile unit context.
01660   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
01661   CompileUnit *Unit = FindCompileUnit(UnitDesc);
01662   
01663   // Get the subprogram die.
01664   DIE *SPDie = Unit->getDieMapSlotFor(SPD);
01665   assert(SPDie && "Missing subprogram descriptor");
01666   
01667   // Add the function bounds.
01668   SPDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
01669                   DWLabel("func_begin", SubprogramCount));
01670   SPDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
01671                   DWLabel("func_end", SubprogramCount));
01672   MachineLocation Location(RI->getFrameRegister(*MF));
01673   AddAddress(SPDie, DW_AT_frame_base, Location);
01674                   
01675   ConstructScope(RootScope, SPDie, Unit);
01676 }
01677 
01678 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
01679 /// tools to recognize the object file contains Dwarf information.
01680 ///
01681 void DwarfWriter::EmitInitial() {
01682   // Check to see if we already emitted intial headers.
01683   if (didInitial) return;
01684   didInitial = true;
01685   
01686   // Dwarf sections base addresses.
01687   Asm->SwitchToDataSection(DwarfFrameSection, 0);
01688   EmitLabel("section_frame", 0);
01689   Asm->SwitchToDataSection(DwarfInfoSection, 0);
01690   EmitLabel("section_info", 0);
01691   EmitLabel("info", 0);
01692   Asm->SwitchToDataSection(DwarfAbbrevSection, 0);
01693   EmitLabel("section_abbrev", 0);
01694   EmitLabel("abbrev", 0);
01695   Asm->SwitchToDataSection(DwarfARangesSection, 0);
01696   EmitLabel("section_aranges", 0);
01697   Asm->SwitchToDataSection(DwarfMacInfoSection, 0);
01698   EmitLabel("section_macinfo", 0);
01699   Asm->SwitchToDataSection(DwarfLineSection, 0);
01700   EmitLabel("section_line", 0);
01701   EmitLabel("line", 0);
01702   Asm->SwitchToDataSection(DwarfLocSection, 0);
01703   EmitLabel("section_loc", 0);
01704   Asm->SwitchToDataSection(DwarfPubNamesSection, 0);
01705   EmitLabel("section_pubnames", 0);
01706   Asm->SwitchToDataSection(DwarfStrSection, 0);
01707   EmitLabel("section_str", 0);
01708   Asm->SwitchToDataSection(DwarfRangesSection, 0);
01709   EmitLabel("section_ranges", 0);
01710 
01711   Asm->SwitchToTextSection(TextSection, 0);
01712   EmitLabel("text_begin", 0);
01713   Asm->SwitchToDataSection(DataSection, 0);
01714   EmitLabel("data_begin", 0);
01715 
01716   // Emit common frame information.
01717   EmitInitialDebugFrame();
01718 }
01719 
01720 /// EmitDIE - Recusively Emits a debug information entry.
01721 ///
01722 void DwarfWriter::EmitDIE(DIE *Die) const {
01723   // Get the abbreviation for this DIE.
01724   unsigned AbbrevID = Die->getAbbrevID();
01725   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
01726   
01727   O << "\n";
01728 
01729   // Emit the code (index) for the abbreviation.
01730   EmitULEB128Bytes(AbbrevID);
01731   EOL(std::string("Abbrev [" +
01732       utostr(AbbrevID) +
01733       "] 0x" + utohexstr(Die->getOffset()) +
01734       ":0x" + utohexstr(Die->getSize()) + " " +
01735       TagString(Abbrev.getTag())));
01736   
01737   const std::vector<DIEValue *> &Values = Die->getValues();
01738   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
01739   
01740   // Emit the DIE attribute values.
01741   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
01742     unsigned Attr = AbbrevData[i].getAttribute();
01743     unsigned Form = AbbrevData[i].getForm();
01744     assert(Form && "Too many attributes for DIE (check abbreviation)");
01745     
01746     switch (Attr) {
01747     case DW_AT_sibling: {
01748       EmitInt32(Die->SiblingOffset());
01749       break;
01750     }
01751     default: {
01752       // Emit an attribute using the defined form.
01753       Values[i]->EmitValue(*this, Form);
01754       break;
01755     }
01756     }
01757     
01758     EOL(AttributeString(Attr));
01759   }
01760   
01761   // Emit the DIE children if any.
01762   if (Abbrev.getChildrenFlag() == DW_CHILDREN_yes) {
01763     const std::vector<DIE *> &Children = Die->getChildren();
01764     
01765     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
01766       EmitDIE(Children[j]);
01767     }
01768     
01769     EmitInt8(0); EOL("End Of Children Mark");
01770   }
01771 }
01772 
01773 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
01774 ///
01775 unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
01776   // Get the children.
01777   const std::vector<DIE *> &Children = Die->getChildren();
01778   
01779   // If not last sibling and has children then add sibling offset attribute.
01780   if (!Last && !Children.empty()) Die->AddSiblingOffset();
01781 
01782   // Record the abbreviation.
01783   Die->Complete(*this);
01784   
01785   // Get the abbreviation for this DIE.
01786   unsigned AbbrevID = Die->getAbbrevID();
01787   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
01788 
01789   // Set DIE offset
01790   Die->setOffset(Offset);
01791   
01792   // Start the size with the size of abbreviation code.
01793   Offset += SizeULEB128(AbbrevID);
01794   
01795   const std::vector<DIEValue *> &Values = Die->getValues();
01796   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
01797 
01798   // Emit the DIE attribute values.
01799   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
01800     // Size attribute value.
01801     Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
01802   }
01803   
01804   // Emit the DIE children if any.
01805   if (!Children.empty()) {
01806     assert(Abbrev.getChildrenFlag() == DW_CHILDREN_yes &&
01807            "Children flag not set");
01808     
01809     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
01810       Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
01811     }
01812     
01813     // End of children marker.
01814     Offset += sizeof(int8_t);
01815   }
01816 
01817   Die->setSize(Offset - Die->getOffset());
01818   return Offset;
01819 }
01820 
01821 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
01822 ///
01823 void DwarfWriter::SizeAndOffsets() {
01824   
01825   // Process each compile unit.
01826   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
01827     CompileUnit *Unit = CompileUnits[i];
01828     if (Unit->hasContent()) {
01829       // Compute size of compile unit header
01830       unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
01831                         sizeof(int16_t) + // DWARF version number
01832                         sizeof(int32_t) + // Offset Into Abbrev. Section
01833                         sizeof(int8_t);   // Pointer Size (in bytes)
01834       SizeAndOffsetDie(Unit->getDie(), Offset, (i + 1) == N);
01835     }
01836   }
01837 }
01838 
01839 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
01840 /// frame.
01841 void DwarfWriter::EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
01842                                  std::vector<MachineMove *> &Moves) {
01843   for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
01844     MachineMove *Move = Moves[i];
01845     unsigned LabelID = Move->getLabelID();
01846     const MachineLocation &Dst = Move->getDestination();
01847     const MachineLocation &Src = Move->getSource();
01848     
01849     // Advance row if new location.
01850     if (BaseLabel && LabelID && BaseLabelID != LabelID) {
01851       EmitULEB128Bytes(DW_CFA_advance_loc4);
01852       EOL("DW_CFA_advance_loc4");
01853       EmitDifference("loc", LabelID, BaseLabel, BaseLabelID);
01854       EOL("");
01855       
01856       BaseLabelID = LabelID;
01857       BaseLabel = "loc";
01858     }
01859     
01860     // If advancing cfa.
01861     if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
01862       if (!Src.isRegister()) {
01863         if (Src.getRegister() == MachineLocation::VirtualFP) {
01864           EmitULEB128Bytes(DW_CFA_def_cfa_offset);
01865           EOL("DW_CFA_def_cfa_offset");
01866         } else {
01867           EmitULEB128Bytes(DW_CFA_def_cfa);
01868           EOL("DW_CFA_def_cfa");
01869           
01870           EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
01871           EOL("Register");
01872         }
01873         
01874         int stackGrowth =
01875             Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
01876               TargetFrameInfo::StackGrowsUp ?
01877                 AddressSize : -AddressSize;
01878         
01879         EmitULEB128Bytes(Src.getOffset() / stackGrowth);
01880         EOL("Offset");
01881       } else {
01882       }
01883     } else {
01884     }
01885   }
01886 }
01887 
01888 /// EmitDebugInfo - Emit the debug info section.
01889 ///
01890 void DwarfWriter::EmitDebugInfo() const {
01891   // Start debug info section.
01892   Asm->SwitchToDataSection(DwarfInfoSection, 0);
01893   
01894   // Process each compile unit.
01895   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
01896     CompileUnit *Unit = CompileUnits[i];
01897     
01898     if (Unit->hasContent()) {
01899       DIE *Die = Unit->getDie();
01900       // Emit the compile units header.
01901       EmitLabel("info_begin", Unit->getID());
01902       // Emit size of content not including length itself
01903       unsigned ContentSize = Die->getSize() +
01904                              sizeof(int16_t) + // DWARF version number
01905                              sizeof(int32_t) + // Offset Into Abbrev. Section
01906                              sizeof(int8_t);   // Pointer Size (in bytes)
01907                              
01908       EmitInt32(ContentSize);  EOL("Length of Compilation Unit Info");
01909       EmitInt16(DWARF_VERSION); EOL("DWARF version number");
01910       EmitDifference("abbrev_begin", 0, "section_abbrev", 0);
01911       EOL("Offset Into Abbrev. Section");
01912       EmitInt8(AddressSize); EOL("Address Size (in bytes)");
01913     
01914       EmitDIE(Die);
01915       EmitLabel("info_end", Unit->getID());
01916     }
01917     
01918     O << "\n";
01919   }
01920 }
01921 
01922 /// EmitAbbreviations - Emit the abbreviation section.
01923 ///
01924 void DwarfWriter::EmitAbbreviations() const {
01925   // Check to see if it is worth the effort.
01926   if (!Abbreviations.empty()) {
01927     // Start the debug abbrev section.
01928     Asm->SwitchToDataSection(DwarfAbbrevSection, 0);
01929     
01930     EmitLabel("abbrev_begin", 0);
01931     
01932     // For each abbrevation.
01933     for (unsigned AbbrevID = 1, NAID = Abbreviations.size();
01934                   AbbrevID <= NAID; ++AbbrevID) {
01935       // Get abbreviation data
01936       const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
01937       
01938       // Emit the abbrevations code (base 1 index.)
01939       EmitULEB128Bytes(AbbrevID); EOL("Abbreviation Code");
01940       
01941       // Emit the abbreviations data.
01942       Abbrev.Emit(*this);
01943   
01944       O << "\n";
01945     }
01946     
01947     EmitLabel("abbrev_end", 0);
01948   
01949     O << "\n";
01950   }
01951 }
01952 
01953 /// EmitDebugLines - Emit source line information.
01954 ///
01955 void DwarfWriter::EmitDebugLines() const {
01956   // Minimum line delta, thus ranging from -10..(255-10).
01957   const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
01958   // Maximum line delta, thus ranging from -10..(255-10).
01959   const int MaxLineDelta = 255 + MinLineDelta;
01960 
01961   // Start the dwarf line section.
01962   Asm->SwitchToDataSection(DwarfLineSection, 0);
01963   
01964   // Construct the section header.
01965   
01966   EmitDifference("line_end", 0, "line_begin", 0);
01967   EOL("Length of Source Line Info");
01968   EmitLabel("line_begin", 0);
01969   
01970   EmitInt16(DWARF_VERSION); EOL("DWARF version number");
01971   
01972   EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0);
01973   EOL("Prolog Length");
01974   EmitLabel("line_prolog_begin", 0);
01975   
01976   EmitInt8(1); EOL("Minimum Instruction Length");
01977 
01978   EmitInt8(1); EOL("Default is_stmt_start flag");
01979 
01980   EmitInt8(MinLineDelta);  EOL("Line Base Value (Special Opcodes)");
01981   
01982   EmitInt8(MaxLineDelta); EOL("Line Range Value (Special Opcodes)");
01983 
01984   EmitInt8(-MinLineDelta); EOL("Special Opcode Base");
01985   
01986   // Line number standard opcode encodings argument count
01987   EmitInt8(0); EOL("DW_LNS_copy arg count");
01988   EmitInt8(1); EOL("DW_LNS_advance_pc arg count");
01989   EmitInt8(1); EOL("DW_LNS_advance_line arg count");
01990   EmitInt8(1); EOL("DW_LNS_set_file arg count");
01991   EmitInt8(1); EOL("DW_LNS_set_column arg count");
01992   EmitInt8(0); EOL("DW_LNS_negate_stmt arg count");
01993   EmitInt8(0); EOL("DW_LNS_set_basic_block arg count");
01994   EmitInt8(0); EOL("DW_LNS_const_add_pc arg count");
01995   EmitInt8(1); EOL("DW_LNS_fixed_advance_pc arg count");
01996 
01997   const UniqueVector<std::string> &Directories = DebugInfo->getDirectories();
01998   const UniqueVector<SourceFileInfo> &SourceFiles = DebugInfo->getSourceFiles();
01999 
02000   // Emit directories.
02001   for (unsigned DirectoryID = 1, NDID = Directories.size();
02002                 DirectoryID <= NDID; ++DirectoryID) {
02003     EmitString(Directories[DirectoryID]); EOL("Directory");
02004   }
02005   EmitInt8(0); EOL("End of directories");
02006   
02007   // Emit files.
02008   for (unsigned SourceID = 1, NSID = SourceFiles.size();
02009                SourceID <= NSID; ++SourceID) {
02010     const SourceFileInfo &SourceFile = SourceFiles[SourceID];
02011     EmitString(SourceFile.getName()); EOL("Source");
02012     EmitULEB128Bytes(SourceFile.getDirectoryID());  EOL("Directory #");
02013     EmitULEB128Bytes(0);  EOL("Mod date");
02014     EmitULEB128Bytes(0);  EOL("File size");
02015   }
02016   EmitInt8(0); EOL("End of files");
02017   
02018   EmitLabel("line_prolog_end", 0);
02019   
02020   // A sequence for each text section.
02021   for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
02022     // Isolate current sections line info.
02023     const std::vector<SourceLineInfo *> &LineInfos = SectionSourceLines[j];
02024     
02025     if (DwarfVerbose) {
02026       O << "\t"
02027         << Asm->CommentString << " "
02028         << "Section "
02029         << SectionMap[j + 1].c_str() << "\n";
02030     }
02031 
02032     // Dwarf assumes we start with first line of first source file.
02033     unsigned Source = 1;
02034     unsigned Line = 1;
02035     
02036     // Construct rows of the address, source, line, column matrix.
02037     for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
02038       SourceLineInfo *LineInfo = LineInfos[i];
02039       
02040       if (DwarfVerbose) {
02041         unsigned SourceID = LineInfo->getSourceID();
02042         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
02043         unsigned DirectoryID = SourceFile.getDirectoryID();
02044         O << "\t"
02045           << Asm->CommentString << " "
02046           << Directories[DirectoryID]
02047           << SourceFile.getName() << ":"
02048           << LineInfo->getLine() << "\n"; 
02049       }
02050 
02051       // Define the line address.
02052       EmitInt8(0); EOL("Extended Op");
02053       EmitInt8(4 + 1); EOL("Op size");
02054       EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
02055       EmitReference("loc",  LineInfo->getLabelID()); EOL("Location label");
02056       
02057       // If change of source, then switch to the new source.
02058       if (Source != LineInfo->getSourceID()) {
02059         Source = LineInfo->getSourceID();
02060         EmitInt8(DW_LNS_set_file); EOL("DW_LNS_set_file");
02061         EmitULEB128Bytes(Source); EOL("New Source");
02062       }
02063       
02064       // If change of line.
02065       if (Line != LineInfo->getLine()) {
02066         // Determine offset.
02067         int Offset = LineInfo->getLine() - Line;
02068         int Delta = Offset - MinLineDelta;
02069         
02070         // Update line.
02071         Line = LineInfo->getLine();
02072         
02073         // If delta is small enough and in range...
02074         if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
02075           // ... then use fast opcode.
02076           EmitInt8(Delta - MinLineDelta); EOL("Line Delta");
02077         } else {
02078           // ... otherwise use long hand.
02079           EmitInt8(DW_LNS_advance_line); EOL("DW_LNS_advance_line");
02080           EmitSLEB128Bytes(Offset); EOL("Line Offset");
02081           EmitInt8(DW_LNS_copy); EOL("DW_LNS_copy");
02082         }
02083       } else {
02084         // Copy the previous row (different address or source)
02085         EmitInt8(DW_LNS_copy); EOL("DW_LNS_copy");
02086       }
02087     }
02088 
02089     // Define last address of section.
02090     EmitInt8(0); EOL("Extended Op");
02091     EmitInt8(4 + 1); EOL("Op size");
02092     EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
02093     EmitReference("section_end", j + 1); EOL("Section end label");
02094 
02095     // Mark end of matrix.
02096     EmitInt8(0); EOL("DW_LNE_end_sequence");
02097     EmitULEB128Bytes(1);  O << "\n";
02098     EmitInt8(1); O << "\n";
02099   }
02100   
02101   EmitLabel("line_end", 0);
02102   
02103   O << "\n";
02104 }
02105   
02106 /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
02107 ///
02108 void DwarfWriter::EmitInitialDebugFrame() {
02109   int stackGrowth =
02110       Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
02111         TargetFrameInfo::StackGrowsUp ?
02112       AddressSize : -AddressSize;
02113 
02114   // Start the dwarf frame section.
02115   Asm->SwitchToDataSection(DwarfFrameSection, 0);
02116 
02117   EmitLabel("frame_common", 0);
02118   EmitDifference("frame_common_end", 0,
02119                  "frame_common_begin", 0);
02120   EOL("Length of Common Information Entry");
02121 
02122   EmitLabel("frame_common_begin", 0);
02123   EmitInt32(DW_CIE_ID); EOL("CIE Identifier Tag");
02124   EmitInt8(DW_CIE_VERSION); EOL("CIE Version");
02125   EmitString("");  EOL("CIE Augmentation");
02126   EmitULEB128Bytes(1); EOL("CIE Code Alignment Factor");
02127   EmitSLEB128Bytes(stackGrowth); EOL("CIE Data Alignment Factor");   
02128   EmitInt8(RI->getDwarfRegNum(RI->getRARegister())); EOL("CIE RA Column");
02129   
02130   std::vector<MachineMove *> Moves;
02131   RI->getInitialFrameState(Moves);
02132   EmitFrameMoves(NULL, 0, Moves);
02133   for (unsigned i = 0, N = Moves.size(); i < N; ++i) delete Moves[i];
02134 
02135   EmitAlign(2);
02136   EmitLabel("frame_common_end", 0);
02137   
02138   O << "\n";
02139 }
02140 
02141 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
02142 /// section.
02143 void DwarfWriter::EmitFunctionDebugFrame() {
02144   // Start the dwarf frame section.
02145   Asm->SwitchToDataSection(DwarfFrameSection, 0);
02146   
02147   EmitDifference("frame_end", SubprogramCount,
02148                  "frame_begin", SubprogramCount);
02149   EOL("Length of Frame Information Entry");
02150   
02151   EmitLabel("frame_begin", SubprogramCount);
02152   
02153   EmitDifference("frame_common", 0, "section_frame", 0);
02154   EOL("FDE CIE offset");
02155 
02156   EmitReference("func_begin", SubprogramCount); EOL("FDE initial location");
02157   EmitDifference("func_end", SubprogramCount,
02158                  "func_begin", SubprogramCount);
02159   EOL("FDE address range");
02160   
02161   std::vector<MachineMove *> &Moves = DebugInfo->getFrameMoves();
02162   
02163   EmitFrameMoves("func_begin", SubprogramCount, Moves);
02164   
02165   EmitAlign(2);
02166   EmitLabel("frame_end", SubprogramCount);
02167 
02168   O << "\n";
02169 }
02170 
02171 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
02172 ///
02173 void DwarfWriter::EmitDebugPubNames() {
02174   // Start the dwarf pubnames section.
02175   Asm->SwitchToDataSection(DwarfPubNamesSection, 0);
02176     
02177   // Process each compile unit.
02178   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
02179     CompileUnit *Unit = CompileUnits[i];
02180     
02181     if (Unit->hasContent()) {
02182       EmitDifference("pubnames_end", Unit->getID(),
02183                      "pubnames_begin", Unit->getID());
02184       EOL("Length of Public Names Info");
02185       
02186       EmitLabel("pubnames_begin", Unit->getID());
02187       
02188       EmitInt16(DWARF_VERSION); EOL("DWARF Version");
02189       
02190       EmitDifference("info_begin", Unit->getID(), "section_info", 0);
02191       EOL("Offset of Compilation Unit Info");
02192 
02193       EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID());
02194       EOL("Compilation Unit Length");
02195       
02196       std::map<std::string, DIE *> &Globals = Unit->getGlobals();
02197       
02198       for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
02199                                                   GE = Globals.end();
02200            GI != GE; ++GI) {
02201         const std::string &Name = GI->first;
02202         DIE * Entity = GI->second;
02203         
02204         EmitInt32(Entity->getOffset()); EOL("DIE offset");
02205         EmitString(Name); EOL("External Name");
02206       }
02207     
02208       EmitInt32(0); EOL("End Mark");
02209       EmitLabel("pubnames_end", Unit->getID());
02210     
02211       O << "\n";
02212     }
02213   }
02214 }
02215 
02216 /// EmitDebugStr - Emit visible names into a debug str section.
02217 ///
02218 void DwarfWriter::EmitDebugStr() {
02219   // Check to see if it is worth the effort.
02220   if (!StringPool.empty()) {
02221     // Start the dwarf str section.
02222     Asm->SwitchToDataSection(DwarfStrSection, 0);
02223     
02224     // For each of strings in the string pool.
02225     for (unsigned StringID = 1, N = StringPool.size();
02226          StringID <= N; ++StringID) {
02227       // Emit a label for reference from debug information entries.
02228       EmitLabel("string", StringID);
02229       // Emit the string itself.
02230       const std::string &String = StringPool[StringID];
02231       EmitString(String); O << "\n";
02232     }
02233   
02234     O << "\n";
02235   }
02236 }
02237 
02238 /// EmitDebugLoc - Emit visible names into a debug loc section.
02239 ///
02240 void DwarfWriter::EmitDebugLoc() {
02241   // Start the dwarf loc section.
02242   Asm->SwitchToDataSection(DwarfLocSection, 0);
02243   
02244   O << "\n";
02245 }
02246 
02247 /// EmitDebugARanges - Emit visible names into a debug aranges section.
02248 ///
02249 void DwarfWriter::EmitDebugARanges() {
02250   // Start the dwarf aranges section.
02251   Asm->SwitchToDataSection(DwarfARangesSection, 0);
02252   
02253   // FIXME - Mock up
02254 #if 0
02255   // Process each compile unit.
02256   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
02257     CompileUnit *Unit = CompileUnits[i];
02258     
02259     if (Unit->hasContent()) {
02260       // Don't include size of length
02261       EmitInt32(0x1c); EOL("Length of Address Ranges Info");
02262       
02263       EmitInt16(DWARF_VERSION); EOL("Dwarf Version");
02264       
02265       EmitReference("info_begin", Unit->getID());
02266       EOL("Offset of Compilation Unit Info");
02267 
02268       EmitInt8(AddressSize); EOL("Size of Address");
02269 
02270       EmitInt8(0); EOL("Size of Segment Descriptor");
02271 
02272       EmitInt16(0);  EOL("Pad (1)");
02273       EmitInt16(0);  EOL("Pad (2)");
02274 
02275       // Range 1
02276       EmitReference("text_begin", 0); EOL("Address");
02277       EmitDifference("text_end", 0, "text_begin", 0); EOL("Length");
02278 
02279       EmitInt32(0); EOL("EOM (1)");
02280       EmitInt32(0); EOL("EOM (2)");
02281       
02282       O << "\n";
02283     }
02284   }
02285 #endif
02286 }
02287 
02288 /// EmitDebugRanges - Emit visible names into a debug ranges section.
02289 ///
02290 void DwarfWriter::EmitDebugRanges() {
02291   // Start the dwarf ranges section.
02292   Asm->SwitchToDataSection(DwarfRangesSection, 0);
02293   
02294   O << "\n";
02295 }
02296 
02297 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
02298 ///
02299 void DwarfWriter::EmitDebugMacInfo() {
02300   // Start the dwarf macinfo section.
02301   Asm->SwitchToDataSection(DwarfMacInfoSection, 0);
02302   
02303   O << "\n";
02304 }
02305 
02306 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
02307 /// header file.
02308 void DwarfWriter::ConstructCompileUnitDIEs() {
02309   const UniqueVector<CompileUnitDesc *> CUW = DebugInfo->getCompileUnits();
02310   
02311   for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
02312     CompileUnit *Unit = NewCompileUnit(CUW[i], i);
02313     CompileUnits.push_back(Unit);
02314   }
02315 }
02316 
02317 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible global
02318 /// variables.
02319 void DwarfWriter::ConstructGlobalDIEs() {
02320   std::vector<GlobalVariableDesc *> GlobalVariables =
02321       DebugInfo->getAnchoredDescriptors<GlobalVariableDesc>(*M);
02322   
02323   for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
02324     GlobalVariableDesc *GVD = GlobalVariables[i];
02325     NewGlobalVariable(GVD);
02326   }
02327 }
02328 
02329 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
02330 /// subprograms.
02331 void DwarfWriter::ConstructSubprogramDIEs() {
02332   std::vector<SubprogramDesc *> Subprograms =
02333       DebugInfo->getAnchoredDescriptors<SubprogramDesc>(*M);
02334   
02335   for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
02336     SubprogramDesc *SPD = Subprograms[i];
02337     NewSubprogram(SPD);
02338   }
02339 }
02340 
02341 //===----------------------------------------------------------------------===//
02342 // Main entry points.
02343 //
02344   
02345 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A)
02346 : O(OS)
02347 , Asm(A)
02348 , TD(Asm->TM.getTargetData())
02349 , RI(Asm->TM.getRegisterInfo())
02350 , M(NULL)
02351 , MF(NULL)
02352 , DebugInfo(NULL)
02353 , didInitial(false)
02354 , shouldEmit(false)
02355 , SubprogramCount(0)
02356 , CompileUnits()
02357 , Abbreviations()
02358 , StringPool()
02359 , DescToUnitMap()
02360 , DescToDieMap()
02361 , SectionMap()
02362 , SectionSourceLines()
02363 , AddressSize(sizeof(int32_t))
02364 , hasLEB128(false)
02365 , hasDotLoc(false)
02366 , hasDotFile(false)
02367 , needsSet(false)
02368 , DwarfAbbrevSection(".debug_abbrev")
02369 , DwarfInfoSection(".debug_info")
02370 , DwarfLineSection(".debug_line")
02371 , DwarfFrameSection(".debug_frame")
02372 , DwarfPubNamesSection(".debug_pubnames")
02373 , DwarfPubTypesSection(".debug_pubtypes")
02374 , DwarfStrSection(".debug_str")
02375 , DwarfLocSection(".debug_loc")
02376 , DwarfARangesSection(".debug_aranges")
02377 , DwarfRangesSection(".debug_ranges")
02378 , DwarfMacInfoSection(".debug_macinfo")
02379 , TextSection(".text")
02380 , DataSection(".data")
02381 {}
02382 DwarfWriter::~DwarfWriter() {
02383   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
02384     delete CompileUnits[i];
02385   }
02386 }
02387 
02388 /// SetDebugInfo - Set DebugInfo when it's known that pass manager has
02389 /// created it.  Set by the target AsmPrinter.
02390 void DwarfWriter::SetDebugInfo(MachineDebugInfo *DI) {
02391   // Make sure initial declarations are made.
02392   if (!DebugInfo && DI->hasInfo()) {
02393     DebugInfo = DI;
02394     shouldEmit = true;
02395     
02396     // Emit initial sections
02397     EmitInitial();
02398   
02399     // Create all the compile unit DIEs.
02400     ConstructCompileUnitDIEs();
02401     
02402     // Create DIEs for each of the externally visible global variables.
02403     ConstructGlobalDIEs();
02404 
02405     // Create DIEs for each of the externally visible subprograms.
02406     ConstructSubprogramDIEs();
02407     
02408     // Prime section data.
02409     SectionMap.insert(std::string("\t") + TextSection);
02410   }
02411 }
02412 
02413 /// BeginModule - Emit all Dwarf sections that should come prior to the content.
02414 ///
02415 void DwarfWriter::BeginModule(Module *M) {
02416   this->M = M;
02417   
02418   if (!ShouldEmitDwarf()) return;
02419   EOL("Dwarf Begin Module");
02420 }
02421 
02422 /// EndModule - Emit all Dwarf sections that should come after the content.
02423 ///
02424 void DwarfWriter::EndModule() {
02425   if (!ShouldEmitDwarf()) return;
02426   EOL("Dwarf End Module");
02427   
02428   // Standard sections final addresses.
02429   Asm->SwitchToTextSection(TextSection, 0);
02430   EmitLabel("text_end", 0);
02431   Asm->SwitchToDataSection(DataSection, 0);
02432   EmitLabel("data_end", 0);
02433   
02434   // End text sections.
02435   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
02436     Asm->SwitchToTextSection(SectionMap[i].c_str(), 0);
02437     EmitLabel("section_end", i);
02438   }
02439   
02440   // Compute DIE offsets and sizes.
02441   SizeAndOffsets();
02442   
02443   // Emit all the DIEs into a debug info section
02444   EmitDebugInfo();
02445   
02446   // Corresponding abbreviations into a abbrev section.
02447   EmitAbbreviations();
02448   
02449   // Emit source line correspondence into a debug line section.
02450   EmitDebugLines();
02451   
02452   // Emit info into a debug pubnames section.
02453   EmitDebugPubNames();
02454   
02455   // Emit info into a debug str section.
02456   EmitDebugStr();
02457   
02458   // Emit info into a debug loc section.
02459   EmitDebugLoc();
02460   
02461   // Emit info into a debug aranges section.
02462   EmitDebugARanges();
02463   
02464   // Emit info into a debug ranges section.
02465   EmitDebugRanges();
02466   
02467   // Emit info into a debug macinfo section.
02468   EmitDebugMacInfo();
02469 }
02470 
02471 /// BeginFunction - Gather pre-function debug information.  Assumes being 
02472 /// emitted immediately after the function entry point.
02473 void DwarfWriter::BeginFunction(MachineFunction *MF) {
02474   this->MF = MF;
02475   
02476   if (!ShouldEmitDwarf()) return;
02477   EOL("Dwarf Begin Function");
02478 
02479   // Begin accumulating function debug information.
02480   DebugInfo->BeginFunction(MF);
02481   
02482   // Assumes in correct section after the entry point.
02483   EmitLabel("func_begin", ++SubprogramCount);
02484 }
02485 
02486 /// EndFunction - Gather and emit post-function debug information.
02487 ///
02488 void DwarfWriter::EndFunction() {
02489   if (!ShouldEmitDwarf()) return;
02490   EOL("Dwarf End Function");
02491   
02492   // Define end label for subprogram.
02493   EmitLabel("func_end", SubprogramCount);
02494     
02495   // Get function line info.
02496   std::vector<SourceLineInfo *> &LineInfos = DebugInfo->getSourceLines();
02497 
02498   if (!LineInfos.empty()) {
02499     // Get section line info.
02500     unsigned ID = SectionMap.insert(Asm->CurrentSection);
02501     if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
02502     std::vector<SourceLineInfo *> &SectionLineInfos =SectionSourceLines[ID-1];
02503     // Append the function info to section info.
02504     SectionLineInfos.insert(SectionLineInfos.end(),
02505                             LineInfos.begin(), LineInfos.end());
02506   }
02507   
02508   // Construct scopes for subprogram.
02509   ConstructRootScope(DebugInfo->getRootScope());
02510   
02511   // Emit function frame information.
02512   EmitFunctionDebugFrame();
02513   
02514   // Reset the line numbers for the next function.
02515   LineInfos.clear();
02516 
02517   // Clear function debug information.
02518   DebugInfo->EndFunction();
02519 }