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 is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains support for writing dwarf info into asm files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/DwarfWriter.h"
00015 
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/FoldingSet.h"
00018 #include "llvm/ADT/StringExtras.h"
00019 #include "llvm/ADT/UniqueVector.h"
00020 #include "llvm/Module.h"
00021 #include "llvm/DerivedTypes.h"
00022 #include "llvm/Constants.h"
00023 #include "llvm/CodeGen/AsmPrinter.h"
00024 #include "llvm/CodeGen/MachineModuleInfo.h"
00025 #include "llvm/CodeGen/MachineFrameInfo.h"
00026 #include "llvm/CodeGen/MachineLocation.h"
00027 #include "llvm/Analysis/DebugInfo.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/Dwarf.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Support/DataTypes.h"
00032 #include "llvm/Support/Mangler.h"
00033 #include "llvm/Support/raw_ostream.h"
00034 #include "llvm/System/Path.h"
00035 #include "llvm/Target/TargetAsmInfo.h"
00036 #include "llvm/Target/TargetRegisterInfo.h"
00037 #include "llvm/Target/TargetData.h"
00038 #include "llvm/Target/TargetFrameInfo.h"
00039 #include "llvm/Target/TargetInstrInfo.h"
00040 #include "llvm/Target/TargetMachine.h"
00041 #include "llvm/Target/TargetOptions.h"
00042 #include <ostream>
00043 #include <string>
00044 using namespace llvm;
00045 using namespace llvm::dwarf;
00046 
00047 static RegisterPass<DwarfWriter>
00048 X("dwarfwriter", "DWARF Information Writer");
00049 char DwarfWriter::ID = 0;
00050 
00051 namespace llvm {
00052 
00053 //===----------------------------------------------------------------------===//
00054 
00055 /// Configuration values for initial hash set sizes (log2).
00056 ///
00057 static const unsigned InitDiesSetSize          = 9; // 512
00058 static const unsigned InitAbbreviationsSetSize = 9; // 512
00059 static const unsigned InitValuesSetSize        = 9; // 512
00060 
00061 //===----------------------------------------------------------------------===//
00062 /// Forward declarations.
00063 ///
00064 class DIE;
00065 class DIEValue;
00066 
00067 //===----------------------------------------------------------------------===//
00068 /// Utility routines.
00069 ///
00070 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
00071 /// specified value in their initializer somewhere.
00072 static void
00073 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
00074   // Scan though value users. 
00075   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
00076     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
00077       // If the user is a GlobalVariable then add to result. 
00078       Result.push_back(GV);
00079     } else if (Constant *C = dyn_cast<Constant>(*I)) {
00080       // If the user is a constant variable then scan its users.
00081       getGlobalVariablesUsing(C, Result);
00082     }
00083   }
00084 }
00085 
00086 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
00087 /// named GlobalVariable. 
00088 static void
00089 getGlobalVariablesUsing(Module &M, const std::string &RootName,
00090                         std::vector<GlobalVariable*> &Result) {
00091   std::vector<const Type*> FieldTypes;
00092   FieldTypes.push_back(Type::Int32Ty);
00093   FieldTypes.push_back(Type::Int32Ty);
00094 
00095   // Get the GlobalVariable root.
00096   GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
00097                                                 StructType::get(FieldTypes));
00098 
00099   // If present and linkonce then scan for users.
00100   if (UseRoot && UseRoot->hasLinkOnceLinkage())
00101     getGlobalVariablesUsing(UseRoot, Result);
00102 }
00103 
00104 /// getGlobalVariable - Return either a direct or cast Global value.
00105 ///
00106 static GlobalVariable *getGlobalVariable(Value *V) {
00107   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
00108     return GV;
00109   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00110     if (CE->getOpcode() == Instruction::BitCast) {
00111       return dyn_cast<GlobalVariable>(CE->getOperand(0));
00112     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
00113       for (unsigned int i=1; i<CE->getNumOperands(); i++) {
00114         if (!CE->getOperand(i)->isNullValue())
00115           return NULL;
00116       }
00117       return dyn_cast<GlobalVariable>(CE->getOperand(0));
00118     }
00119   }
00120   return NULL;
00121 }
00122 
00123 //===----------------------------------------------------------------------===//
00124 /// DWLabel - Labels are used to track locations in the assembler file.
00125 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
00126 /// where the tag is a category of label (Ex. location) and number is a value
00127 /// unique in that category.
00128 class DWLabel {
00129 public:
00130   /// Tag - Label category tag. Should always be a staticly declared C string.
00131   ///
00132   const char *Tag;
00133 
00134   /// Number - Value to make label unique.
00135   ///
00136   unsigned    Number;
00137 
00138   DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
00139 
00140   void Profile(FoldingSetNodeID &ID) const {
00141     ID.AddString(std::string(Tag));
00142     ID.AddInteger(Number);
00143   }
00144 
00145 #ifndef NDEBUG
00146   void print(std::ostream *O) const {
00147     if (O) print(*O);
00148   }
00149   void print(std::ostream &O) const {
00150     O << "." << Tag;
00151     if (Number) O << Number;
00152   }
00153 #endif
00154 };
00155 
00156 //===----------------------------------------------------------------------===//
00157 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
00158 /// Dwarf abbreviation.
00159 class DIEAbbrevData {
00160 private:
00161   /// Attribute - Dwarf attribute code.
00162   ///
00163   unsigned Attribute;
00164 
00165   /// Form - Dwarf form code.
00166   ///
00167   unsigned Form;
00168 
00169 public:
00170   DIEAbbrevData(unsigned A, unsigned F)
00171   : Attribute(A)
00172   , Form(F)
00173   {}
00174 
00175   // Accessors.
00176   unsigned getAttribute() const { return Attribute; }
00177   unsigned getForm()      const { return Form; }
00178 
00179   /// Profile - Used to gather unique data for the abbreviation folding set.
00180   ///
00181   void Profile(FoldingSetNodeID &ID)const  {
00182     ID.AddInteger(Attribute);
00183     ID.AddInteger(Form);
00184   }
00185 };
00186 
00187 //===----------------------------------------------------------------------===//
00188 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
00189 /// information object.
00190 class DIEAbbrev : public FoldingSetNode {
00191 private:
00192   /// Tag - Dwarf tag code.
00193   ///
00194   unsigned Tag;
00195 
00196   /// Unique number for node.
00197   ///
00198   unsigned Number;
00199 
00200   /// ChildrenFlag - Dwarf children flag.
00201   ///
00202   unsigned ChildrenFlag;
00203 
00204   /// Data - Raw data bytes for abbreviation.
00205   ///
00206   SmallVector<DIEAbbrevData, 8> Data;
00207 
00208 public:
00209 
00210   DIEAbbrev(unsigned T, unsigned C)
00211   : Tag(T)
00212   , ChildrenFlag(C)
00213   , Data()
00214   {}
00215   ~DIEAbbrev() {}
00216 
00217   // Accessors.
00218   unsigned getTag()                           const { return Tag; }
00219   unsigned getNumber()                        const { return Number; }
00220   unsigned getChildrenFlag()                  const { return ChildrenFlag; }
00221   const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
00222   void setTag(unsigned T)                           { Tag = T; }
00223   void setChildrenFlag(unsigned CF)                 { ChildrenFlag = CF; }
00224   void setNumber(unsigned N)                        { Number = N; }
00225 
00226   /// AddAttribute - Adds another set of attribute information to the
00227   /// abbreviation.
00228   void AddAttribute(unsigned Attribute, unsigned Form) {
00229     Data.push_back(DIEAbbrevData(Attribute, Form));
00230   }
00231 
00232   /// AddFirstAttribute - Adds a set of attribute information to the front
00233   /// of the abbreviation.
00234   void AddFirstAttribute(unsigned Attribute, unsigned Form) {
00235     Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
00236   }
00237 
00238   /// Profile - Used to gather unique data for the abbreviation folding set.
00239   ///
00240   void Profile(FoldingSetNodeID &ID) {
00241     ID.AddInteger(Tag);
00242     ID.AddInteger(ChildrenFlag);
00243 
00244     // For each attribute description.
00245     for (unsigned i = 0, N = Data.size(); i < N; ++i)
00246       Data[i].Profile(ID);
00247   }
00248 
00249   /// Emit - Print the abbreviation using the specified Dwarf writer.
00250   ///
00251   void Emit(const DwarfDebug &DD) const;
00252 
00253 #ifndef NDEBUG
00254   void print(std::ostream *O) {
00255     if (O) print(*O);
00256   }
00257   void print(std::ostream &O);
00258   void dump();
00259 #endif
00260 };
00261 
00262 //===----------------------------------------------------------------------===//
00263 /// DIE - A structured debug information entry.  Has an abbreviation which
00264 /// describes it's organization.
00265 class DIE : public FoldingSetNode {
00266 protected:
00267   /// Abbrev - Buffer for constructing abbreviation.
00268   ///
00269   DIEAbbrev Abbrev;
00270 
00271   /// Offset - Offset in debug info section.
00272   ///
00273   unsigned Offset;
00274 
00275   /// Size - Size of instance + children.
00276   ///
00277   unsigned Size;
00278 
00279   /// Children DIEs.
00280   ///
00281   std::vector<DIE *> Children;
00282 
00283   /// Attributes values.
00284   ///
00285   SmallVector<DIEValue*, 32> Values;
00286 
00287 public:
00288   explicit DIE(unsigned Tag)
00289   : Abbrev(Tag, DW_CHILDREN_no)
00290   , Offset(0)
00291   , Size(0)
00292   , Children()
00293   , Values()
00294   {}
00295   virtual ~DIE();
00296 
00297   // Accessors.
00298   DIEAbbrev &getAbbrev()                           { return Abbrev; }
00299   unsigned   getAbbrevNumber()               const {
00300     return Abbrev.getNumber();
00301   }
00302   unsigned getTag()                          const { return Abbrev.getTag(); }
00303   unsigned getOffset()                       const { return Offset; }
00304   unsigned getSize()                         const { return Size; }
00305   const std::vector<DIE *> &getChildren()    const { return Children; }
00306   SmallVector<DIEValue*, 32> &getValues()       { return Values; }
00307   void setTag(unsigned Tag)                  { Abbrev.setTag(Tag); }
00308   void setOffset(unsigned O)                 { Offset = O; }
00309   void setSize(unsigned S)                   { Size = S; }
00310 
00311   /// AddValue - Add a value and attributes to a DIE.
00312   ///
00313   void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
00314     Abbrev.AddAttribute(Attribute, Form);
00315     Values.push_back(Value);
00316   }
00317 
00318   /// SiblingOffset - Return the offset of the debug information entry's
00319   /// sibling.
00320   unsigned SiblingOffset() const { return Offset + Size; }
00321 
00322   /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
00323   ///
00324   void AddSiblingOffset();
00325 
00326   /// AddChild - Add a child to the DIE.
00327   ///
00328   void AddChild(DIE *Child) {
00329     Abbrev.setChildrenFlag(DW_CHILDREN_yes);
00330     Children.push_back(Child);
00331   }
00332 
00333   /// Detach - Detaches objects connected to it after copying.
00334   ///
00335   void Detach() {
00336     Children.clear();
00337   }
00338 
00339   /// Profile - Used to gather unique data for the value folding set.
00340   ///
00341   void Profile(FoldingSetNodeID &ID) ;
00342 
00343 #ifndef NDEBUG
00344   void print(std::ostream *O, unsigned IncIndent = 0) {
00345     if (O) print(*O, IncIndent);
00346   }
00347   void print(std::ostream &O, unsigned IncIndent = 0);
00348   void dump();
00349 #endif
00350 };
00351 
00352 //===----------------------------------------------------------------------===//
00353 /// DIEValue - A debug information entry value.
00354 ///
00355 class DIEValue : public FoldingSetNode {
00356 public:
00357   enum {
00358     isInteger,
00359     isString,
00360     isLabel,
00361     isAsIsLabel,
00362     isSectionOffset,
00363     isDelta,
00364     isEntry,
00365     isBlock
00366   };
00367 
00368   /// Type - Type of data stored in the value.
00369   ///
00370   unsigned Type;
00371 
00372   explicit DIEValue(unsigned T)
00373   : Type(T)
00374   {}
00375   virtual ~DIEValue() {}
00376 
00377   // Accessors
00378   unsigned getType()  const { return Type; }
00379 
00380   // Implement isa/cast/dyncast.
00381   static bool classof(const DIEValue *) { return true; }
00382 
00383   /// EmitValue - Emit value via the Dwarf writer.
00384   ///
00385   virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
00386 
00387   /// SizeOf - Return the size of a value in bytes.
00388   ///
00389   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
00390 
00391   /// Profile - Used to gather unique data for the value folding set.
00392   ///
00393   virtual void Profile(FoldingSetNodeID &ID) = 0;
00394 
00395 #ifndef NDEBUG
00396   void print(std::ostream *O) {
00397     if (O) print(*O);
00398   }
00399   virtual void print(std::ostream &O) = 0;
00400   void dump();
00401 #endif
00402 };
00403 
00404 //===----------------------------------------------------------------------===//
00405 /// DWInteger - An integer value DIE.
00406 ///
00407 class DIEInteger : public DIEValue {
00408 private:
00409   uint64_t Integer;
00410 
00411 public:
00412   explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
00413 
00414   // Implement isa/cast/dyncast.
00415   static bool classof(const DIEInteger *) { return true; }
00416   static bool classof(const DIEValue *I)  { return I->Type == isInteger; }
00417 
00418   /// BestForm - Choose the best form for integer.
00419   ///
00420   static unsigned BestForm(bool IsSigned, uint64_t Integer) {
00421     if (IsSigned) {
00422       if ((char)Integer == (signed)Integer)   return DW_FORM_data1;
00423       if ((short)Integer == (signed)Integer)  return DW_FORM_data2;
00424       if ((int)Integer == (signed)Integer)    return DW_FORM_data4;
00425     } else {
00426       if ((unsigned char)Integer == Integer)  return DW_FORM_data1;
00427       if ((unsigned short)Integer == Integer) return DW_FORM_data2;
00428       if ((unsigned int)Integer == Integer)   return DW_FORM_data4;
00429     }
00430     return DW_FORM_data8;
00431   }
00432 
00433   /// EmitValue - Emit integer of appropriate size.
00434   ///
00435   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
00436 
00437   /// SizeOf - Determine size of integer value in bytes.
00438   ///
00439   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
00440 
00441   /// Profile - Used to gather unique data for the value folding set.
00442   ///
00443   static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
00444     ID.AddInteger(isInteger);
00445     ID.AddInteger(Integer);
00446   }
00447   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
00448 
00449 #ifndef NDEBUG
00450   virtual void print(std::ostream &O) {
00451     O << "Int: " << (int64_t)Integer
00452       << "  0x" << std::hex << Integer << std::dec;
00453   }
00454 #endif
00455 };
00456 
00457 //===----------------------------------------------------------------------===//
00458 /// DIEString - A string value DIE.
00459 ///
00460 class DIEString : public DIEValue {
00461 public:
00462   const std::string String;
00463 
00464   explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
00465 
00466   // Implement isa/cast/dyncast.
00467   static bool classof(const DIEString *) { return true; }
00468   static bool classof(const DIEValue *S) { return S->Type == isString; }
00469 
00470   /// EmitValue - Emit string value.
00471   ///
00472   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
00473 
00474   /// SizeOf - Determine size of string value in bytes.
00475   ///
00476   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
00477     return String.size() + sizeof(char); // sizeof('\0');
00478   }
00479 
00480   /// Profile - Used to gather unique data for the value folding set.
00481   ///
00482   static void Profile(FoldingSetNodeID &ID, const std::string &String) {
00483     ID.AddInteger(isString);
00484     ID.AddString(String);
00485   }
00486   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
00487 
00488 #ifndef NDEBUG
00489   virtual void print(std::ostream &O) {
00490     O << "Str: \"" << String << "\"";
00491   }
00492 #endif
00493 };
00494 
00495 //===----------------------------------------------------------------------===//
00496 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
00497 //
00498 class DIEDwarfLabel : public DIEValue {
00499 public:
00500 
00501   const DWLabel Label;
00502 
00503   explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
00504 
00505   // Implement isa/cast/dyncast.
00506   static bool classof(const DIEDwarfLabel *)  { return true; }
00507   static bool classof(const DIEValue *L) { return L->Type == isLabel; }
00508 
00509   /// EmitValue - Emit label value.
00510   ///
00511   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
00512 
00513   /// SizeOf - Determine size of label value in bytes.
00514   ///
00515   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
00516 
00517   /// Profile - Used to gather unique data for the value folding set.
00518   ///
00519   static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
00520     ID.AddInteger(isLabel);
00521     Label.Profile(ID);
00522   }
00523   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
00524 
00525 #ifndef NDEBUG
00526   virtual void print(std::ostream &O) {
00527     O << "Lbl: ";
00528     Label.print(O);
00529   }
00530 #endif
00531 };
00532 
00533 
00534 //===----------------------------------------------------------------------===//
00535 /// DIEObjectLabel - A label to an object in code or data.
00536 //
00537 class DIEObjectLabel : public DIEValue {
00538 public:
00539   const std::string Label;
00540 
00541   explicit DIEObjectLabel(const std::string &L)
00542   : DIEValue(isAsIsLabel), Label(L) {}
00543 
00544   // Implement isa/cast/dyncast.
00545   static bool classof(const DIEObjectLabel *) { return true; }
00546   static bool classof(const DIEValue *L)    { return L->Type == isAsIsLabel; }
00547 
00548   /// EmitValue - Emit label value.
00549   ///
00550   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
00551 
00552   /// SizeOf - Determine size of label value in bytes.
00553   ///
00554   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
00555 
00556   /// Profile - Used to gather unique data for the value folding set.
00557   ///
00558   static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
00559     ID.AddInteger(isAsIsLabel);
00560     ID.AddString(Label);
00561   }
00562   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
00563 
00564 #ifndef NDEBUG
00565   virtual void print(std::ostream &O) {
00566     O << "Obj: " << Label;
00567   }
00568 #endif
00569 };
00570 
00571 //===----------------------------------------------------------------------===//
00572 /// DIESectionOffset - A section offset DIE.
00573 //
00574 class DIESectionOffset : public DIEValue {
00575 public:
00576   const DWLabel Label;
00577   const DWLabel Section;
00578   bool IsEH : 1;
00579   bool UseSet : 1;
00580 
00581   DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
00582                    bool isEH = false, bool useSet = true)
00583   : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
00584                                IsEH(isEH), UseSet(useSet) {}
00585 
00586   // Implement isa/cast/dyncast.
00587   static bool classof(const DIESectionOffset *)  { return true; }
00588   static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
00589 
00590   /// EmitValue - Emit section offset.
00591   ///
00592   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
00593 
00594   /// SizeOf - Determine size of section offset value in bytes.
00595   ///
00596   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
00597 
00598   /// Profile - Used to gather unique data for the value folding set.
00599   ///
00600   static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
00601                                             const DWLabel &Section) {
00602     ID.AddInteger(isSectionOffset);
00603     Label.Profile(ID);
00604     Section.Profile(ID);
00605     // IsEH and UseSet are specific to the Label/Section that we will emit
00606     // the offset for; so Label/Section are enough for uniqueness.
00607   }
00608   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
00609 
00610 #ifndef NDEBUG
00611   virtual void print(std::ostream &O) {
00612     O << "Off: ";
00613     Label.print(O);
00614     O << "-";
00615     Section.print(O);
00616     O << "-" << IsEH << "-" << UseSet;
00617   }
00618 #endif
00619 };
00620 
00621 //===----------------------------------------------------------------------===//
00622 /// DIEDelta - A simple label difference DIE.
00623 ///
00624 class DIEDelta : public DIEValue {
00625 public:
00626   const DWLabel LabelHi;
00627   const DWLabel LabelLo;
00628 
00629   DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
00630   : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
00631 
00632   // Implement isa/cast/dyncast.
00633   static bool classof(const DIEDelta *)  { return true; }
00634   static bool classof(const DIEValue *D) { return D->Type == isDelta; }
00635 
00636   /// EmitValue - Emit delta value.
00637   ///
00638   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
00639 
00640   /// SizeOf - Determine size of delta value in bytes.
00641   ///
00642   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
00643 
00644   /// Profile - Used to gather unique data for the value folding set.
00645   ///
00646   static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
00647                                             const DWLabel &LabelLo) {
00648     ID.AddInteger(isDelta);
00649     LabelHi.Profile(ID);
00650     LabelLo.Profile(ID);
00651   }
00652   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
00653 
00654 #ifndef NDEBUG
00655   virtual void print(std::ostream &O) {
00656     O << "Del: ";
00657     LabelHi.print(O);
00658     O << "-";
00659     LabelLo.print(O);
00660   }
00661 #endif
00662 };
00663 
00664 //===----------------------------------------------------------------------===//
00665 /// DIEntry - A pointer to another debug information entry.  An instance of this
00666 /// class can also be used as a proxy for a debug information entry not yet
00667 /// defined (ie. types.)
00668 class DIEntry : public DIEValue {
00669 public:
00670   DIE *Entry;
00671 
00672   explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
00673 
00674   // Implement isa/cast/dyncast.
00675   static bool classof(const DIEntry *)   { return true; }
00676   static bool classof(const DIEValue *E) { return E->Type == isEntry; }
00677 
00678   /// EmitValue - Emit debug information entry offset.
00679   ///
00680   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
00681 
00682   /// SizeOf - Determine size of debug information entry in bytes.
00683   ///
00684   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
00685     return sizeof(int32_t);
00686   }
00687 
00688   /// Profile - Used to gather unique data for the value folding set.
00689   ///
00690   static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
00691     ID.AddInteger(isEntry);
00692     ID.AddPointer(Entry);
00693   }
00694   virtual void Profile(FoldingSetNodeID &ID) {
00695     ID.AddInteger(isEntry);
00696 
00697     if (Entry) {
00698       ID.AddPointer(Entry);
00699     } else {
00700       ID.AddPointer(this);
00701     }
00702   }
00703 
00704 #ifndef NDEBUG
00705   virtual void print(std::ostream &O) {
00706     O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
00707   }
00708 #endif
00709 };
00710 
00711 //===----------------------------------------------------------------------===//
00712 /// DIEBlock - A block of values.  Primarily used for location expressions.
00713 //
00714 class DIEBlock : public DIEValue, public DIE {
00715 public:
00716   unsigned Size;                        // Size in bytes excluding size header.
00717 
00718   DIEBlock()
00719   : DIEValue(isBlock)
00720   , DIE(0)
00721   , Size(0)
00722   {}
00723   ~DIEBlock()  {
00724   }
00725 
00726   // Implement isa/cast/dyncast.
00727   static bool classof(const DIEBlock *)  { return true; }
00728   static bool classof(const DIEValue *E) { return E->Type == isBlock; }
00729 
00730   /// ComputeSize - calculate the size of the block.
00731   ///
00732   unsigned ComputeSize(DwarfDebug &DD);
00733 
00734   /// BestForm - Choose the best form for data.
00735   ///
00736   unsigned BestForm() const {
00737     if ((unsigned char)Size == Size)  return DW_FORM_block1;
00738     if ((unsigned short)Size == Size) return DW_FORM_block2;
00739     if ((unsigned int)Size == Size)   return DW_FORM_block4;
00740     return DW_FORM_block;
00741   }
00742 
00743   /// EmitValue - Emit block data.
00744   ///
00745   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
00746 
00747   /// SizeOf - Determine size of block data in bytes.
00748   ///
00749   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
00750 
00751 
00752   /// Profile - Used to gather unique data for the value folding set.
00753   ///
00754   virtual void Profile(FoldingSetNodeID &ID) {
00755     ID.AddInteger(isBlock);
00756     DIE::Profile(ID);
00757   }
00758 
00759 #ifndef NDEBUG
00760   virtual void print(std::ostream &O) {
00761     O << "Blk: ";
00762     DIE::print(O, 5);
00763   }
00764 #endif
00765 };
00766 
00767 //===----------------------------------------------------------------------===//
00768 /// CompileUnit - This dwarf writer support class manages information associate
00769 /// with a source file.
00770 class CompileUnit {
00771 private:
00772   /// ID - File identifier for source.
00773   ///
00774   unsigned ID;
00775 
00776   /// Die - Compile unit debug information entry.
00777   ///
00778   DIE *Die;
00779 
00780   /// GVToDieMap - Tracks the mapping of unit level debug informaton
00781   /// variables to debug information entries.
00782   std::map<GlobalVariable *, DIE *> GVToDieMap;
00783 
00784   /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
00785   /// descriptors to debug information entries using a DIEntry proxy.
00786   std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
00787 
00788   /// Globals - A map of globally visible named entities for this unit.
00789   ///
00790   std::map<std::string, DIE *> Globals;
00791 
00792   /// DiesSet - Used to uniquely define dies within the compile unit.
00793   ///
00794   FoldingSet<DIE> DiesSet;
00795 
00796 public:
00797   CompileUnit(unsigned I, DIE *D)
00798     : ID(I), Die(D), GVToDieMap(),
00799       GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
00800   {}
00801 
00802   ~CompileUnit() {
00803     delete Die;
00804   }
00805 
00806   // Accessors.
00807   unsigned getID()           const { return ID; }
00808   DIE* getDie()              const { return Die; }
00809   std::map<std::string, DIE *> &getGlobals() { return Globals; }
00810 
00811   /// hasContent - Return true if this compile unit has something to write out.
00812   ///
00813   bool hasContent() const {
00814     return !Die->getChildren().empty();
00815   }
00816 
00817   /// AddGlobal - Add a new global entity to the compile unit.
00818   ///
00819   void AddGlobal(const std::string &Name, DIE *Die) {
00820     Globals[Name] = Die;
00821   }
00822 
00823   /// getDieMapSlotFor - Returns the debug information entry map slot for the
00824   /// specified debug variable.
00825   DIE *&getDieMapSlotFor(GlobalVariable *GV) {
00826     return GVToDieMap[GV];
00827   }
00828 
00829   /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
00830   /// specified debug variable.
00831   DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
00832     return GVToDIEntryMap[GV];
00833   }
00834 
00835   /// AddDie - Adds or interns the DIE to the compile unit.
00836   ///
00837   DIE *AddDie(DIE &Buffer) {
00838     FoldingSetNodeID ID;
00839     Buffer.Profile(ID);
00840     void *Where;
00841     DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
00842 
00843     if (!Die) {
00844       Die = new DIE(Buffer);
00845       DiesSet.InsertNode(Die, Where);
00846       this->Die->AddChild(Die);
00847       Buffer.Detach();
00848     }
00849 
00850     return Die;
00851   }
00852 };
00853 
00854 //===----------------------------------------------------------------------===//
00855 /// Dwarf - Emits general Dwarf directives.
00856 ///
00857 class Dwarf {
00858 
00859 protected:
00860 
00861   //===--------------------------------------------------------------------===//
00862   // Core attributes used by the Dwarf writer.
00863   //
00864 
00865   //
00866   /// O - Stream to .s file.
00867   ///
00868   raw_ostream &O;
00869 
00870   /// Asm - Target of Dwarf emission.
00871   ///
00872   AsmPrinter *Asm;
00873 
00874   /// TAI - Target asm information.
00875   const TargetAsmInfo *TAI;
00876 
00877   /// TD - Target data.
00878   const TargetData *TD;
00879 
00880   /// RI - Register Information.
00881   const TargetRegisterInfo *RI;
00882 
00883   /// M - Current module.
00884   ///
00885   Module *M;
00886 
00887   /// MF - Current machine function.
00888   ///
00889   MachineFunction *MF;
00890 
00891   /// MMI - Collected machine module information.
00892   ///
00893   MachineModuleInfo *MMI;
00894 
00895   /// SubprogramCount - The running count of functions being compiled.
00896   ///
00897   unsigned SubprogramCount;
00898 
00899   /// Flavor - A unique string indicating what dwarf producer this is, used to
00900   /// unique labels.
00901   const char * const Flavor;
00902 
00903   unsigned SetCounter;
00904   Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
00905         const char *flavor)
00906   : O(OS)
00907   , Asm(A)
00908   , TAI(T)
00909   , TD(Asm->TM.getTargetData())
00910   , RI(Asm->TM.getRegisterInfo())
00911   , M(NULL)
00912   , MF(NULL)
00913   , MMI(NULL)
00914   , SubprogramCount(0)
00915   , Flavor(flavor)
00916   , SetCounter(1)
00917   {
00918   }
00919 
00920 public:
00921 
00922   //===--------------------------------------------------------------------===//
00923   // Accessors.
00924   //
00925   AsmPrinter *getAsm() const { return Asm; }
00926   MachineModuleInfo *getMMI() const { return MMI; }
00927   const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
00928   const TargetData *getTargetData() const { return TD; }
00929 
00930   void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
00931                                                                          const {
00932     if (isInSection && TAI->getDwarfSectionOffsetDirective())
00933       O << TAI->getDwarfSectionOffsetDirective();
00934     else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
00935       O << TAI->getData32bitsDirective();
00936     else
00937       O << TAI->getData64bitsDirective();
00938   }
00939 
00940   /// PrintLabelName - Print label name in form used by Dwarf writer.
00941   ///
00942   void PrintLabelName(DWLabel Label) const {
00943     PrintLabelName(Label.Tag, Label.Number);
00944   }
00945   void PrintLabelName(const char *Tag, unsigned Number) const {
00946     O << TAI->getPrivateGlobalPrefix() << Tag;
00947     if (Number) O << Number;
00948   }
00949 
00950   void PrintLabelName(const char *Tag, unsigned Number,
00951                       const char *Suffix) const {
00952     O << TAI->getPrivateGlobalPrefix() << Tag;
00953     if (Number) O << Number;
00954     O << Suffix;
00955   }
00956 
00957   /// EmitLabel - Emit location label for internal use by Dwarf.
00958   ///
00959   void EmitLabel(DWLabel Label) const {
00960     EmitLabel(Label.Tag, Label.Number);
00961   }
00962   void EmitLabel(const char *Tag, unsigned Number) const {
00963     PrintLabelName(Tag, Number);
00964     O << ":\n";
00965   }
00966 
00967   /// EmitReference - Emit a reference to a label.
00968   ///
00969   void EmitReference(DWLabel Label, bool IsPCRelative = false,
00970                      bool Force32Bit = false) const {
00971     EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
00972   }
00973   void EmitReference(const char *Tag, unsigned Number,
00974                      bool IsPCRelative = false, bool Force32Bit = false) const {
00975     PrintRelDirective(Force32Bit);
00976     PrintLabelName(Tag, Number);
00977 
00978     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
00979   }
00980   void EmitReference(const std::string &Name, bool IsPCRelative = false,
00981                      bool Force32Bit = false) const {
00982     PrintRelDirective(Force32Bit);
00983 
00984     O << Name;
00985 
00986     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
00987   }
00988 
00989   /// EmitDifference - Emit the difference between two labels.  Some
00990   /// assemblers do not behave with absolute expressions with data directives,
00991   /// so there is an option (needsSet) to use an intermediary set expression.
00992   void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
00993                       bool IsSmall = false) {
00994     EmitDifference(LabelHi.Tag, LabelHi.Number,
00995                    LabelLo.Tag, LabelLo.Number,
00996                    IsSmall);
00997   }
00998   void EmitDifference(const char *TagHi, unsigned NumberHi,
00999                       const char *TagLo, unsigned NumberLo,
01000                       bool IsSmall = false) {
01001     if (TAI->needsSet()) {
01002       O << "\t.set\t";
01003       PrintLabelName("set", SetCounter, Flavor);
01004       O << ",";
01005       PrintLabelName(TagHi, NumberHi);
01006       O << "-";
01007       PrintLabelName(TagLo, NumberLo);
01008       O << "\n";
01009 
01010       PrintRelDirective(IsSmall);
01011       PrintLabelName("set", SetCounter, Flavor);
01012       ++SetCounter;
01013     } else {
01014       PrintRelDirective(IsSmall);
01015 
01016       PrintLabelName(TagHi, NumberHi);
01017       O << "-";
01018       PrintLabelName(TagLo, NumberLo);
01019     }
01020   }
01021 
01022   void EmitSectionOffset(const char* Label, const char* Section,
01023                          unsigned LabelNumber, unsigned SectionNumber,
01024                          bool IsSmall = false, bool isEH = false,
01025                          bool useSet = true) {
01026     bool printAbsolute = false;
01027     if (isEH)
01028       printAbsolute = TAI->isAbsoluteEHSectionOffsets();
01029     else
01030       printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
01031 
01032     if (TAI->needsSet() && useSet) {
01033       O << "\t.set\t";
01034       PrintLabelName("set", SetCounter, Flavor);
01035       O << ",";
01036       PrintLabelName(Label, LabelNumber);
01037 
01038       if (!printAbsolute) {
01039         O << "-";
01040         PrintLabelName(Section, SectionNumber);
01041       }
01042       O << "\n";
01043 
01044       PrintRelDirective(IsSmall);
01045 
01046       PrintLabelName("set", SetCounter, Flavor);
01047       ++SetCounter;
01048     } else {
01049       PrintRelDirective(IsSmall, true);
01050 
01051       PrintLabelName(Label, LabelNumber);
01052 
01053       if (!printAbsolute) {
01054         O << "-";
01055         PrintLabelName(Section, SectionNumber);
01056       }
01057     }
01058   }
01059 
01060   /// EmitFrameMoves - Emit frame instructions to describe the layout of the
01061   /// frame.
01062   void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
01063                       const std::vector<MachineMove> &Moves, bool isEH) {
01064     int stackGrowth =
01065         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
01066           TargetFrameInfo::StackGrowsUp ?
01067             TD->getPointerSize() : -TD->getPointerSize();
01068     bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
01069 
01070     for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
01071       const MachineMove &Move = Moves[i];
01072       unsigned LabelID = Move.getLabelID();
01073 
01074       if (LabelID) {
01075         LabelID = MMI->MappedLabel(LabelID);
01076 
01077         // Throw out move if the label is invalid.
01078         if (!LabelID) continue;
01079       }
01080 
01081       const MachineLocation &Dst = Move.getDestination();
01082       const MachineLocation &Src = Move.getSource();
01083 
01084       // Advance row if new location.
01085       if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
01086         Asm->EmitInt8(DW_CFA_advance_loc4);
01087         Asm->EOL("DW_CFA_advance_loc4");
01088         EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
01089         Asm->EOL();
01090 
01091         BaseLabelID = LabelID;
01092         BaseLabel = "label";
01093         IsLocal = true;
01094       }
01095 
01096       // If advancing cfa.
01097       if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
01098         if (!Src.isReg()) {
01099           if (Src.getReg() == MachineLocation::VirtualFP) {
01100             Asm->EmitInt8(DW_CFA_def_cfa_offset);
01101             Asm->EOL("DW_CFA_def_cfa_offset");
01102           } else {
01103             Asm->EmitInt8(DW_CFA_def_cfa);
01104             Asm->EOL("DW_CFA_def_cfa");
01105             Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
01106             Asm->EOL("Register");
01107           }
01108 
01109           int Offset = -Src.getOffset();
01110 
01111           Asm->EmitULEB128Bytes(Offset);
01112           Asm->EOL("Offset");
01113         } else {
01114           assert(0 && "Machine move no supported yet.");
01115         }
01116       } else if (Src.isReg() &&
01117         Src.getReg() == MachineLocation::VirtualFP) {
01118         if (Dst.isReg()) {
01119           Asm->EmitInt8(DW_CFA_def_cfa_register);
01120           Asm->EOL("DW_CFA_def_cfa_register");
01121           Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
01122           Asm->EOL("Register");
01123         } else {
01124           assert(0 && "Machine move no supported yet.");
01125         }
01126       } else {
01127         unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
01128         int Offset = Dst.getOffset() / stackGrowth;
01129 
01130         if (Offset < 0) {
01131           Asm->EmitInt8(DW_CFA_offset_extended_sf);
01132           Asm->EOL("DW_CFA_offset_extended_sf");
01133           Asm->EmitULEB128Bytes(Reg);
01134           Asm->EOL("Reg");
01135           Asm->EmitSLEB128Bytes(Offset);
01136           Asm->EOL("Offset");
01137         } else if (Reg < 64) {
01138           Asm->EmitInt8(DW_CFA_offset + Reg);
01139           if (VerboseAsm)
01140             Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
01141           else
01142             Asm->EOL();
01143           Asm->EmitULEB128Bytes(Offset);
01144           Asm->EOL("Offset");
01145         } else {
01146           Asm->EmitInt8(DW_CFA_offset_extended);
01147           Asm->EOL("DW_CFA_offset_extended");
01148           Asm->EmitULEB128Bytes(Reg);
01149           Asm->EOL("Reg");
01150           Asm->EmitULEB128Bytes(Offset);
01151           Asm->EOL("Offset");
01152         }
01153       }
01154     }
01155   }
01156 
01157 };
01158 
01159 //===----------------------------------------------------------------------===//
01160 /// SrcLineInfo - This class is used to record source line correspondence.
01161 ///
01162 class SrcLineInfo {
01163   unsigned Line;                        // Source line number.
01164   unsigned Column;                      // Source column.
01165   unsigned SourceID;                    // Source ID number.
01166   unsigned LabelID;                     // Label in code ID number.
01167 public:
01168   SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
01169   : Line(L), Column(C), SourceID(S), LabelID(I) {}
01170   
01171   // Accessors
01172   unsigned getLine()     const { return Line; }
01173   unsigned getColumn()   const { return Column; }
01174   unsigned getSourceID() const { return SourceID; }
01175   unsigned getLabelID()  const { return LabelID; }
01176 };
01177 
01178 
01179 //===----------------------------------------------------------------------===//
01180 /// SrcFileInfo - This class is used to track source information.
01181 ///
01182 class SrcFileInfo {
01183   unsigned DirectoryID;                 // Directory ID number.
01184   std::string Name;                     // File name (not including directory.)
01185 public:
01186   SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
01187             
01188   // Accessors
01189   unsigned getDirectoryID()    const { return DirectoryID; }
01190   const std::string &getName() const { return Name; }
01191 
01192   /// operator== - Used by UniqueVector to locate entry.
01193   ///
01194   bool operator==(const SrcFileInfo &SI) const {
01195     return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
01196   }
01197 
01198   /// operator< - Used by UniqueVector to locate entry.
01199   ///
01200   bool operator<(const SrcFileInfo &SI) const {
01201     return getDirectoryID() < SI.getDirectoryID() ||
01202           (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
01203   }
01204 };
01205 
01206 //===----------------------------------------------------------------------===//
01207 /// DbgVariable - This class is used to track local variable information.
01208 ///
01209 class DbgVariable {
01210 private:
01211   DIVariable Var;                   // Variable Descriptor.
01212   unsigned FrameIndex;               // Variable frame index.
01213 
01214 public:
01215   DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I)  {}
01216   
01217   // Accessors.
01218   DIVariable getVariable()  const { return Var; }
01219   unsigned getFrameIndex() const { return FrameIndex; }
01220 };
01221 
01222 //===----------------------------------------------------------------------===//
01223 /// DbgScope - This class is used to track scope information.
01224 ///
01225 class DbgScope {
01226 private:
01227   DbgScope *Parent;                   // Parent to this scope.
01228   DIDescriptor Desc;                  // Debug info descriptor for scope.
01229                                       // Either subprogram or block.
01230   unsigned StartLabelID;              // Label ID of the beginning of scope.
01231   unsigned EndLabelID;                // Label ID of the end of scope.
01232   SmallVector<DbgScope *, 4> Scopes;  // Scopes defined in scope.
01233   SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
01234   
01235 public:
01236   DbgScope(DbgScope *P, DIDescriptor D)
01237   : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
01238   {}
01239   ~DbgScope() {
01240     for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
01241     for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
01242   }
01243   
01244   // Accessors.
01245   DbgScope *getParent()          const { return Parent; }
01246   DIDescriptor getDesc()         const { return Desc; }
01247   unsigned getStartLabelID()     const { return StartLabelID; }
01248   unsigned getEndLabelID()       const { return EndLabelID; }
01249   SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
01250   SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
01251   void setStartLabelID(unsigned S) { StartLabelID = S; }
01252   void setEndLabelID(unsigned E)   { EndLabelID = E; }
01253   
01254   /// AddScope - Add a scope to the scope.
01255   ///
01256   void AddScope(DbgScope *S) { Scopes.push_back(S); }
01257   
01258   /// AddVariable - Add a variable to the scope.
01259   ///
01260   void AddVariable(DbgVariable *V) { Variables.push_back(V); }
01261 };
01262 
01263 //===----------------------------------------------------------------------===//
01264 /// DwarfDebug - Emits Dwarf debug directives.
01265 ///
01266 class DwarfDebug : public Dwarf {
01267 
01268 private:
01269   //===--------------------------------------------------------------------===//
01270   // Attributes used to construct specific Dwarf sections.
01271   //
01272 
01273   /// DW_CUs - All the compile units involved in this build.  The index
01274   /// of each entry in this vector corresponds to the sources in MMI.
01275   DenseMap<Value *, CompileUnit *> DW_CUs;
01276 
01277   /// MainCU - Some platform prefers one compile unit per .o file. In such
01278   /// cases, all dies are inserted in MainCU.
01279   CompileUnit *MainCU;
01280   /// AbbreviationsSet - Used to uniquely define abbreviations.
01281   ///
01282   FoldingSet<DIEAbbrev> AbbreviationsSet;
01283 
01284   /// Abbreviations - A list of all the unique abbreviations in use.
01285   ///
01286   std::vector<DIEAbbrev *> Abbreviations;
01287 
01288   /// Directories - Uniquing vector for directories.
01289   UniqueVector<std::string> Directories;
01290 
01291   /// SourceFiles - Uniquing vector for source files.
01292   UniqueVector<SrcFileInfo> SrcFiles;
01293 
01294   /// Lines - List of of source line correspondence.
01295   std::vector<SrcLineInfo> Lines;
01296 
01297   /// ValuesSet - Used to uniquely define values.
01298   ///
01299   FoldingSet<DIEValue> ValuesSet;
01300 
01301   /// Values - A list of all the unique values in use.
01302   ///
01303   std::vector<DIEValue *> Values;
01304 
01305   /// StringPool - A UniqueVector of strings used by indirect references.
01306   ///
01307   UniqueVector<std::string> StringPool;
01308 
01309   /// SectionMap - Provides a unique id per text section.
01310   ///
01311   UniqueVector<const Section*> SectionMap;
01312 
01313   /// SectionSourceLines - Tracks line numbers per text section.
01314   ///
01315   std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
01316 
01317   /// didInitial - Flag to indicate if initial emission has been done.
01318   ///
01319   bool didInitial;
01320 
01321   /// shouldEmit - Flag to indicate if debug information should be emitted.
01322   ///
01323   bool shouldEmit;
01324 
01325   // RootDbgScope - Top level scope for the current function.
01326   //
01327   DbgScope *RootDbgScope;
01328   
01329   // DbgScopeMap - Tracks the scopes in the current function.
01330   DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
01331   
01332   struct FunctionDebugFrameInfo {
01333     unsigned Number;
01334     std::vector<MachineMove> Moves;
01335 
01336     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
01337       Number(Num), Moves(M) { }
01338   };
01339 
01340   std::vector<FunctionDebugFrameInfo> DebugFrames;
01341 
01342 public:
01343 
01344   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
01345   ///
01346   bool ShouldEmitDwarf() const { return shouldEmit; }
01347 
01348   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
01349   ///
01350   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
01351     // Profile the node so that we can make it unique.
01352     FoldingSetNodeID ID;
01353     Abbrev.Profile(ID);
01354 
01355     // Check the set for priors.
01356     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
01357 
01358     // If it's newly added.
01359     if (InSet == &Abbrev) {
01360       // Add to abbreviation list.
01361       Abbreviations.push_back(&Abbrev);
01362       // Assign the vector position + 1 as its number.
01363       Abbrev.setNumber(Abbreviations.size());
01364     } else {
01365       // Assign existing abbreviation number.
01366       Abbrev.setNumber(InSet->getNumber());
01367     }
01368   }
01369 
01370   /// NewString - Add a string to the constant pool and returns a label.
01371   ///
01372   DWLabel NewString(const std::string &String) {
01373     unsigned StringID = StringPool.insert(String);
01374     return DWLabel("string", StringID);
01375   }
01376 
01377   /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
01378   /// entry.
01379   DIEntry *NewDIEntry(DIE *Entry = NULL) {
01380     DIEntry *Value;
01381 
01382     if (Entry) {
01383       FoldingSetNodeID ID;
01384       DIEntry::Profile(ID, Entry);
01385       void *Where;
01386       Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
01387 
01388       if (Value) return Value;
01389 
01390       Value = new DIEntry(Entry);
01391       ValuesSet.InsertNode(Value, Where);
01392     } else {
01393       Value = new DIEntry(Entry);
01394     }
01395 
01396     Values.push_back(Value);
01397     return Value;
01398   }
01399 
01400   /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
01401   ///
01402   void SetDIEntry(DIEntry *Value, DIE *Entry) {
01403     Value->Entry = Entry;
01404     // Add to values set if not already there.  If it is, we merely have a
01405     // duplicate in the values list (no harm.)
01406     ValuesSet.GetOrInsertNode(Value);
01407   }
01408 
01409   /// AddUInt - Add an unsigned integer attribute data and value.
01410   ///
01411   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
01412     if (!Form) Form = DIEInteger::BestForm(false, Integer);
01413 
01414     FoldingSetNodeID ID;
01415     DIEInteger::Profile(ID, Integer);
01416     void *Where;
01417     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
01418     if (!Value) {
01419       Value = new DIEInteger(Integer);
01420       ValuesSet.InsertNode(Value, Where);
01421       Values.push_back(Value);
01422     }
01423 
01424     Die->AddValue(Attribute, Form, Value);
01425   }
01426 
01427   /// AddSInt - Add an signed integer attribute data and value.
01428   ///
01429   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
01430     if (!Form) Form = DIEInteger::BestForm(true, Integer);
01431 
01432     FoldingSetNodeID ID;
01433     DIEInteger::Profile(ID, (uint64_t)Integer);
01434     void *Where;
01435     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
01436     if (!Value) {
01437       Value = new DIEInteger(Integer);
01438       ValuesSet.InsertNode(Value, Where);
01439       Values.push_back(Value);
01440     }
01441 
01442     Die->AddValue(Attribute, Form, Value);
01443   }
01444 
01445   /// AddString - Add a std::string attribute data and value.
01446   ///
01447   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
01448                  const std::string &String) {
01449     FoldingSetNodeID ID;
01450     DIEString::Profile(ID, String);
01451     void *Where;
01452     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
01453     if (!Value) {
01454       Value = new DIEString(String);
01455       ValuesSet.InsertNode(Value, Where);
01456       Values.push_back(Value);
01457     }
01458 
01459     Die->AddValue(Attribute, Form, Value);
01460   }
01461 
01462   /// AddLabel - Add a Dwarf label attribute data and value.
01463   ///
01464   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
01465                      const DWLabel &Label) {
01466     FoldingSetNodeID ID;
01467     DIEDwarfLabel::Profile(ID, Label);
01468     void *Where;
01469     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
01470     if (!Value) {
01471       Value = new DIEDwarfLabel(Label);
01472       ValuesSet.InsertNode(Value, Where);
01473       Values.push_back(Value);
01474     }
01475 
01476     Die->AddValue(Attribute, Form, Value);
01477   }
01478 
01479   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
01480   ///
01481   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
01482                       const std::string &Label) {
01483     FoldingSetNodeID ID;
01484     DIEObjectLabel::Profile(ID, Label);
01485     void *Where;
01486     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
01487     if (!Value) {
01488       Value = new DIEObjectLabel(Label);
01489       ValuesSet.InsertNode(Value, Where);
01490       Values.push_back(Value);
01491     }
01492 
01493     Die->AddValue(Attribute, Form, Value);
01494   }
01495 
01496   /// AddSectionOffset - Add a section offset label attribute data and value.
01497   ///
01498   void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
01499                         const DWLabel &Label, const DWLabel &Section,
01500                         bool isEH = false, bool useSet = true) {
01501     FoldingSetNodeID ID;
01502     DIESectionOffset::Profile(ID, Label, Section);
01503     void *Where;
01504     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
01505     if (!Value) {
01506       Value = new DIESectionOffset(Label, Section, isEH, useSet);
01507       ValuesSet.InsertNode(Value, Where);
01508       Values.push_back(Value);
01509     }
01510 
01511     Die->AddValue(Attribute, Form, Value);
01512   }
01513 
01514   /// AddDelta - Add a label delta attribute data and value.
01515   ///
01516   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
01517                           const DWLabel &Hi, const DWLabel &Lo) {
01518     FoldingSetNodeID ID;
01519     DIEDelta::Profile(ID, Hi, Lo);
01520     void *Where;
01521     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
01522     if (!Value) {
01523       Value = new DIEDelta(Hi, Lo);
01524       ValuesSet.InsertNode(Value, Where);
01525       Values.push_back(Value);
01526     }
01527 
01528     Die->AddValue(Attribute, Form, Value);
01529   }
01530 
01531   /// AddDIEntry - Add a DIE attribute data and value.
01532   ///
01533   void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
01534     Die->AddValue(Attribute, Form, NewDIEntry(Entry));
01535   }
01536 
01537   /// AddBlock - Add block data.
01538   ///
01539   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
01540     Block->ComputeSize(*this);
01541     FoldingSetNodeID ID;
01542     Block->Profile(ID);
01543     void *Where;
01544     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
01545     if (!Value) {
01546       Value = Block;
01547       ValuesSet.InsertNode(Value, Where);
01548       Values.push_back(Value);
01549     } else {
01550       // Already exists, reuse the previous one.
01551       delete Block;
01552       Block = cast<DIEBlock>(Value);
01553     }
01554 
01555     Die->AddValue(Attribute, Block->BestForm(), Value);
01556   }
01557 
01558 private:
01559 
01560   /// AddSourceLine - Add location information to specified debug information
01561   /// entry.
01562   void AddSourceLine(DIE *Die, const DIVariable *V) {
01563     unsigned FileID = 0;
01564     unsigned Line = V->getLineNumber();
01565     CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
01566     FileID = Unit->getID();
01567     AddUInt(Die, DW_AT_decl_file, 0, FileID);
01568     AddUInt(Die, DW_AT_decl_line, 0, Line);
01569   }
01570 
01571   /// AddSourceLine - Add location information to specified debug information
01572   /// entry.
01573   void AddSourceLine(DIE *Die, const DIGlobal *G) {
01574     unsigned FileID = 0;
01575     unsigned Line = G->getLineNumber();
01576     CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
01577     FileID = Unit->getID();
01578     AddUInt(Die, DW_AT_decl_file, 0, FileID);
01579     AddUInt(Die, DW_AT_decl_line, 0, Line);
01580   }
01581 
01582   void AddSourceLine(DIE *Die, const DIType *Ty) {
01583     unsigned FileID = 0;
01584     unsigned Line = Ty->getLineNumber();
01585     DICompileUnit CU = Ty->getCompileUnit();
01586     if (CU.isNull())
01587       return;
01588     CompileUnit *Unit = FindCompileUnit(CU);
01589     FileID = Unit->getID();
01590     AddUInt(Die, DW_AT_decl_file, 0, FileID);
01591     AddUInt(Die, DW_AT_decl_line, 0, Line);
01592   }
01593 
01594   /// AddAddress - Add an address attribute to a die based on the location
01595   /// provided.
01596   void AddAddress(DIE *Die, unsigned Attribute,
01597                             const MachineLocation &Location) {
01598     unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
01599     DIEBlock *Block = new DIEBlock();
01600 
01601     if (Location.isReg()) {
01602       if (Reg < 32) {
01603         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
01604       } else {
01605         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
01606         AddUInt(Block, 0, DW_FORM_udata, Reg);
01607       }
01608     } else {
01609       if (Reg < 32) {
01610         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
01611       } else {
01612         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
01613         AddUInt(Block, 0, DW_FORM_udata, Reg);
01614       }
01615       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
01616     }
01617 
01618     AddBlock(Die, Attribute, 0, Block);
01619   }
01620 
01621   /// AddType - Add a new type attribute to the specified entity.
01622   void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
01623     if (Ty.isNull())
01624       return;
01625 
01626     // Check for pre-existence.
01627     DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
01628     // If it exists then use the existing value.
01629     if (Slot) {
01630       Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
01631       return;
01632     }
01633 
01634     // Set up proxy. 
01635     Slot = NewDIEntry();
01636 
01637     // Construct type.
01638     DIE Buffer(DW_TAG_base_type);
01639     if (Ty.isBasicType(Ty.getTag()))
01640       ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
01641     else if (Ty.isDerivedType(Ty.getTag()))
01642       ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
01643     else {
01644       assert (Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
01645       ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
01646     }
01647     
01648     // Add debug information entry to entity and appropriate context.
01649     DIE *Die = NULL;
01650     DIDescriptor Context = Ty.getContext();
01651     if (!Context.isNull())
01652       Die = DW_Unit->getDieMapSlotFor(Context.getGV());
01653 
01654     if (Die) {
01655       DIE *Child = new DIE(Buffer);
01656       Die->AddChild(Child);
01657       Buffer.Detach();
01658       SetDIEntry(Slot, Child);
01659     }
01660     else {
01661       Die = DW_Unit->AddDie(Buffer);
01662       SetDIEntry(Slot, Die);
01663     }
01664 
01665     Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
01666   }
01667 
01668   /// ConstructTypeDIE - Construct basic type die from DIBasicType.
01669   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
01670                         DIBasicType BTy) {
01671     
01672     // Get core information.
01673     const std::string &Name = BTy.getName();
01674     Buffer.setTag(DW_TAG_base_type);
01675     AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BTy.getEncoding());
01676     // Add name if not anonymous or intermediate type.
01677     if (!Name.empty())
01678       AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
01679     uint64_t Size = BTy.getSizeInBits() >> 3;
01680     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
01681   }
01682 
01683   /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
01684   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
01685                         DIDerivedType DTy) {
01686 
01687     // Get core information.
01688     const std::string &Name = DTy.getName();
01689     uint64_t Size = DTy.getSizeInBits() >> 3;
01690     unsigned Tag = DTy.getTag();
01691     // FIXME - Workaround for templates.
01692     if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
01693 
01694     Buffer.setTag(Tag);
01695     // Map to main type, void will not have a type.
01696     DIType FromTy = DTy.getTypeDerivedFrom();
01697     AddType(DW_Unit, &Buffer, FromTy);
01698 
01699     // Add name if not anonymous or intermediate type.
01700     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
01701 
01702     // Add size if non-zero (derived types might be zero-sized.)
01703     if (Size)
01704       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
01705 
01706     // Add source line info if available and TyDesc is not a forward
01707     // declaration.
01708     if (!DTy.isForwardDecl())
01709       AddSourceLine(&Buffer, &DTy);
01710   }
01711 
01712   /// ConstructTypeDIE - Construct type DIE from DICompositeType.
01713   void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
01714                         DICompositeType CTy) {
01715 
01716     // Get core information.
01717     const std::string &Name = CTy.getName();
01718     uint64_t Size = CTy.getSizeInBits() >> 3;
01719     unsigned Tag = CTy.getTag();
01720     Buffer.setTag(Tag);
01721     switch (Tag) {
01722     case DW_TAG_vector_type:
01723     case DW_TAG_array_type:
01724       ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
01725       break;
01726     case DW_TAG_enumeration_type:
01727       {
01728         DIArray Elements = CTy.getTypeArray();
01729         // Add enumerators to enumeration type.
01730         for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
01731           DIE *ElemDie = NULL;
01732           DIEnumerator Enum(Elements.getElement(i).getGV());
01733           ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
01734           Buffer.AddChild(ElemDie);
01735         }
01736       }
01737       break;
01738     case DW_TAG_subroutine_type: 
01739       {
01740         // Add prototype flag.
01741         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
01742         DIArray Elements = CTy.getTypeArray();
01743         // Add return type.
01744         DIDescriptor RTy = Elements.getElement(0);
01745         AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
01746 
01747         // Add arguments.
01748         for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
01749           DIE *Arg = new DIE(DW_TAG_formal_parameter);
01750           DIDescriptor Ty = Elements.getElement(i);
01751           AddType(DW_Unit, Arg, DIType(Ty.getGV()));
01752           Buffer.AddChild(Arg);
01753         }
01754       }
01755       break;
01756     case DW_TAG_structure_type:
01757     case DW_TAG_union_type: 
01758       {
01759         // Add elements to structure type.
01760         DIArray Elements = CTy.getTypeArray();
01761 
01762         // A forward struct declared type may not have elements available.
01763         if (Elements.isNull())
01764           break;
01765 
01766         // Add elements to structure type.
01767         for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
01768           DIDescriptor Element = Elements.getElement(i);
01769           DIE *ElemDie = NULL;
01770           if (Element.getTag() == dwarf::DW_TAG_subprogram)
01771             ElemDie = CreateSubprogramDIE(DW_Unit, 
01772                                           DISubprogram(Element.getGV()));
01773           else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
01774             ElemDie = CreateGlobalVariableDIE(DW_Unit, 
01775                                               DIGlobalVariable(Element.getGV()));
01776           else
01777             ElemDie = CreateMemberDIE(DW_Unit, 
01778                                       DIDerivedType(Element.getGV()));
01779           Buffer.AddChild(ElemDie);
01780         }
01781       }
01782       break;
01783     default:
01784       break;
01785     }
01786 
01787     // Add name if not anonymous or intermediate type.
01788     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
01789 
01790     if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
01791         || Tag == DW_TAG_union_type) {
01792       // Add size if non-zero (derived types might be zero-sized.)
01793       if (Size)
01794         AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
01795       else {
01796         // Add zero size if it is not a forward declaration.
01797         if (CTy.isForwardDecl())
01798           AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
01799         else
01800           AddUInt(&Buffer, DW_AT_byte_size, 0, 0); 
01801       }
01802       
01803       // Add source line info if available.
01804       if (!CTy.isForwardDecl())
01805         AddSourceLine(&Buffer, &CTy);
01806     }
01807   }
01808   
01809   // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
01810   void ConstructSubrangeDIE (DIE &Buffer, DISubrange SR, DIE *IndexTy) {
01811     int64_t L = SR.getLo();
01812     int64_t H = SR.getHi();
01813     DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
01814     if (L != H) {
01815       AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
01816       if (L)
01817         AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
01818       AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
01819     }
01820     Buffer.AddChild(DW_Subrange);
01821   }
01822 
01823   /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
01824   void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 
01825                              DICompositeType *CTy) {
01826     Buffer.setTag(DW_TAG_array_type);
01827     if (CTy->getTag() == DW_TAG_vector_type)
01828       AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
01829     
01830     // Emit derived type.
01831     AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());    
01832     DIArray Elements = CTy->getTypeArray();
01833 
01834     // Construct an anonymous type for index type.
01835     DIE IdxBuffer(DW_TAG_base_type);
01836     AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
01837     AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
01838     DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
01839 
01840     // Add subranges to array type.
01841     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
01842       DIDescriptor Element = Elements.getElement(i);
01843       if (Element.getTag() == dwarf::DW_TAG_subrange_type)
01844         ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
01845     }
01846   }
01847 
01848   /// ConstructEnumTypeDIE - Construct enum type DIE from 
01849   /// DIEnumerator.
01850   DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
01851 
01852     DIE *Enumerator = new DIE(DW_TAG_enumerator);
01853     AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
01854     int64_t Value = ETy->getEnumValue();                             
01855     AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
01856     return Enumerator;
01857   }
01858 
01859   /// CreateGlobalVariableDIE - Create new DIE using GV.
01860   DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV) 
01861   {
01862     DIE *GVDie = new DIE(DW_TAG_variable);
01863     AddString(GVDie, DW_AT_name, DW_FORM_string, GV.getName());
01864     const std::string &LinkageName = GV.getLinkageName();
01865     if (!LinkageName.empty())
01866       AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
01867     AddType(DW_Unit, GVDie, GV.getType());
01868     if (!GV.isLocalToUnit())
01869       AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
01870     AddSourceLine(GVDie, &GV);
01871     return GVDie;
01872   }
01873 
01874   /// CreateMemberDIE - Create new member DIE.
01875   DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
01876     DIE *MemberDie = new DIE(DT.getTag());
01877     std::string Name = DT.getName();
01878     if (!Name.empty())
01879       AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
01880 
01881     AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
01882 
01883     AddSourceLine(MemberDie, &DT);
01884 
01885     // FIXME _ Handle bitfields
01886     DIEBlock *Block = new DIEBlock();
01887     AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
01888     AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
01889     AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
01890 
01891     if (DT.isProtected())
01892       AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
01893     else if (DT.isPrivate())
01894       AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
01895 
01896     return MemberDie;
01897   }
01898 
01899   /// CreateSubprogramDIE - Create new DIE using SP.
01900   DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
01901                            const  DISubprogram &SP,
01902                            bool IsConstructor = false) {
01903     DIE *SPDie = new DIE(DW_TAG_subprogram);
01904     AddString(SPDie, DW_AT_name, DW_FORM_string, SP.getName());
01905     const std::string &LinkageName = SP.getLinkageName();
01906     if (!LinkageName.empty())
01907       AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string, 
01908                 LinkageName);
01909     AddSourceLine(SPDie, &SP);
01910 
01911     DICompositeType SPTy = SP.getType();
01912     DIArray Args = SPTy.getTypeArray();
01913     
01914     // Add Return Type.
01915     if (!IsConstructor) 
01916       AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
01917 
01918     if (!SP.isDefinition()) {
01919       AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);    
01920       // Add arguments.
01921       // Do not add arguments for subprogram definition. They will be
01922       // handled through RecordVariable.
01923       if (!Args.isNull())
01924         for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
01925           DIE *Arg = new DIE(DW_TAG_formal_parameter);
01926           AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
01927           AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
01928           SPDie->AddChild(Arg);
01929         }
01930     }
01931 
01932     if (!SP.isLocalToUnit())
01933       AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
01934     return SPDie;
01935   }
01936 
01937   /// FindCompileUnit - Get the compile unit for the given descriptor. 
01938   ///
01939   CompileUnit *FindCompileUnit(DICompileUnit Unit) {
01940     CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
01941     assert(DW_Unit && "Missing compile unit.");
01942     return DW_Unit;
01943   }
01944 
01945   /// NewDbgScopeVariable - Create a new scope variable.
01946   ///
01947   DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
01948     // Get the descriptor.
01949     const DIVariable &VD = DV->getVariable();
01950 
01951     // Translate tag to proper Dwarf tag.  The result variable is dropped for
01952     // now.
01953     unsigned Tag;
01954     switch (VD.getTag()) {
01955     case DW_TAG_return_variable:  return NULL;
01956     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
01957     case DW_TAG_auto_variable:    // fall thru
01958     default:                      Tag = DW_TAG_variable; break;
01959     }
01960 
01961     // Define variable debug information entry.
01962     DIE *VariableDie = new DIE(Tag);
01963     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD.getName());
01964 
01965     // Add source line info if available.
01966     AddSourceLine(VariableDie, &VD);
01967 
01968     // Add variable type.
01969     AddType(Unit, VariableDie, VD.getType());
01970 
01971     // Add variable address.
01972     MachineLocation Location;
01973     Location.set(RI->getFrameRegister(*MF),
01974                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
01975     AddAddress(VariableDie, DW_AT_location, Location);
01976 
01977     return VariableDie;
01978   }
01979 
01980   /// getOrCreateScope - Returns the scope associated with the given descriptor.
01981   ///
01982   DbgScope *getOrCreateScope(GlobalVariable *V) {
01983     DbgScope *&Slot = DbgScopeMap[V];
01984     if (!Slot) {
01985       // FIXME - breaks down when the context is an inlined function.
01986       DIDescriptor ParentDesc;
01987       DIDescriptor Desc(V);
01988       if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
01989         DIBlock Block(V);
01990         ParentDesc = Block.getContext();
01991       }
01992       DbgScope *Parent = ParentDesc.isNull() ? 
01993         NULL : getOrCreateScope(ParentDesc.getGV());
01994       Slot = new DbgScope(Parent, Desc);
01995       if (Parent) {
01996         Parent->AddScope(Slot);
01997       } else if (RootDbgScope) {
01998         // FIXME - Add inlined function scopes to the root so we can delete
01999         // them later.  Long term, handle inlined functions properly.
02000         RootDbgScope->AddScope(Slot);
02001       } else {
02002         // First function is top level function.
02003         RootDbgScope = Slot;
02004       }
02005     }
02006     return Slot;
02007   }
02008 
02009   /// ConstructDbgScope - Construct the components of a scope.
02010   ///
02011   void ConstructDbgScope(DbgScope *ParentScope,
02012                          unsigned ParentStartID, unsigned ParentEndID,
02013                          DIE *ParentDie, CompileUnit *Unit) {
02014     // Add variables to scope.
02015     SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
02016     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
02017       DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
02018       if (VariableDie) ParentDie->AddChild(VariableDie);
02019     }
02020 
02021     // Add nested scopes.
02022     SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
02023     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
02024       // Define the Scope debug information entry.
02025       DbgScope *Scope = Scopes[j];
02026       // FIXME - Ignore inlined functions for the time being.
02027       if (!Scope->getParent()) continue;
02028 
02029       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
02030       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
02031 
02032       // Ignore empty scopes.
02033       if (StartID == EndID && StartID != 0) continue;
02034       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
02035 
02036       if (StartID == ParentStartID && EndID == ParentEndID) {
02037         // Just add stuff to the parent scope.
02038         ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
02039       } else {
02040         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
02041 
02042         // Add the scope bounds.
02043         if (StartID) {
02044           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
02045                              DWLabel("label", StartID));
02046         } else {
02047           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
02048                              DWLabel("func_begin", SubprogramCount));
02049         }
02050         if (EndID) {
02051           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
02052                              DWLabel("label", EndID));
02053         } else {
02054           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
02055                              DWLabel("func_end", SubprogramCount));
02056         }
02057 
02058         // Add the scope contents.
02059         ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
02060         ParentDie->AddChild(ScopeDie);
02061       }
02062     }
02063   }
02064 
02065   /// ConstructRootDbgScope - Construct the scope for the subprogram.
02066   ///
02067   void ConstructRootDbgScope(DbgScope *RootScope) {
02068     // Exit if there is no root scope.
02069     if (!RootScope) return;
02070     DIDescriptor Desc = RootScope->getDesc();
02071     if (Desc.isNull())
02072       return;
02073 
02074     // Get the subprogram debug information entry.
02075     DISubprogram SPD(Desc.getGV());
02076 
02077     // Get the compile unit context.
02078     CompileUnit *Unit = MainCU;
02079     if (!Unit)
02080       Unit = FindCompileUnit(SPD.getCompileUnit());
02081 
02082     // Get the subprogram die.
02083     DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
02084     assert(SPDie && "Missing subprogram descriptor");
02085 
02086     // Add the function bounds.
02087     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
02088                     DWLabel("func_begin", SubprogramCount));
02089     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
02090                     DWLabel("func_end", SubprogramCount));
02091     MachineLocation Location(RI->getFrameRegister(*MF));
02092     AddAddress(SPDie, DW_AT_frame_base, Location);
02093 
02094     ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
02095   }
02096 
02097   /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
02098   ///
02099   void ConstructDefaultDbgScope(MachineFunction *MF) {
02100     // Find the correct subprogram descriptor.
02101     std::string SPName = "llvm.dbg.subprograms";
02102     std::vector<GlobalVariable*> Result;
02103     getGlobalVariablesUsing(*M, SPName, Result);
02104     for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
02105            E = Result.end(); I != E; ++I) {
02106 
02107       DISubprogram SPD(*I);
02108 
02109       if (SPD.getName() == MF->getFunction()->getName()) {
02110         // Get the compile unit context.
02111         CompileUnit *Unit = MainCU;
02112         if (!Unit)
02113           Unit = FindCompileUnit(SPD.getCompileUnit());
02114 
02115         // Get the subprogram die.
02116         DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
02117         assert(SPDie && "Missing subprogram descriptor");
02118 
02119         // Add the function bounds.
02120         AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
02121                  DWLabel("func_begin", SubprogramCount));
02122         AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
02123                  DWLabel("func_end", SubprogramCount));
02124 
02125         MachineLocation Location(RI->getFrameRegister(*MF));
02126         AddAddress(SPDie, DW_AT_frame_base, Location);
02127         return;
02128       }
02129     }
02130 #if 0
02131     // FIXME: This is causing an abort because C++ mangled names are compared
02132     // with their unmangled counterparts. See PR2885. Don't do this assert.
02133     assert(0 && "Couldn't find DIE for machine function!");
02134 #endif
02135   }
02136 
02137   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
02138   /// tools to recognize the object file contains Dwarf information.
02139   void EmitInitial() {
02140     // Check to see if we already emitted intial headers.
02141     if (didInitial) return;
02142     didInitial = true;
02143 
02144     // Dwarf sections base addresses.
02145     if (TAI->doesDwarfRequireFrameSection()) {
02146       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
02147       EmitLabel("section_debug_frame", 0);
02148     }
02149     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
02150     EmitLabel("section_info", 0);
02151     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
02152     EmitLabel("section_abbrev", 0);
02153     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
02154     EmitLabel("section_aranges", 0);
02155     if (TAI->doesSupportMacInfoSection()) {
02156       Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
02157       EmitLabel("section_macinfo", 0);
02158     }
02159     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
02160     EmitLabel("section_line", 0);
02161     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
02162     EmitLabel("section_loc", 0);
02163     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
02164     EmitLabel("section_pubnames", 0);
02165     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
02166     EmitLabel("section_str", 0);
02167     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
02168     EmitLabel("section_ranges", 0);
02169 
02170     Asm->SwitchToSection(TAI->getTextSection());
02171     EmitLabel("text_begin", 0);
02172     Asm->SwitchToSection(TAI->getDataSection());
02173     EmitLabel("data_begin", 0);
02174   }
02175 
02176   /// EmitDIE - Recusively Emits a debug information entry.
02177   ///
02178   void EmitDIE(DIE *Die) {
02179     // Get the abbreviation for this DIE.
02180     unsigned AbbrevNumber = Die->getAbbrevNumber();
02181     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
02182 
02183     Asm->EOL();
02184 
02185     // Emit the code (index) for the abbreviation.
02186     Asm->EmitULEB128Bytes(AbbrevNumber);
02187 
02188     if (VerboseAsm)
02189       Asm->EOL(std::string("Abbrev [" +
02190                            utostr(AbbrevNumber) +
02191                            "] 0x" + utohexstr(Die->getOffset()) +
02192                            ":0x" + utohexstr(Die->getSize()) + " " +
02193                            TagString(Abbrev->getTag())));
02194     else
02195       Asm->EOL();
02196 
02197     SmallVector<DIEValue*, 32> &Values = Die->getValues();
02198     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
02199 
02200     // Emit the DIE attribute values.
02201     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
02202       unsigned Attr = AbbrevData[i].getAttribute();
02203       unsigned Form = AbbrevData[i].getForm();
02204       assert(Form && "Too many attributes for DIE (check abbreviation)");
02205 
02206       switch (Attr) {
02207       case DW_AT_sibling: {
02208         Asm->EmitInt32(Die->SiblingOffset());
02209         break;
02210       }
02211       default: {
02212         // Emit an attribute using the defined form.
02213         Values[i]->EmitValue(*this, Form);
02214         break;
02215       }
02216       }
02217 
02218       Asm->EOL(AttributeString(Attr));
02219     }
02220 
02221     // Emit the DIE children if any.
02222     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
02223       const std::vector<DIE *> &Children = Die->getChildren();
02224 
02225       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
02226         EmitDIE(Children[j]);
02227       }
02228 
02229       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
02230     }
02231   }
02232 
02233   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
02234   ///
02235   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
02236     // Get the children.
02237     const std::vector<DIE *> &Children = Die->getChildren();
02238 
02239     // If not last sibling and has children then add sibling offset attribute.
02240     if (!Last && !Children.empty()) Die->AddSiblingOffset();
02241 
02242     // Record the abbreviation.
02243     AssignAbbrevNumber(Die->getAbbrev());
02244 
02245     // Get the abbreviation for this DIE.
02246     unsigned AbbrevNumber = Die->getAbbrevNumber();
02247     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
02248 
02249     // Set DIE offset
02250     Die->setOffset(Offset);
02251 
02252     // Start the size with the size of abbreviation code.
02253     Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
02254 
02255     const SmallVector<DIEValue*, 32> &Values = Die->getValues();
02256     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
02257 
02258     // Size the DIE attribute values.
02259     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
02260       // Size attribute value.
02261       Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
02262     }
02263 
02264     // Size the DIE children if any.
02265     if (!Children.empty()) {
02266       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
02267              "Children flag not set");
02268 
02269       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
02270         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
02271       }
02272 
02273       // End of children marker.
02274       Offset += sizeof(int8_t);
02275     }
02276 
02277     Die->setSize(Offset - Die->getOffset());
02278     return Offset;
02279   }
02280 
02281   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
02282   ///
02283   void SizeAndOffsets() {
02284     // Process base compile unit.
02285     if (MainCU) {
02286       // Compute size of compile unit header
02287       unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
02288         sizeof(int16_t) + // DWARF version number
02289         sizeof(int32_t) + // Offset Into Abbrev. Section
02290         sizeof(int8_t);   // Pointer Size (in bytes)
02291       SizeAndOffsetDie(MainCU->getDie(), Offset, true);
02292       return;
02293     }
02294     for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
02295            CE = DW_CUs.end(); CI != CE; ++CI) {
02296       CompileUnit *Unit = CI->second;
02297       // Compute size of compile unit header
02298       unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
02299         sizeof(int16_t) + // DWARF version number
02300         sizeof(int32_t) + // Offset Into Abbrev. Section
02301         sizeof(int8_t);   // Pointer Size (in bytes)
02302       SizeAndOffsetDie(Unit->getDie(), Offset, true);
02303     }
02304   }
02305 
02306   /// EmitDebugInfo - Emit the debug info section.
02307   ///
02308   void EmitDebugInfo() {
02309     // Start debug info section.
02310     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
02311 
02312     for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
02313            CE = DW_CUs.end(); CI != CE; ++CI) {
02314       CompileUnit *Unit = CI->second;
02315       if (MainCU)
02316         Unit = MainCU;
02317       DIE *Die = Unit->getDie();
02318       // Emit the compile units header.
02319       EmitLabel("info_begin", Unit->getID());
02320       // Emit size of content not including length itself
02321       unsigned ContentSize = Die->getSize() +
02322         sizeof(int16_t) + // DWARF version number
02323         sizeof(int32_t) + // Offset Into Abbrev. Section
02324         sizeof(int8_t) +  // Pointer Size (in bytes)
02325         sizeof(int32_t);  // FIXME - extra pad for gdb bug.
02326       
02327       Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
02328       Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
02329       EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
02330       Asm->EOL("Offset Into Abbrev. Section");
02331       Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
02332       
02333       EmitDIE(Die);
02334       // FIXME - extra padding for gdb bug.
02335       Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
02336       Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
02337       Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
02338       Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
02339       EmitLabel("info_end", Unit->getID());
02340       
02341       Asm->EOL();
02342       if (MainCU)
02343         return;
02344     }
02345   }
02346 
02347   /// EmitAbbreviations - Emit the abbreviation section.
02348   ///
02349   void EmitAbbreviations() const {
02350     // Check to see if it is worth the effort.
02351     if (!Abbreviations.empty()) {
02352       // Start the debug abbrev section.
02353       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
02354 
02355       EmitLabel("abbrev_begin", 0);
02356 
02357       // For each abbrevation.
02358       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
02359         // Get abbreviation data
02360         const DIEAbbrev *Abbrev = Abbreviations[i];
02361 
02362         // Emit the abbrevations code (base 1 index.)
02363         Asm->EmitULEB128Bytes(Abbrev->getNumber());
02364         Asm->EOL("Abbreviation Code");
02365 
02366         // Emit the abbreviations data.
02367         Abbrev->Emit(*this);
02368 
02369         Asm->EOL();
02370       }
02371 
02372       // Mark end of abbreviations.
02373       Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
02374 
02375       EmitLabel("abbrev_end", 0);
02376 
02377       Asm->EOL();
02378     }
02379   }
02380 
02381   /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
02382   /// the line matrix.
02383   ///
02384   void EmitEndOfLineMatrix(unsigned SectionEnd) {
02385     // Define last address of section.
02386     Asm->EmitInt8(0); Asm->EOL("Extended Op");
02387     Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
02388     Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
02389     EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
02390 
02391     // Mark end of matrix.
02392     Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
02393     Asm->EmitULEB128Bytes(1); Asm->EOL();
02394     Asm->EmitInt8(1); Asm->EOL();
02395   }
02396 
02397   /// EmitDebugLines - Emit source line information.
02398   ///
02399   void EmitDebugLines() {
02400     // If the target is using .loc/.file, the assembler will be emitting the
02401     // .debug_line table automatically.
02402     if (TAI->hasDotLocAndDotFile())
02403       return;
02404 
02405     // Minimum line delta, thus ranging from -10..(255-10).
02406     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
02407     // Maximum line delta, thus ranging from -10..(255-10).
02408     const int MaxLineDelta = 255 + MinLineDelta;
02409 
02410     // Start the dwarf line section.
02411     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
02412 
02413     // Construct the section header.
02414 
02415     EmitDifference("line_end", 0, "line_begin", 0, true);
02416     Asm->EOL("Length of Source Line Info");
02417     EmitLabel("line_begin", 0);
02418 
02419     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
02420 
02421     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
02422     Asm->EOL("Prolog Length");
02423     EmitLabel("line_prolog_begin", 0);
02424 
02425     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
02426 
02427     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
02428 
02429     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
02430 
02431     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
02432 
02433     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
02434 
02435     // Line number standard opcode encodings argument count
02436     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
02437     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
02438     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
02439     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
02440     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
02441     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
02442     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
02443     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
02444     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
02445 
02446     // Emit directories.
02447     for (unsigned DirectoryID = 1, NDID = Directories.size();
02448                   DirectoryID <= NDID; ++DirectoryID) {
02449       Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
02450     }
02451     Asm->EmitInt8(0); Asm->EOL("End of directories");
02452 
02453     // Emit files.
02454     for (unsigned SourceID = 1, NSID = SrcFiles.size();
02455                  SourceID <= NSID; ++SourceID) {
02456       const SrcFileInfo &SourceFile = SrcFiles[SourceID];
02457       Asm->EmitString(SourceFile.getName());
02458       Asm->EOL("Source");
02459       Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
02460       Asm->EOL("Directory #");
02461       Asm->EmitULEB128Bytes(0);
02462       Asm->EOL("Mod date");
02463       Asm->EmitULEB128Bytes(0);
02464       Asm->EOL("File size");
02465     }
02466     Asm->EmitInt8(0); Asm->EOL("End of files");
02467 
02468     EmitLabel("line_prolog_end", 0);
02469 
02470     // A sequence for each text section.
02471     unsigned SecSrcLinesSize = SectionSourceLines.size();
02472 
02473     for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
02474       // Isolate current sections line info.
02475       const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
02476 
02477       if (VerboseAsm) {
02478         const Section* S = SectionMap[j + 1];
02479         Asm->EOL(std::string("Section ") + S->getName());
02480       } else
02481         Asm->EOL();
02482 
02483       // Dwarf assumes we start with first line of first source file.
02484       unsigned Source = 1;
02485       unsigned Line = 1;
02486 
02487       // Construct rows of the address, source, line, column matrix.
02488       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
02489         const SrcLineInfo &LineInfo = LineInfos[i];
02490         unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
02491         if (!LabelID) continue;
02492 
02493         unsigned SourceID = LineInfo.getSourceID();
02494         const SrcFileInfo &SourceFile = SrcFiles[SourceID];
02495         unsigned DirectoryID = SourceFile.getDirectoryID();
02496         if (VerboseAsm)
02497           Asm->EOL(Directories[DirectoryID]
02498                    + SourceFile.getName()
02499                    + ":"
02500                    + utostr_32(LineInfo.getLine()));
02501         else
02502           Asm->EOL();
02503 
02504         // Define the line address.
02505         Asm->EmitInt8(0); Asm->EOL("Extended Op");
02506         Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
02507         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
02508         EmitReference("label",  LabelID); Asm->EOL("Location label");
02509 
02510         // If change of source, then switch to the new source.
02511         if (Source != LineInfo.getSourceID()) {
02512           Source = LineInfo.getSourceID();
02513           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
02514           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
02515         }
02516 
02517         // If change of line.
02518         if (Line != LineInfo.getLine()) {
02519           // Determine offset.
02520           int Offset = LineInfo.getLine() - Line;
02521           int Delta = Offset - MinLineDelta;
02522 
02523           // Update line.
02524           Line = LineInfo.getLine();
02525 
02526           // If delta is small enough and in range...
02527           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
02528             // ... then use fast opcode.
02529             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
02530           } else {
02531             // ... otherwise use long hand.
02532             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
02533             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
02534             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
02535           }
02536         } else {
02537           // Copy the previous row (different address or source)
02538           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
02539         }
02540       }
02541 
02542       EmitEndOfLineMatrix(j + 1);
02543     }
02544 
02545     if (SecSrcLinesSize == 0)
02546       // Because we're emitting a debug_line section, we still need a line
02547       // table. The linker and friends expect it to exist. If there's nothing to
02548       // put into it, emit an empty table.
02549       EmitEndOfLineMatrix(1);
02550 
02551     EmitLabel("line_end", 0);
02552 
02553     Asm->EOL();
02554   }
02555 
02556   /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
02557   ///
02558   void EmitCommonDebugFrame() {
02559     if (!TAI->doesDwarfRequireFrameSection())
02560       return;
02561 
02562     int stackGrowth =
02563         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
02564           TargetFrameInfo::StackGrowsUp ?
02565         TD->getPointerSize() : -TD->getPointerSize();
02566 
02567     // Start the dwarf frame section.
02568     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
02569 
02570     EmitLabel("debug_frame_common", 0);
02571     EmitDifference("debug_frame_common_end", 0,
02572                    "debug_frame_common_begin", 0, true);
02573     Asm->EOL("Length of Common Information Entry");
02574 
02575     EmitLabel("debug_frame_common_begin", 0);
02576     Asm->EmitInt32((int)DW_CIE_ID);
02577     Asm->EOL("CIE Identifier Tag");
02578     Asm->EmitInt8(DW_CIE_VERSION);
02579     Asm->EOL("CIE Version");
02580     Asm->EmitString("");
02581     Asm->EOL("CIE Augmentation");
02582     Asm->EmitULEB128Bytes(1);
02583     Asm->EOL("CIE Code Alignment Factor");
02584     Asm->EmitSLEB128Bytes(stackGrowth);
02585     Asm->EOL("CIE Data Alignment Factor");
02586     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
02587     Asm->EOL("CIE RA Column");
02588 
02589     std::vector<MachineMove> Moves;
02590     RI->getInitialFrameState(Moves);
02591 
02592     EmitFrameMoves(NULL, 0, Moves, false);
02593 
02594     Asm->EmitAlignment(2, 0, 0, false);
02595     EmitLabel("debug_frame_common_end", 0);
02596 
02597     Asm->EOL();
02598   }
02599 
02600   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
02601   /// section.
02602   void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
02603     if (!TAI->doesDwarfRequireFrameSection())
02604       return;
02605 
02606     // Start the dwarf frame section.
02607     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
02608 
02609     EmitDifference("debug_frame_end", DebugFrameInfo.Number,
02610                    "debug_frame_begin", DebugFrameInfo.Number, true);
02611     Asm->EOL("Length of Frame Information Entry");
02612 
02613     EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
02614 
02615     EmitSectionOffset("debug_frame_common", "section_debug_frame",
02616                       0, 0, true, false);
02617     Asm->EOL("FDE CIE offset");
02618 
02619     EmitReference("func_begin", DebugFrameInfo.Number);
02620     Asm->EOL("FDE initial location");
02621     EmitDifference("func_end", DebugFrameInfo.Number,
02622                    "func_begin", DebugFrameInfo.Number);
02623     Asm->EOL("FDE address range");
02624 
02625     EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, 
02626                    false);
02627 
02628     Asm->EmitAlignment(2, 0, 0, false);
02629     EmitLabel("debug_frame_end", DebugFrameInfo.Number);
02630 
02631     Asm->EOL();
02632   }
02633 
02634   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
02635   ///
02636   void EmitDebugPubNames() {
02637     // Start the dwarf pubnames section.
02638     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
02639 
02640     for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
02641            CE = DW_CUs.end(); CI != CE; ++CI) {
02642       CompileUnit *Unit = CI->second;
02643       if (MainCU)
02644         Unit = MainCU;
02645 
02646       EmitDifference("pubnames_end", Unit->getID(),
02647                      "pubnames_begin", Unit->getID(), true);
02648       Asm->EOL("Length of Public Names Info");
02649       
02650       EmitLabel("pubnames_begin", Unit->getID());
02651       
02652       Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
02653       
02654       EmitSectionOffset("info_begin", "section_info",
02655                         Unit->getID(), 0, true, false);
02656       Asm->EOL("Offset of Compilation Unit Info");
02657       
02658       EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
02659                      true);
02660       Asm->EOL("Compilation Unit Length");
02661       
02662       std::map<std::string, DIE *> &Globals = Unit->getGlobals();
02663       
02664       for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
02665              GE = Globals.end();
02666            GI != GE; ++GI) {
02667         const std::string &Name = GI->first;
02668         DIE * Entity = GI->second;
02669         
02670         Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
02671         Asm->EmitString(Name); Asm->EOL("External Name");
02672       }
02673       
02674       Asm->EmitInt32(0); Asm->EOL("End Mark");
02675       EmitLabel("pubnames_end", Unit->getID());
02676       
02677       Asm->EOL();
02678       if (MainCU)
02679         return;
02680     }
02681   }
02682 
02683   /// EmitDebugStr - Emit visible names into a debug str section.
02684   ///
02685   void EmitDebugStr() {
02686     // Check to see if it is worth the effort.
02687     if (!StringPool.empty()) {
02688       // Start the dwarf str section.
02689       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
02690 
02691       // For each of strings in the string pool.
02692       for (unsigned StringID = 1, N = StringPool.size();
02693            StringID <= N; ++StringID) {
02694         // Emit a label for reference from debug information entries.
02695         EmitLabel("string", StringID);
02696         // Emit the string itself.
02697         const std::string &String = StringPool[StringID];
02698         Asm->EmitString(String); Asm->EOL();
02699       }
02700 
02701       Asm->EOL();
02702     }
02703   }
02704 
02705   /// EmitDebugLoc - Emit visible names into a debug loc section.
02706   ///
02707   void EmitDebugLoc() {
02708     // Start the dwarf loc section.
02709     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
02710 
02711     Asm->EOL();
02712   }
02713 
02714   /// EmitDebugARanges - Emit visible names into a debug aranges section.
02715   ///
02716   void EmitDebugARanges() {
02717     // Start the dwarf aranges section.
02718     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
02719 
02720     // FIXME - Mock up
02721 #if 0
02722     CompileUnit *Unit = GetBaseCompileUnit();
02723 
02724     // Don't include size of length
02725     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
02726 
02727     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
02728 
02729     EmitReference("info_begin", Unit->getID());
02730     Asm->EOL("Offset of Compilation Unit Info");
02731 
02732     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
02733 
02734     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
02735 
02736     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
02737     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
02738 
02739     // Range 1
02740     EmitReference("text_begin", 0); Asm->EOL("Address");
02741     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
02742 
02743     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
02744     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
02745 #endif
02746 
02747     Asm->EOL();
02748   }
02749 
02750   /// EmitDebugRanges - Emit visible names into a debug ranges section.
02751   ///
02752   void EmitDebugRanges() {
02753     // Start the dwarf ranges section.
02754     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
02755 
02756     Asm->EOL();
02757   }
02758 
02759   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
02760   ///
02761   void EmitDebugMacInfo() {
02762     if (TAI->doesSupportMacInfoSection()) {
02763       // Start the dwarf macinfo section.
02764       Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
02765 
02766       Asm->EOL();
02767     }
02768   }
02769 
02770   /// ConstructCompileUnits - Create a compile unit DIEs.
02771   void ConstructCompileUnits() {
02772     std::string CUName = "llvm.dbg.compile_units";
02773     std::vector<GlobalVariable*> Result;
02774     getGlobalVariablesUsing(*M, CUName, Result);
02775     for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
02776            RE = Result.end(); RI != RE; ++RI) {
02777       DICompileUnit DIUnit(*RI);
02778       unsigned ID = RecordSource(DIUnit.getDirectory(),
02779                                  DIUnit.getFilename());
02780 
02781       DIE *Die = new DIE(DW_TAG_compile_unit);
02782       AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
02783                        DWLabel("section_line", 0), DWLabel("section_line", 0),
02784                        false);
02785       AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer());
02786       AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
02787       AddString(Die, DW_AT_name, DW_FORM_string, DIUnit.getFilename());
02788       if (!DIUnit.getDirectory().empty())
02789         AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit.getDirectory());
02790       if (DIUnit.isOptimized())
02791         AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
02792       const std::string &Flags = DIUnit.getFlags();
02793       if (!Flags.empty())
02794         AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
02795 
02796       CompileUnit *Unit = new CompileUnit(ID, Die);
02797       if (DIUnit.isMain()) {
02798         assert (!MainCU && "Multiple main compile units are found!");
02799         MainCU = Unit;
02800       }
02801       DW_CUs[DIUnit.getGV()] = Unit;
02802     }
02803   }
02804 
02805   /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally 
02806   /// visible global variables.
02807   void ConstructGlobalVariableDIEs() {
02808     std::string GVName = "llvm.dbg.global_variables";
02809     std::vector<GlobalVariable*> Result;
02810     getGlobalVariablesUsing(*M, GVName, Result);
02811     for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
02812            GVE = Result.end(); GVI != GVE; ++GVI) {
02813       DIGlobalVariable DI_GV(*GVI);
02814       CompileUnit *DW_Unit = MainCU;
02815       if (!DW_Unit)
02816         DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
02817 
02818       // Check for pre-existence.
02819       DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
02820       if (Slot) continue;
02821 
02822       DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
02823 
02824       // Add address.
02825       DIEBlock *Block = new DIEBlock();
02826       AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
02827       AddObjectLabel(Block, 0, DW_FORM_udata,
02828                      Asm->getGlobalLinkName(DI_GV.getGlobal()));
02829       AddBlock(VariableDie, DW_AT_location, 0, Block);
02830 
02831       //Add to map.
02832       Slot = VariableDie;
02833 
02834       //Add to context owner.
02835       DW_Unit->getDie()->AddChild(VariableDie);
02836 
02837       //Expose as global. FIXME - need to check external flag.
02838       DW_Unit->AddGlobal(DI_GV.getName(), VariableDie);
02839     }
02840   }
02841 
02842   /// ConstructSubprograms - Create DIEs for each of the externally visible
02843   /// subprograms.
02844   void ConstructSubprograms() {
02845 
02846     std::string SPName = "llvm.dbg.subprograms";
02847     std::vector<GlobalVariable*> Result;
02848     getGlobalVariablesUsing(*M, SPName, Result);
02849     for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
02850            RE = Result.end(); RI != RE; ++RI) {
02851 
02852       DISubprogram SP(*RI);
02853       CompileUnit *Unit = MainCU;
02854       if (!Unit)
02855         Unit = FindCompileUnit(SP.getCompileUnit());
02856 
02857       // Check for pre-existence.
02858       DIE *&Slot = Unit->getDieMapSlotFor(SP.getGV());
02859       if (Slot) continue;
02860 
02861       if (!SP.isDefinition())
02862         // This is a method declaration which will be handled while
02863         // constructing class type.
02864         continue;
02865 
02866       DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
02867 
02868       //Add to map.
02869       Slot = SubprogramDie;
02870       //Add to context owner.
02871       Unit->getDie()->AddChild(SubprogramDie);
02872       //Expose as global.
02873       Unit->AddGlobal(SP.getName(), SubprogramDie);
02874     }
02875   }
02876 
02877 public:
02878   //===--------------------------------------------------------------------===//
02879   // Main entry points.
02880   //
02881   DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
02882   : Dwarf(OS, A, T, "dbg")
02883   , MainCU(NULL)
02884   , AbbreviationsSet(InitAbbreviationsSetSize)
02885   , Abbreviations()
02886   , ValuesSet(InitValuesSetSize)
02887   , Values()
02888   , StringPool()
02889   , SectionMap()
02890   , SectionSourceLines()
02891   , didInitial(false)
02892   , shouldEmit(false)
02893   , RootDbgScope(NULL)
02894   {
02895   }
02896   virtual ~DwarfDebug() {
02897     for (unsigned j = 0, M = Values.size(); j < M; ++j)
02898       delete Values[j];
02899   }
02900 
02901   /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
02902   /// This is inovked by the target AsmPrinter.
02903   void SetDebugInfo(MachineModuleInfo *mmi) {
02904 
02905       // Create all the compile unit DIEs.
02906       ConstructCompileUnits();
02907       
02908       if (DW_CUs.empty())
02909         return;
02910 
02911       MMI = mmi;
02912       shouldEmit = true;
02913       MMI->setDebugInfoAvailability(true);
02914 
02915       // Create DIEs for each of the externally visible global variables.
02916       ConstructGlobalVariableDIEs();
02917 
02918       // Create DIEs for each of the externally visible subprograms.
02919       ConstructSubprograms();
02920 
02921       // Prime section data.
02922       SectionMap.insert(TAI->getTextSection());
02923 
02924       // Print out .file directives to specify files for .loc directives. These
02925       // are printed out early so that they precede any .loc directives.
02926       if (TAI->hasDotLocAndDotFile()) {
02927         for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
02928           sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
02929           bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
02930           assert(AppendOk && "Could not append filename to directory!");
02931           AppendOk = false;
02932           Asm->EmitFile(i, FullPath.toString());
02933           Asm->EOL();
02934         }
02935       }
02936 
02937       // Emit initial sections
02938       EmitInitial();
02939   }
02940 
02941   /// BeginModule - Emit all Dwarf sections that should come prior to the
02942   /// content.
02943   void BeginModule(Module *M) {
02944     this->M = M;
02945   }
02946 
02947   /// EndModule - Emit all Dwarf sections that should come after the content.
02948   ///
02949   void EndModule() {
02950     if (!ShouldEmitDwarf()) return;
02951 
02952     // Standard sections final addresses.
02953     Asm->SwitchToSection(TAI->getTextSection());
02954     EmitLabel("text_end", 0);
02955     Asm->SwitchToSection(TAI->getDataSection());
02956     EmitLabel("data_end", 0);
02957 
02958     // End text sections.
02959     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
02960       Asm->SwitchToSection(SectionMap[i]);
02961       EmitLabel("section_end", i);
02962     }
02963 
02964     // Emit common frame information.
02965     EmitCommonDebugFrame();
02966 
02967     // Emit function debug frame information
02968     for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
02969            E = DebugFrames.end(); I != E; ++I)
02970       EmitFunctionDebugFrame(*I);
02971 
02972     // Compute DIE offsets and sizes.
02973     SizeAndOffsets();
02974 
02975     // Emit all the DIEs into a debug info section
02976     EmitDebugInfo();
02977 
02978     // Corresponding abbreviations into a abbrev section.
02979     EmitAbbreviations();
02980 
02981     // Emit source line correspondence into a debug line section.
02982     EmitDebugLines();
02983 
02984     // Emit info into a debug pubnames section.
02985     EmitDebugPubNames();
02986 
02987     // Emit info into a debug str section.
02988     EmitDebugStr();
02989 
02990     // Emit info into a debug loc section.
02991     EmitDebugLoc();
02992 
02993     // Emit info into a debug aranges section.
02994     EmitDebugARanges();
02995 
02996     // Emit info into a debug ranges section.
02997     EmitDebugRanges();
02998 
02999     // Emit info into a debug macinfo section.
03000     EmitDebugMacInfo();
03001   }
03002 
03003   /// BeginFunction - Gather pre-function debug information.  Assumes being
03004   /// emitted immediately after the function entry point.
03005   void BeginFunction(MachineFunction *MF) {
03006     this->MF = MF;
03007 
03008     if (!ShouldEmitDwarf()) return;
03009 
03010     // Begin accumulating function debug information.
03011     MMI->BeginFunction(MF);
03012 
03013     // Assumes in correct section after the entry point.
03014     EmitLabel("func_begin", ++SubprogramCount);
03015 
03016     // Emit label for the implicitly defined dbg.stoppoint at the start of
03017     // the function.
03018     if (!Lines.empty()) {
03019       const SrcLineInfo &LineInfo = Lines[0];
03020       Asm->printLabel(LineInfo.getLabelID());
03021     }
03022   }
03023 
03024   /// EndFunction - Gather and emit post-function debug information.
03025   ///
03026   void EndFunction(MachineFunction *MF) {
03027     if (!ShouldEmitDwarf()) return;
03028 
03029     // Define end label for subprogram.
03030     EmitLabel("func_end", SubprogramCount);
03031 
03032     // Get function line info.
03033     if (!Lines.empty()) {
03034       // Get section line info.
03035       unsigned ID = SectionMap.insert(Asm->CurrentSection_);
03036       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
03037       std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
03038       // Append the function info to section info.
03039       SectionLineInfos.insert(SectionLineInfos.end(),
03040                               Lines.begin(), Lines.end());
03041     }
03042 
03043     // Construct scopes for subprogram.
03044     if (RootDbgScope)
03045       ConstructRootDbgScope(RootDbgScope);
03046     else
03047       // FIXME: This is wrong. We are essentially getting past a problem with
03048       // debug information not being able to handle unreachable blocks that have
03049       // debug information in them. In particular, those unreachable blocks that
03050       // have "region end" info in them. That situation results in the "root
03051       // scope" not being created. If that's the case, then emit a "default"
03052       // scope, i.e., one that encompasses the whole function. This isn't
03053       // desirable. And a better way of handling this (and all of the debugging
03054       // information) needs to be explored.
03055       ConstructDefaultDbgScope(MF);
03056 
03057     DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
03058                                                  MMI->getFrameMoves()));
03059 
03060     // Clear debug info
03061     if (RootDbgScope) {
03062       delete RootDbgScope;
03063       DbgScopeMap.clear();
03064       RootDbgScope = NULL;
03065     }
03066     Lines.clear();
03067   }
03068 
03069 public:
03070 
03071   /// ValidDebugInfo - Return true if V represents valid debug info value.
03072   bool ValidDebugInfo(Value *V) {
03073 
03074     if (!V)
03075       return false;
03076 
03077     if (!shouldEmit)
03078       return false;
03079 
03080     GlobalVariable *GV = getGlobalVariable(V);
03081     if (!GV)
03082       return false;
03083     
03084     if (GV->getLinkage() != GlobalValue::InternalLinkage
03085         && GV->getLinkage() != GlobalValue::LinkOnceLinkage)
03086       return false;
03087 
03088     DIDescriptor DI(GV);
03089     // Check current version. Allow Version6 for now.
03090     unsigned Version = DI.getVersion();
03091     if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
03092       return false;
03093 
03094     unsigned Tag = DI.getTag();
03095     switch (Tag) {
03096     case DW_TAG_variable:
03097       assert (DIVariable(GV).Verify() && "Invalid DebugInfo value");
03098       break;
03099     case DW_TAG_compile_unit:
03100       assert (DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
03101       break;
03102     case DW_TAG_subprogram:
03103       assert (DISubprogram(GV).Verify() && "Invalid DebugInfo value");
03104       break;
03105     default:
03106       break;
03107     }
03108 
03109     return true;
03110   }
03111 
03112   /// RecordSourceLine - Records location information and associates it with a 
03113   /// label. Returns a unique label ID used to generate a label and provide
03114   /// correspondence to the source line list.
03115   unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
03116     CompileUnit *Unit = DW_CUs[V];
03117     assert (Unit && "Unable to find CompileUnit");
03118     unsigned ID = MMI->NextLabelID();
03119     Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
03120     return ID;
03121   }
03122   
03123   /// RecordSourceLine - Records location information and associates it with a 
03124   /// label. Returns a unique label ID used to generate a label and provide
03125   /// correspondence to the source line list.
03126   unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
03127     unsigned ID = MMI->NextLabelID();
03128     Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
03129     return ID;
03130   }
03131 
03132   unsigned getRecordSourceLineCount() {
03133     return Lines.size();
03134   }
03135                             
03136   /// RecordSource - Register a source file with debug info. Returns an source
03137   /// ID.
03138   unsigned RecordSource(const std::string &Directory,
03139                         const std::string &File) {
03140     unsigned DID = Directories.insert(Directory);
03141     return SrcFiles.insert(SrcFileInfo(DID,File));
03142   }
03143 
03144   /// RecordRegionStart - Indicate the start of a region.
03145   ///
03146   unsigned RecordRegionStart(GlobalVariable *V) {
03147     DbgScope *Scope = getOrCreateScope(V);
03148     unsigned ID = MMI->NextLabelID();
03149     if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
03150     return ID;
03151   }
03152 
03153   /// RecordRegionEnd - Indicate the end of a region.
03154   ///
03155   unsigned RecordRegionEnd(GlobalVariable *V) {
03156     DbgScope *Scope = getOrCreateScope(V);
03157     unsigned ID = MMI->NextLabelID();
03158     Scope->setEndLabelID(ID);
03159     return ID;
03160   }
03161 
03162   /// RecordVariable - Indicate the declaration of  a local variable.
03163   ///
03164   void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
03165     DIDescriptor Desc(GV);
03166     DbgScope *Scope = NULL;
03167     if (Desc.getTag() == DW_TAG_variable) {
03168       // GV is a global variable.
03169       DIGlobalVariable DG(GV);
03170       Scope = getOrCreateScope(DG.getContext().getGV());
03171     } else {
03172       // or GV is a local variable.
03173       DIVariable DV(GV);
03174       Scope = getOrCreateScope(DV.getContext().getGV());
03175     }
03176     assert (Scope && "Unable to find variable' scope");
03177     DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
03178     Scope->AddVariable(DV);
03179   }
03180 };
03181 
03182 //===----------------------------------------------------------------------===//
03183 /// DwarfException - Emits Dwarf exception handling directives.
03184 ///
03185 class DwarfException : public Dwarf  {
03186 
03187 private:
03188   struct FunctionEHFrameInfo {
03189     std::string FnName;
03190     unsigned Number;
03191     unsigned PersonalityIndex;
03192     bool hasCalls;
03193     bool hasLandingPads;
03194     std::vector<MachineMove> Moves;
03195     const Function * function;
03196 
03197     FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
03198                         bool hC, bool hL,
03199                         const std::vector<MachineMove> &M,
03200                         const Function *f):
03201       FnName(FN), Number(Num), PersonalityIndex(P),
03202       hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
03203   };
03204 
03205   std::vector<FunctionEHFrameInfo> EHFrames;
03206 
03207   /// shouldEmitTable - Per-function flag to indicate if EH tables should
03208   /// be emitted.
03209   bool shouldEmitTable;
03210 
03211   /// shouldEmitMoves - Per-function flag to indicate if frame moves info
03212   /// should be emitted.
03213   bool shouldEmitMoves;
03214 
03215   /// shouldEmitTableModule - Per-module flag to indicate if EH tables
03216   /// should be emitted.
03217   bool shouldEmitTableModule;
03218 
03219   /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
03220   /// should be emitted.
03221   bool shouldEmitMovesModule;
03222 
03223   /// EmitCommonEHFrame - Emit the common eh unwind frame.
03224   ///
03225   void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
03226     // Size and sign of stack growth.
03227     int stackGrowth =
03228         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
03229           TargetFrameInfo::StackGrowsUp ?
03230         TD->getPointerSize() : -TD->getPointerSize();
03231 
03232     // Begin eh frame section.
03233     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
03234 
03235     if (!TAI->doesRequireNonLocalEHFrameLabel())
03236       O << TAI->getEHGlobalPrefix();
03237     O << "EH_frame" << Index << ":\n";
03238     EmitLabel("section_eh_frame", Index);
03239 
03240     // Define base labels.
03241     EmitLabel("eh_frame_common", Index);
03242 
03243     // Define the eh frame length.
03244     EmitDifference("eh_frame_common_end", Index,
03245                    "eh_frame_common_begin", Index, true);
03246     Asm->EOL("Length of Common Information Entry");
03247 
03248     // EH frame header.
03249     EmitLabel("eh_frame_common_begin", Index);
03250     Asm->EmitInt32((int)0);
03251     Asm->EOL("CIE Identifier Tag");
03252     Asm->EmitInt8(DW_CIE_VERSION);
03253     Asm->EOL("CIE Version");
03254 
03255     // The personality presence indicates that language specific information
03256     // will show up in the eh frame.
03257     Asm->EmitString(Personality ? "zPLR" : "zR");
03258     Asm->EOL("CIE Augmentation");
03259 
03260     // Round out reader.
03261     Asm->EmitULEB128Bytes(1);
03262     Asm->EOL("CIE Code Alignment Factor");
03263     Asm->EmitSLEB128Bytes(stackGrowth);
03264     Asm->EOL("CIE Data Alignment Factor");
03265     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
03266     Asm->EOL("CIE Return Address Column");
03267 
03268     // If there is a personality, we need to indicate the functions location.
03269     if (Personality) {
03270       Asm->EmitULEB128Bytes(7);
03271       Asm->EOL("Augmentation Size");
03272 
03273       if (TAI->getNeedsIndirectEncoding()) {
03274         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
03275         Asm->EOL("Personality (pcrel sdata4 indirect)");
03276       } else {
03277         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
03278         Asm->EOL("Personality (pcrel sdata4)");
03279       }
03280 
03281       PrintRelDirective(true);
03282       O << TAI->getPersonalityPrefix();
03283       Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
03284       O << TAI->getPersonalitySuffix();
03285       if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
03286         O << "-" << TAI->getPCSymbol();
03287       Asm->EOL("Personality");
03288 
03289       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
03290       Asm->EOL("LSDA Encoding (pcrel sdata4)");
03291 
03292       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
03293       Asm->EOL("FDE Encoding (pcrel sdata4)");
03294    } else {
03295       Asm->EmitULEB128Bytes(1);
03296       Asm->EOL("Augmentation Size");
03297 
03298       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
03299       Asm->EOL("FDE Encoding (pcrel sdata4)");
03300     }
03301 
03302     // Indicate locations of general callee saved registers in frame.
03303     std::vector<MachineMove> Moves;
03304     RI->getInitialFrameState(Moves);
03305     EmitFrameMoves(NULL, 0, Moves, true);
03306 
03307     // On Darwin the linker honors the alignment of eh_frame, which means it
03308     // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise
03309     // you get holes which confuse readers of eh_frame.
03310     Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
03311                        0, 0, false);
03312     EmitLabel("eh_frame_common_end", Index);
03313 
03314     Asm->EOL();
03315   }
03316 
03317   /// EmitEHFrame - Emit function exception frame information.
03318   ///
03319   void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
03320     Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
03321 
03322     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
03323 
03324     // Externally visible entry into the functions eh frame info.
03325     // If the corresponding function is static, this should not be
03326     // externally visible.
03327     if (linkage != Function::InternalLinkage &&
03328         linkage != Function::PrivateLinkage) {
03329       if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
03330         O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
03331     }
03332 
03333     // If corresponding function is weak definition, this should be too.
03334     if ((linkage == Function::WeakLinkage ||
03335          linkage == Function::LinkOnceLinkage) &&
03336         TAI->getWeakDefDirective())
03337       O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
03338 
03339     // If there are no calls then you can't unwind.  This may mean we can
03340     // omit the EH Frame, but some environments do not handle weak absolute
03341     // symbols.
03342     // If UnwindTablesMandatory is set we cannot do this optimization; the
03343     // unwind info is to be available for non-EH uses.
03344     if (!EHFrameInfo.hasCalls &&
03345         !UnwindTablesMandatory &&
03346         ((linkage != Function::WeakLinkage &&
03347           linkage != Function::LinkOnceLinkage) ||
03348          !TAI->getWeakDefDirective() ||
03349          TAI->getSupportsWeakOmittedEHFrame()))
03350     {
03351       O << EHFrameInfo.FnName << " = 0\n";
03352       // This name has no connection to the function, so it might get
03353       // dead-stripped when the function is not, erroneously.  Prohibit
03354       // dead-stripping unconditionally.
03355       if (const char *UsedDirective = TAI->getUsedDirective())
03356         O << UsedDirective << EHFrameInfo.FnName << "\n\n";
03357     } else {
03358       O << EHFrameInfo.FnName << ":\n";
03359 
03360       // EH frame header.
03361       EmitDifference("eh_frame_end", EHFrameInfo.Number,
03362                      "eh_frame_begin", EHFrameInfo.Number, true);
03363       Asm->EOL("Length of Frame Information Entry");
03364 
03365       EmitLabel("eh_frame_begin", EHFrameInfo.Number);
03366 
03367       if (TAI->doesRequireNonLocalEHFrameLabel()) {
03368         PrintRelDirective(true, true);
03369         PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
03370 
03371         if (!TAI->isAbsoluteEHSectionOffsets())
03372           O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
03373       } else {
03374         EmitSectionOffset("eh_frame_begin", "eh_frame_common",
03375                           EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
03376                           true, true, false);
03377       }
03378 
03379       Asm->EOL("FDE CIE offset");
03380 
03381       EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
03382       Asm->EOL("FDE initial location");
03383       EmitDifference("eh_func_end", EHFrameInfo.Number,
03384                      "eh_func_begin", EHFrameInfo.Number, true);
03385       Asm->EOL("FDE address range");
03386 
03387       // If there is a personality and landing pads then point to the language
03388       // specific data area in the exception table.
03389       if (EHFrameInfo.PersonalityIndex) {
03390         Asm->EmitULEB128Bytes(4);
03391         Asm->EOL("Augmentation size");
03392 
03393         if (EHFrameInfo.hasLandingPads)
03394           EmitReference("exception", EHFrameInfo.Number, true, true);
03395         else
03396           Asm->EmitInt32((int)0);
03397         Asm->EOL("Language Specific Data Area");
03398       } else {
03399         Asm->EmitULEB128Bytes(0);
03400         Asm->EOL("Augmentation size");
03401       }
03402 
03403       // Indicate locations of function specific  callee saved registers in
03404       // frame.
03405       EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, 
03406                      true);
03407 
03408       // On Darwin the linker honors the alignment of eh_frame, which means it
03409       // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise
03410       // you get holes which confuse readers of eh_frame.
03411       Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
03412                          0, 0, false);
03413       EmitLabel("eh_frame_end", EHFrameInfo.Number);
03414 
03415       // If the function is marked used, this table should be also.  We cannot
03416       // make the mark unconditional in this case, since retaining the table
03417       // also retains the function in this case, and there is code around
03418       // that depends on unused functions (calling undefined externals) being
03419       // dead-stripped to link correctly.  Yes, there really is.
03420       if (MMI->getUsedFunctions().count(EHFrameInfo.function))
03421         if (const char *UsedDirective = TAI->getUsedDirective())
03422           O << UsedDirective << EHFrameInfo.FnName << "\n\n";
03423     }
03424   }
03425 
03426   /// EmitExceptionTable - Emit landing pads and actions.
03427   ///
03428   /// The general organization of the table is complex, but the basic concepts
03429   /// are easy.  First there is a header which describes the location and
03430   /// organization of the three components that follow.
03431   ///  1. The landing pad site information describes the range of code covered
03432   ///     by the try.  In our case it's an accumulation of the ranges covered
03433   ///     by the invokes in the try.  There is also a reference to the landing
03434   ///     pad that handles the exception once processed.  Finally an index into
03435   ///     the actions table.
03436   ///  2. The action table, in our case, is composed of pairs of type ids
03437   ///     and next action offset.  Starting with the action index from the
03438   ///     landing pad site, each type Id is checked for a match to the current
03439   ///     exception.  If it matches then the exception and type id are passed
03440   ///     on to the landing pad.  Otherwise the next action is looked up.  This
03441   ///     chain is terminated with a next action of zero.  If no type id is
03442   ///     found the the frame is unwound and handling continues.
03443   ///  3. Type id table contains references to all the C++ typeinfo for all
03444   ///     catches in the function.  This tables is reversed indexed base 1.
03445 
03446   /// SharedTypeIds - How many leading type ids two landing pads have in common.
03447   static unsigned SharedTypeIds(const LandingPadInfo *L,
03448                                 const LandingPadInfo *R) {
03449     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
03450     unsigned LSize = LIds.size(), RSize = RIds.size();
03451     unsigned MinSize = LSize < RSize ? LSize : RSize;
03452     unsigned Count = 0;
03453 
03454     for (; Count != MinSize; ++Count)
03455       if (LIds[Count] != RIds[Count])
03456         return Count;
03457 
03458     return Count;
03459   }
03460 
03461   /// PadLT - Order landing pads lexicographically by type id.
03462   static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
03463     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
03464     unsigned LSize = LIds.size(), RSize = RIds.size();
03465     unsigned MinSize = LSize < RSize ? LSize : RSize;
03466 
03467     for (unsigned i = 0; i != MinSize; ++i)
03468       if (LIds[i] != RIds[i])
03469         return LIds[i] < RIds[i];
03470 
03471     return LSize < RSize;
03472   }
03473 
03474   struct KeyInfo {
03475     static inline unsigned getEmptyKey() { return -1U; }
03476     static inline unsigned getTombstoneKey() { return -2U; }
03477     static unsigned getHashValue(const unsigned &Key) { return Key; }
03478     static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
03479     static bool isPod() { return true; }
03480   };
03481 
03482   /// ActionEntry - Structure describing an entry in the actions table.
03483   struct ActionEntry {
03484     int ValueForTypeID; // The value to write - may not be equal to the type id.
03485     int NextAction;
03486     struct ActionEntry *Previous;
03487   };
03488 
03489   /// PadRange - Structure holding a try-range and the associated landing pad.
03490   struct PadRange {
03491     // The index of the landing pad.
03492     unsigned PadIndex;
03493     // The index of the begin and end labels in the landing pad's label lists.
03494     unsigned RangeIndex;
03495   };
03496 
03497   typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
03498 
03499   /// CallSiteEntry - Structure describing an entry in the call-site table.
03500   struct CallSiteEntry {
03501     // The 'try-range' is BeginLabel .. EndLabel.
03502     unsigned BeginLabel; // zero indicates the start of the function.
03503     unsigned EndLabel;   // zero indicates the end of the function.
03504     // The landing pad starts at PadLabel.
03505     unsigned PadLabel;   // zero indicates that there is no landing pad.
03506     unsigned Action;
03507   };
03508 
03509   void EmitExceptionTable() {
03510     const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
03511     const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
03512     const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
03513     if (PadInfos.empty()) return;
03514 
03515     // Sort the landing pads in order of their type ids.  This is used to fold
03516     // duplicate actions.
03517     SmallVector<const LandingPadInfo *, 64> LandingPads;
03518     LandingPads.reserve(PadInfos.size());
03519     for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
03520       LandingPads.push_back(&PadInfos[i]);
03521     std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
03522 
03523     // Negative type ids index into FilterIds, positive type ids index into
03524     // TypeInfos.  The value written for a positive type id is just the type
03525     // id itself.  For a negative type id, however, the value written is the
03526     // (negative) byte offset of the corresponding FilterIds entry.  The byte
03527     // offset is usually equal to the type id, because the FilterIds entries
03528     // are written using a variable width encoding which outputs one byte per
03529     // entry as long as the value written is not too large, but can differ.
03530     // This kind of complication does not occur for positive type ids because
03531     // type infos are output using a fixed width encoding.
03532     // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
03533     SmallVector<int, 16> FilterOffsets;
03534     FilterOffsets.reserve(FilterIds.size());
03535     int Offset = -1;
03536     for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
03537         E = FilterIds.end(); I != E; ++I) {
03538       FilterOffsets.push_back(Offset);
03539       Offset -= TargetAsmInfo::getULEB128Size(*I);
03540     }
03541 
03542     // Compute the actions table and gather the first action index for each
03543     // landing pad site.
03544     SmallVector<ActionEntry, 32> Actions;
03545     SmallVector<unsigned, 64> FirstActions;
03546     FirstActions.reserve(LandingPads.size());
03547 
03548     int FirstAction = 0;
03549     unsigned SizeActions = 0;
03550     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
03551       const LandingPadInfo *LP = LandingPads[i];
03552       const std::vector<int> &TypeIds = LP->TypeIds;
03553       const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
03554       unsigned SizeSiteActions = 0;
03555 
03556       if (NumShared < TypeIds.size()) {
03557         unsigned SizeAction = 0;
03558         ActionEntry *PrevAction = 0;
03559 
03560         if (NumShared) {
03561           const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
03562           assert(Actions.size());
03563           PrevAction = &Actions.back();
03564           SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
03565             TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
03566           for (unsigned j = NumShared; j != SizePrevIds; ++j) {
03567             SizeAction -=
03568               TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
03569             SizeAction += -PrevAction->NextAction;
03570             PrevAction = PrevAction->Previous;
03571           }
03572         }
03573 
03574         // Compute the actions.
03575         for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
03576           int TypeID = TypeIds[I];
03577           assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
03578           int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
03579           unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
03580 
03581           int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
03582           SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
03583           SizeSiteActions += SizeAction;
03584 
03585           ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
03586           Actions.push_back(Action);
03587 
03588           PrevAction = &Actions.back();
03589         }
03590 
03591         // Record the first action of the landing pad site.
03592         FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
03593       } // else identical - re-use previous FirstAction
03594 
03595       FirstActions.push_back(FirstAction);
03596 
03597       // Compute this sites contribution to size.
03598       SizeActions += SizeSiteActions;
03599     }
03600 
03601     // Compute the call-site table.  The entry for an invoke has a try-range
03602     // containing the call, a non-zero landing pad and an appropriate action.
03603     // The entry for an ordinary call has a try-range containing the call and
03604     // zero for the landing pad and the action.  Calls marked 'nounwind' have
03605     // no entry and must not be contained in the try-range of any entry - they
03606     // form gaps in the table.  Entries must be ordered by try-range address.
03607     SmallVector<CallSiteEntry, 64> CallSites;
03608 
03609     RangeMapType PadMap;
03610     // Invokes and nounwind calls have entries in PadMap (due to being bracketed
03611     // by try-range labels when lowered).  Ordinary calls do not, so appropriate
03612     // try-ranges for them need be deduced.
03613     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
03614       const LandingPadInfo *LandingPad = LandingPads[i];
03615       for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
03616         unsigned BeginLabel = LandingPad->BeginLabels[j];
03617         assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
03618         PadRange P = { i, j };
03619         PadMap[BeginLabel] = P;
03620       }
03621     }
03622 
03623     // The end label of the previous invoke or nounwind try-range.
03624     unsigned LastLabel = 0;
03625 
03626     // Whether there is a potentially throwing instruction (currently this means
03627     // an ordinary call) between the end of the previous try-range and now.
03628     bool SawPotentiallyThrowing = false;
03629 
03630     // Whether the last callsite entry was for an invoke.
03631     bool PreviousIsInvoke = false;
03632 
03633     // Visit all instructions in order of address.
03634     for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
03635          I != E; ++I) {
03636       for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
03637            MI != E; ++MI) {
03638         if (!MI->isLabel()) {
03639           SawPotentiallyThrowing |= MI->getDesc().isCall();
03640           continue;
03641         }
03642 
03643         unsigned BeginLabel = MI->getOperand(0).getImm();
03644         assert(BeginLabel && "Invalid label!");
03645 
03646         // End of the previous try-range?
03647         if (BeginLabel == LastLabel)
03648           SawPotentiallyThrowing = false;
03649 
03650         // Beginning of a new try-range?
03651         RangeMapType::iterator L = PadMap.find(BeginLabel);
03652         if (L == PadMap.end())
03653           // Nope, it was just some random label.
03654           continue;
03655 
03656         PadRange P = L->second;
03657         const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
03658 
03659         assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
03660                "Inconsistent landing pad map!");
03661 
03662         // If some instruction between the previous try-range and this one may
03663         // throw, create a call-site entry with no landing pad for the region
03664         // between the try-ranges.
03665         if (SawPotentiallyThrowing) {
03666           CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
03667           CallSites.push_back(Site);
03668           PreviousIsInvoke = false;
03669         }
03670 
03671         LastLabel = LandingPad->EndLabels[P.RangeIndex];
03672         assert(BeginLabel && LastLabel && "Invalid landing pad!");
03673 
03674         if (LandingPad->LandingPadLabel) {
03675           // This try-range is for an invoke.
03676           CallSiteEntry Site = {BeginLabel, LastLabel,
03677             LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
03678 
03679           // Try to merge with the previous call-site.
03680           if (PreviousIsInvoke) {
03681             CallSiteEntry &Prev = CallSites.back();
03682             if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
03683               // Extend the range of the previous entry.
03684               Prev.EndLabel = Site.EndLabel;
03685               continue;
03686             }
03687           }
03688 
03689           // Otherwise, create a new call-site.
03690           CallSites.push_back(Site);
03691           PreviousIsInvoke = true;
03692         } else {
03693           // Create a gap.
03694           PreviousIsInvoke = false;
03695         }
03696       }
03697     }
03698     // If some instruction between the previous try-range and the end of the
03699     // function may throw, create a call-site entry with no landing pad for the
03700     // region following the try-range.
03701     if (SawPotentiallyThrowing) {
03702       CallSiteEntry Site = {LastLabel, 0, 0, 0};
03703       CallSites.push_back(Site);
03704     }
03705 
03706     // Final tallies.
03707 
03708     // Call sites.
03709     const unsigned SiteStartSize  = sizeof(int32_t); // DW_EH_PE_udata4
03710     const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
03711     const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
03712     unsigned SizeSites = CallSites.size() * (SiteStartSize +
03713                                              SiteLengthSize +
03714                                              LandingPadSize);
03715     for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
03716       SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
03717 
03718     // Type infos.
03719     const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
03720     unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
03721 
03722     unsigned TypeOffset = sizeof(int8_t) + // Call site format
03723            TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
03724                           SizeSites + SizeActions + SizeTypes;
03725 
03726     unsigned TotalSize = sizeof(int8_t) + // LPStart format
03727                          sizeof(int8_t) + // TType format
03728            TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
03729                          TypeOffset;
03730 
03731     unsigned SizeAlign = (4 - TotalSize) & 3;
03732 
03733     // Begin the exception table.
03734     Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
03735     Asm->EmitAlignment(2, 0, 0, false);
03736     O << "GCC_except_table" << SubprogramCount << ":\n";
03737     for (unsigned i = 0; i != SizeAlign; ++i) {
03738       Asm->EmitInt8(0);
03739       Asm->EOL("Padding");
03740     }
03741     EmitLabel("exception", SubprogramCount);
03742 
03743     // Emit the header.
03744     Asm->EmitInt8(DW_EH_PE_omit);
03745     Asm->EOL("LPStart format (DW_EH_PE_omit)");
03746     Asm->EmitInt8(DW_EH_PE_absptr);
03747     Asm->EOL("TType format (DW_EH_PE_absptr)");
03748     Asm->EmitULEB128Bytes(TypeOffset);
03749     Asm->EOL("TType base offset");
03750     Asm->EmitInt8(DW_EH_PE_udata4);
03751     Asm->EOL("Call site format (DW_EH_PE_udata4)");
03752     Asm->EmitULEB128Bytes(SizeSites);
03753     Asm->EOL("Call-site table length");
03754 
03755     // Emit the landing pad site information.
03756     for (unsigned i = 0; i < CallSites.size(); ++i) {
03757       CallSiteEntry &S = CallSites[i];
03758       const char *BeginTag;
03759       unsigned BeginNumber;
03760 
03761       if (!S.BeginLabel) {
03762         BeginTag = "eh_func_begin";
03763         BeginNumber = SubprogramCount;
03764       } else {
03765         BeginTag = "label";
03766         BeginNumber = S.BeginLabel;
03767       }
03768 
03769       EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
03770                         true, true);
03771       Asm->EOL("Region start");
03772 
03773       if (!S.EndLabel) {
03774         EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
03775                        true);
03776       } else {
03777         EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
03778       }
03779       Asm->EOL("Region length");
03780 
03781       if (!S.PadLabel)
03782         Asm->EmitInt32(0);
03783       else
03784         EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
03785                           true, true);
03786       Asm->EOL("Landing pad");
03787 
03788       Asm->EmitULEB128Bytes(S.Action);
03789       Asm->EOL("Action");
03790     }
03791 
03792     // Emit the actions.
03793     for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
03794       ActionEntry &Action = Actions[I];
03795 
03796       Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
03797       Asm->EOL("TypeInfo index");
03798       Asm->EmitSLEB128Bytes(Action.NextAction);
03799       Asm->EOL("Next action");
03800     }
03801 
03802     // Emit the type ids.
03803     for (unsigned M = TypeInfos.size(); M; --M) {
03804       GlobalVariable *GV = TypeInfos[M - 1];
03805 
03806       PrintRelDirective();
03807 
03808       if (GV)
03809         O << Asm->getGlobalLinkName(GV);
03810       else
03811         O << "0";
03812 
03813       Asm->EOL("TypeInfo");
03814     }
03815 
03816     // Emit the filter typeids.
03817     for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
03818       unsigned TypeID = FilterIds[j];
03819       Asm->EmitULEB128Bytes(TypeID);
03820       Asm->EOL("Filter TypeInfo index");
03821     }
03822 
03823     Asm->EmitAlignment(2, 0, 0, false);
03824   }
03825 
03826 public:
03827   //===--------------------------------------------------------------------===//
03828   // Main entry points.
03829   //
03830   DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
03831   : Dwarf(OS, A, T, "eh")
03832   , shouldEmitTable(false)
03833   , shouldEmitMoves(false)
03834   , shouldEmitTableModule(false)
03835   , shouldEmitMovesModule(false)
03836   {}
03837 
03838   virtual ~DwarfException() {}
03839 
03840   /// SetModuleInfo - Set machine module information when it's known that pass
03841   /// manager has created it.  Set by the target AsmPrinter.
03842   void SetModuleInfo(MachineModuleInfo *mmi) {
03843     MMI = mmi;
03844   }
03845 
03846   /// BeginModule - Emit all exception information that should come prior to the
03847   /// content.
03848   void BeginModule(Module *M) {
03849     this->M = M;
03850   }
03851 
03852   /// EndModule - Emit all exception information that should come after the
03853   /// content.
03854   void EndModule() {
03855     if (shouldEmitMovesModule || shouldEmitTableModule) {
03856       const std::vector<Function *> Personalities = MMI->getPersonalities();
03857       for (unsigned i =0; i < Personalities.size(); ++i)
03858         EmitCommonEHFrame(Personalities[i], i);
03859 
03860       for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
03861              E = EHFrames.end(); I != E; ++I)
03862         EmitEHFrame(*I);
03863     }
03864   }
03865 
03866   /// BeginFunction - Gather pre-function exception information.  Assumes being
03867   /// emitted immediately after the function entry point.
03868   void BeginFunction(MachineFunction *MF) {
03869     this->MF = MF;
03870     shouldEmitTable = shouldEmitMoves = false;
03871     if (MMI && TAI->doesSupportExceptionHandling()) {
03872 
03873       // Map all labels and get rid of any dead landing pads.
03874       MMI->TidyLandingPads();
03875       // If any landing pads survive, we need an EH table.
03876       if (MMI->getLandingPads().size())
03877         shouldEmitTable = true;
03878 
03879       // See if we need frame move info.
03880       if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
03881         shouldEmitMoves = true;
03882 
03883       if (shouldEmitMoves || shouldEmitTable)
03884         // Assumes in correct section after the entry point.
03885         EmitLabel("eh_func_begin", ++SubprogramCount);
03886     }
03887     shouldEmitTableModule |= shouldEmitTable;
03888     shouldEmitMovesModule |= shouldEmitMoves;
03889   }
03890 
03891   /// EndFunction - Gather and emit post-function exception information.
03892   ///
03893   void EndFunction() {
03894     if (shouldEmitMoves || shouldEmitTable) {
03895       EmitLabel("eh_func_end", SubprogramCount);
03896       EmitExceptionTable();
03897 
03898       // Save EH frame information
03899       EHFrames.
03900         push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
03901                                     SubprogramCount,
03902                                     MMI->getPersonalityIndex(),
03903                                     MF->getFrameInfo()->hasCalls(),
03904                                     !MMI->getLandingPads().empty(),
03905                                     MMI->getFrameMoves(),
03906                                     MF->getFunction()));
03907       }
03908   }
03909 };
03910 
03911 } // End of namespace llvm
03912 
03913 //===----------------------------------------------------------------------===//
03914 
03915 /// Emit - Print the abbreviation using the specified Dwarf writer.
03916 ///
03917 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
03918   // Emit its Dwarf tag type.
03919   DD.getAsm()->EmitULEB128Bytes(Tag);
03920   DD.getAsm()->EOL(TagString(Tag));
03921 
03922   // Emit whether it has children DIEs.
03923   DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
03924   DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
03925 
03926   // For each attribute description.
03927   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
03928     const DIEAbbrevData &AttrData = Data[i];
03929 
03930     // Emit attribute type.
03931     DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
03932     DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
03933 
03934     // Emit form type.
03935     DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
03936     DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
03937   }
03938 
03939   // Mark end of abbreviation.
03940   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
03941   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
03942 }
03943 
03944 #ifndef NDEBUG
03945 void DIEAbbrev::print(std::ostream &O) {
03946   O << "Abbreviation @"
03947     << std::hex << (intptr_t)this << std::dec
03948     << "  "
03949     << TagString(Tag)
03950     << " "
03951     << ChildrenString(ChildrenFlag)
03952     << "\n";
03953 
03954   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
03955     O << "  "
03956       << AttributeString(Data[i].getAttribute())
03957       << "  "
03958       << FormEncodingString(Data[i].getForm())
03959       << "\n";
03960   }
03961 }
03962 void DIEAbbrev::dump() { print(cerr); }
03963 #endif
03964 
03965 //===----------------------------------------------------------------------===//
03966 
03967 #ifndef NDEBUG
03968 void DIEValue::dump() {
03969   print(cerr);
03970 }
03971 #endif
03972 
03973 //===----------------------------------------------------------------------===//
03974 
03975 /// EmitValue - Emit integer of appropriate size.
03976 ///
03977 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
03978   switch (Form) {
03979   case DW_FORM_flag:  // Fall thru
03980   case DW_FORM_ref1:  // Fall thru
03981   case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer);         break;
03982   case DW_FORM_ref2:  // Fall thru
03983   case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer);        break;
03984   case DW_FORM_ref4:  // Fall thru
03985   case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer);        break;
03986   case DW_FORM_ref8:  // Fall thru
03987   case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer);        break;
03988   case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
03989   case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
03990   default: assert(0 && "DIE Value form not supported yet");   break;
03991   }
03992 }
03993 
03994 /// SizeOf - Determine size of integer value in bytes.
03995 ///
03996 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
03997   switch (Form) {
03998   case DW_FORM_flag:  // Fall thru
03999   case DW_FORM_ref1:  // Fall thru
04000   case DW_FORM_data1: return sizeof(int8_t);
04001   case DW_FORM_ref2:  // Fall thru
04002   case DW_FORM_data2: return sizeof(int16_t);
04003   case DW_FORM_ref4:  // Fall thru
04004   case DW_FORM_data4: return sizeof(int32_t);
04005   case DW_FORM_ref8:  // Fall thru
04006   case DW_FORM_data8: return sizeof(int64_t);
04007   case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
04008   case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
04009   default: assert(0 && "DIE Value form not supported yet"); break;
04010   }
04011   return 0;
04012 }
04013 
04014 //===----------------------------------------------------------------------===//
04015 
04016 /// EmitValue - Emit string value.
04017 ///
04018 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
04019   DD.getAsm()->EmitString(String);
04020 }
04021 
04022 //===----------------------------------------------------------------------===//
04023 
04024 /// EmitValue - Emit label value.
04025 ///
04026 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
04027   bool IsSmall = Form == DW_FORM_data4;
04028   DD.EmitReference(Label, false, IsSmall);
04029 }
04030 
04031 /// SizeOf - Determine size of label value in bytes.
04032 ///
04033 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
04034   if (Form == DW_FORM_data4) return 4;
04035   return DD.getTargetData()->getPointerSize();
04036 }
04037 
04038 //===----------------------------------------------------------------------===//
04039 
04040 /// EmitValue - Emit label value.
04041 ///
04042 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
04043   bool IsSmall = Form == DW_FORM_data4;
04044   DD.EmitReference(Label, false, IsSmall);
04045 }
04046 
04047 /// SizeOf - Determine size of label value in bytes.
04048 ///
04049 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
04050   if (Form == DW_FORM_data4) return 4;
04051   return DD.getTargetData()->getPointerSize();
04052 }
04053 
04054 //===----------------------------------------------------------------------===//
04055 
04056 /// EmitValue - Emit delta value.
04057 ///
04058 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
04059   bool IsSmall = Form == DW_FORM_data4;
04060   DD.EmitSectionOffset(Label.Tag, Section.Tag,
04061                        Label.Number, Section.Number, IsSmall, IsEH, UseSet);
04062 }
04063 
04064 /// SizeOf - Determine size of delta value in bytes.
04065 ///
04066 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
04067   if (Form == DW_FORM_data4) return 4;
04068   return DD.getTargetData()->getPointerSize();
04069 }
04070 
04071 //===----------------------------------------------------------------------===//
04072 
04073 /// EmitValue - Emit delta value.
04074 ///
04075 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
04076   bool IsSmall = Form == DW_FORM_data4;
04077   DD.EmitDifference(LabelHi, LabelLo, IsSmall);
04078 }
04079 
04080 /// SizeOf - Determine size of delta value in bytes.
04081 ///
04082 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
04083   if (Form == DW_FORM_data4) return 4;
04084   return DD.getTargetData()->getPointerSize();
04085 }
04086 
04087 //===----------------------------------------------------------------------===//
04088 
04089 /// EmitValue - Emit debug information entry offset.
04090 ///
04091 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
04092   DD.getAsm()->EmitInt32(Entry->getOffset());
04093 }
04094 
04095 //===----------------------------------------------------------------------===//
04096 
04097 /// ComputeSize - calculate the size of the block.
04098 ///
04099 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
04100   if (!Size) {
04101     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
04102 
04103     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
04104       Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
04105     }
04106   }
04107   return Size;
04108 }
04109 
04110 /// EmitValue - Emit block data.
04111 ///
04112 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
04113   switch (Form) {
04114   case DW_FORM_block1: DD.getAsm()->EmitInt8(Size);         break;
04115   case DW_FORM_block2: DD.getAsm()->EmitInt16(Size);        break;
04116   case DW_FORM_block4: DD.getAsm()->EmitInt32(Size);        break;
04117   case DW_FORM_block:  DD.getAsm()->EmitULEB128Bytes(Size); break;
04118   default: assert(0 && "Improper form for block");          break;
04119   }
04120 
04121   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
04122 
04123   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
04124     DD.getAsm()->EOL();
04125     Values[i]->EmitValue(DD, AbbrevData[i].getForm());
04126   }
04127 }
04128 
04129 /// SizeOf - Determine size of block data in bytes.
04130 ///
04131 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
04132   switch (Form) {
04133   case DW_FORM_block1: return Size + sizeof(int8_t);
04134   case DW_FORM_block2: return Size + sizeof(int16_t);
04135   case DW_FORM_block4: return Size + sizeof(int32_t);
04136   case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
04137   default: assert(0 && "Improper form for block"); break;
04138   }
04139   return 0;
04140 }
04141 
04142 //===----------------------------------------------------------------------===//
04143 /// DIE Implementation
04144 
04145 DIE::~DIE() {
04146   for (unsigned i = 0, N = Children.size(); i < N; ++i)
04147     delete Children[i];
04148 }
04149 
04150 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
04151 ///
04152 void DIE::AddSiblingOffset() {
04153   DIEInteger *DI = new DIEInteger(0);
04154   Values.insert(Values.begin(), DI);
04155   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
04156 }
04157 
04158 /// Profile - Used to gather unique data for the value folding set.
04159 ///
04160 void DIE::Profile(FoldingSetNodeID &ID) {
04161   Abbrev.Profile(ID);
04162 
04163   for (unsigned i = 0, N = Children.size(); i < N; ++i)
04164     ID.AddPointer(Children[i]);
04165 
04166   for (unsigned j = 0, M = Values.size(); j < M; ++j)
04167     ID.AddPointer(Values[j]);
04168 }
04169 
04170 #ifndef NDEBUG
04171 void DIE::print(std::ostream &O, unsigned IncIndent) {
04172   static unsigned IndentCount = 0;
04173   IndentCount += IncIndent;
04174   const std::string Indent(IndentCount, ' ');
04175   bool isBlock = Abbrev.getTag() == 0;
04176 
04177   if (!isBlock) {
04178     O << Indent
04179       << "Die: "
04180       << "0x" << std::hex << (intptr_t)this << std::dec
04181       << ", Offset: " << Offset
04182       << ", Size: " << Size
04183       << "\n";
04184 
04185     O << Indent
04186       << TagString(Abbrev.getTag())
04187       << " "
04188       << ChildrenString(Abbrev.getChildrenFlag());
04189   } else {
04190     O << "Size: " << Size;
04191   }
04192   O << "\n";
04193 
04194   const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
04195 
04196   IndentCount += 2;
04197   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
04198     O << Indent;
04199 
04200     if (!isBlock)
04201       O << AttributeString(Data[i].getAttribute());
04202     else
04203       O << "Blk[" << i << "]";
04204 
04205     O <<  "  "
04206       << FormEncodingString(Data[i].getForm())
04207       << " ";
04208     Values[i]->print(O);
04209     O << "\n";
04210   }
04211   IndentCount -= 2;
04212 
04213   for (unsigned j = 0, M = Children.size(); j < M; ++j) {
04214     Children[j]->print(O, 4);
04215   }
04216 
04217   if (!isBlock) O << "\n";
04218   IndentCount -= IncIndent;
04219 }
04220 
04221 void DIE::dump() {
04222   print(cerr);
04223 }
04224 #endif
04225 
04226 //===----------------------------------------------------------------------===//
04227 /// DwarfWriter Implementation
04228 ///
04229 
04230 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
04231 }
04232 
04233 DwarfWriter::~DwarfWriter() {
04234   delete DE;
04235   delete DD;
04236 }
04237 
04238 /// BeginModule - Emit all Dwarf sections that should come prior to the
04239 /// content.
04240 void DwarfWriter::BeginModule(Module *M,
04241                               MachineModuleInfo *MMI,
04242                               raw_ostream &OS, AsmPrinter *A,
04243                               const TargetAsmInfo *T) {
04244   DE = new DwarfException(OS, A, T);
04245   DD = new DwarfDebug(OS, A, T);
04246   DE->BeginModule(M);
04247   DD->BeginModule(M);
04248   DD->SetDebugInfo(MMI);
04249   DE->SetModuleInfo(MMI);
04250 }
04251 
04252 /// EndModule - Emit all Dwarf sections that should come after the content.
04253 ///
04254 void DwarfWriter::EndModule() {
04255   DE->EndModule();
04256   DD->EndModule();
04257 }
04258 
04259 /// BeginFunction - Gather pre-function debug information.  Assumes being
04260 /// emitted immediately after the function entry point.
04261 void DwarfWriter::BeginFunction(MachineFunction *MF) {
04262   DE->BeginFunction(MF);
04263   DD->BeginFunction(MF);
04264 }
04265 
04266 /// EndFunction - Gather and emit post-function debug information.
04267 ///
04268 void DwarfWriter::EndFunction(MachineFunction *MF) {
04269   DD->EndFunction(MF);
04270   DE->EndFunction();
04271 
04272   if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
04273     // Clear function debug information.
04274     MMI->EndFunction();
04275 }
04276 
04277 /// ValidDebugInfo - Return true if V represents valid debug info value.
04278 bool DwarfWriter::ValidDebugInfo(Value *V) {
04279   return DD && DD->ValidDebugInfo(V);
04280 }
04281 
04282 /// RecordSourceLine - Records location information and associates it with a 
04283 /// label. Returns a unique label ID used to generate a label and provide
04284 /// correspondence to the source line list.
04285 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col, 
04286                                        unsigned Src) {
04287   return DD->RecordSourceLine(Line, Col, Src);
04288 }
04289 
04290 /// RecordSource - Register a source file with debug info. Returns an source
04291 /// ID.
04292 unsigned DwarfWriter::RecordSource(const std::string &Dir, 
04293                                    const std::string &File) {
04294   return DD->RecordSource(Dir, File);
04295 }
04296 
04297 /// RecordRegionStart - Indicate the start of a region.
04298 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
04299   return DD->RecordRegionStart(V);
04300 }
04301 
04302 /// RecordRegionEnd - Indicate the end of a region.
04303 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
04304   return DD->RecordRegionEnd(V);
04305 }
04306 
04307 /// getRecordSourceLineCount - Count source lines.
04308 unsigned DwarfWriter::getRecordSourceLineCount() {
04309   return DD->getRecordSourceLineCount();
04310 }
04311 
04312 /// RecordVariable - Indicate the declaration of  a local variable.
04313 ///
04314 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
04315   DD->RecordVariable(GV, FrameIndex);
04316 }
04317