Refactor address attributes. Add base register to frame info.
[oota-llvm.git] / lib / CodeGen / DwarfWriter.cpp
index fee0a654d30213afac2dab078831382dceed8ced..43fbb3b902fe949a7f34e2ac249575fd539282e2 100644 (file)
 #include "llvm/Type.h"
 #include "llvm/CodeGen/AsmPrinter.h"
 #include "llvm/CodeGen/MachineDebugInfo.h"
+#include "llvm/CodeGen/MachineLocation.h"
 #include "llvm/Support/Dwarf.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Mangler.h"
+#include "llvm/Target/MRegisterInfo.h"
 #include "llvm/Target/TargetMachine.h"
 
 #include <iostream>
 
 using namespace llvm;
-using namespace dwarf;
+using namespace llvm::dwarf;
 
 static cl::opt<bool>
 DwarfVerbose("dwarf-verbose", cl::Hidden,
@@ -37,9 +39,55 @@ namespace llvm {
 //===----------------------------------------------------------------------===//
 // Forward declarations.
 //
-class CompileUnit;
 class DIE;
 
+//===----------------------------------------------------------------------===//
+// CompileUnit - This dwarf writer support class manages information associate
+// with a source file.
+class CompileUnit {
+private:
+  CompileUnitDesc *Desc;                // Compile unit debug descriptor.
+  unsigned ID;                          // File ID for source.
+  DIE *Die;                             // Compile unit debug information entry.
+  std::map<std::string, DIE *> Globals; // A map of globally visible named
+                                        // entities for this unit.
+  std::map<DebugInfoDesc *, DIE *> DescToDieMap;
+                                        // Tracks the mapping of unit level
+                                        // debug informaton descriptors to debug
+                                        // information entries.
+
+public:
+  CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
+  : Desc(CUD)
+  , ID(I)
+  , Die(D)
+  , Globals()
+  , DescToDieMap()
+  {}
+  
+  ~CompileUnit();
+  
+  // Accessors.
+  CompileUnitDesc *getDesc() const { return Desc; }
+  unsigned getID()           const { return ID; }
+  DIE* getDie()              const { return Die; }
+  std::map<std::string, DIE *> &getGlobals() { return Globals; }
+  
+  /// hasContent - Return true if this compile unit has something to write out.
+  ///
+  bool hasContent() const;
+  
+  /// AddGlobal - Add a new global entity to the compile unit.
+  ///
+  void AddGlobal(const std::string &Name, DIE *Die);
+  
+  /// getDieMapSlotFor - Returns the debug information entry map slot for the
+  /// specified debug descriptor.
+  DIE *&getDieMapSlotFor(DebugInfoDesc *DD) {
+    return DescToDieMap[DD];
+  }
+};
+
 //===----------------------------------------------------------------------===//
 // DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
 // Dwarf abbreviation.
@@ -54,7 +102,7 @@ public:
   , Form(F)
   {}
   
-  // Accessors
+  // Accessors.
   unsigned getAttribute() const { return Attribute; }
   unsigned getForm()      const { return Form; }
   
@@ -96,7 +144,7 @@ public:
   {}
   ~DIEAbbrev() {}
   
-  // Accessors
+  // Accessors.
   unsigned getTag()                           const { return Tag; }
   unsigned getChildrenFlag()                  const { return ChildrenFlag; }
   const std::vector<DIEAbbrevData> &getData() const { return Data; }
@@ -116,6 +164,12 @@ public:
     Data.push_back(DIEAbbrevData(Attribute, Form));
   }
   
+  /// AddFirstAttribute - Adds a set of attribute information to the front
+  /// of the abbreviation.
+  void AddFirstAttribute(unsigned Attribute, unsigned Form) {
+    Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
+  }
+  
   /// Emit - Print the abbreviation using the specified Dwarf writer.
   ///
   void Emit(const DwarfWriter &DW) const; 
@@ -137,7 +191,8 @@ public:
     isLabel,
     isAsIsLabel,
     isDelta,
-    isEntry
+    isEntry,
+    isBlock
   };
   
   unsigned Type;                      // Type of the value
@@ -171,6 +226,10 @@ public:
   static bool classof(const DIEInteger *) { return true; }
   static bool classof(const DIEValue *I)  { return I->Type == isInteger; }
   
+  /// BestForm - Choose the best form for integer.
+  ///
+  unsigned BestForm(bool IsSigned);
+
   /// EmitValue - Emit integer of appropriate size.
   ///
   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
@@ -279,15 +338,81 @@ struct DIEntry : public DIEValue {
   static bool classof(const DIEntry *)   { return true; }
   static bool classof(const DIEValue *E) { return E->Type == isEntry; }
   
-  /// EmitValue - Emit delta value.
+  /// EmitValue - Emit debug information entry offset.
   ///
   virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
   
-  /// SizeOf - Determine size of delta value in bytes.
+  /// SizeOf - Determine size of debug information entry in bytes.
   ///
   virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
 };
 
+//===----------------------------------------------------------------------===//
+// DIEBlock - A block of values.  Primarily used for location expressions.
+//
+struct DIEBlock : public DIEValue {
+  unsigned Size;                        // Size in bytes excluding size header.
+  std::vector<unsigned> Forms;          // Data forms.
+  std::vector<DIEValue *> Values;       // Block values.
+  
+  DIEBlock()
+  : DIEValue(isBlock)
+  , Size(0)
+  , Forms()
+  , Values()
+  {}
+  ~DIEBlock();
+
+  // Implement isa/cast/dyncast.
+  static bool classof(const DIEBlock *)  { return true; }
+  static bool classof(const DIEValue *E) { return E->Type == isBlock; }
+  
+  /// ComputeSize - calculate the size of the block.
+  ///
+  unsigned ComputeSize(DwarfWriter &DW);
+  
+  /// BestForm - Choose the best form for data.
+  ///
+  unsigned BestForm();
+
+  /// EmitValue - Emit block data.
+  ///
+  virtual void EmitValue(const DwarfWriter &DW, unsigned Form) const;
+  
+  /// SizeOf - Determine size of block data in bytes.
+  ///
+  virtual unsigned SizeOf(const DwarfWriter &DW, unsigned Form) const;
+
+  /// AddUInt - Add an unsigned integer value.
+  ///
+  void AddUInt(unsigned Form, uint64_t Integer);
+
+  /// AddSInt - Add an signed integer value.
+  ///
+  void AddSInt(unsigned Form, int64_t Integer);
+      
+  /// AddString - Add a std::string value.
+  ///
+  void AddString(unsigned Form, const std::string &String);
+      
+  /// AddLabel - Add a Dwarf label value.
+  ///
+  void AddLabel(unsigned Form, const DWLabel &Label);
+      
+  /// AddObjectLabel - Add a non-Dwarf label value.
+  ///
+  void AddObjectLabel(unsigned Form, const std::string &Label);
+      
+  /// AddDelta - Add a label delta value.
+  ///
+  void AddDelta(unsigned Form, const DWLabel &Hi, const DWLabel &Lo);
+      
+  /// AddDIEntry - Add a DIE value.
+  ///
+  void AddDIEntry(unsigned Form, DIE *Entry);
+
+};
+
 //===----------------------------------------------------------------------===//
 // DIE - A structured debug information entry.  Has an abbreviation which
 // describes it's organization.
@@ -304,7 +429,7 @@ public:
   DIE(unsigned Tag);
   ~DIE();
   
-  // Accessors
+  // Accessors.
   unsigned   getAbbrevID()                   const { return AbbrevID; }
   unsigned   getOffset()                     const { return Offset; }
   unsigned   getSize()                       const { return Size; }
@@ -316,6 +441,10 @@ public:
   /// SiblingOffset - Return the offset of the debug information entry's
   /// sibling.
   unsigned SiblingOffset() const { return Offset + Size; }
+  
+  /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
+  ///
+  void AddSiblingOffset();
 
   /// AddUInt - Add an unsigned integer attribute data and value.
   ///
@@ -344,10 +473,14 @@ public:
   void AddDelta(unsigned Attribute, unsigned Form,
                 const DWLabel &Hi, const DWLabel &Lo);
       
-  ///  AddDIEntry - Add a DIE attribute data and value.
+  /// AddDIEntry - Add a DIE attribute data and value.
   ///
   void AddDIEntry(unsigned Attribute, unsigned Form, DIE *Entry);
 
+  /// AddBlock - Add block data.
+  ///
+  void AddBlock(unsigned Attribute, unsigned Form, DIEBlock *Block);
+
   /// Complete - Indicate that all attributes have been added and
   /// ready to get an abbreviation ID.
   ///
@@ -361,6 +494,24 @@ public:
 
 //===----------------------------------------------------------------------===//
 
+CompileUnit::~CompileUnit() {
+  delete Die;
+}
+
+/// hasContent - Return true if this compile unit has something to write out.
+///
+bool CompileUnit::hasContent() const {
+  return !Die->getChildren().empty();
+}
+
+/// AddGlobal - Add a new global entity to the compile unit.
+///
+void CompileUnit::AddGlobal(const std::string &Name, DIE *Die) {
+  Globals[Name] = Die;
+}
+
+//===----------------------------------------------------------------------===//
+
 /// operator== - Used by UniqueVector to locate entry.
 ///
 bool DIEAbbrev::operator==(const DIEAbbrev &DA) const {
@@ -441,14 +592,33 @@ void DIEAbbrev::Emit(const DwarfWriter &DW) const {
 
 //===----------------------------------------------------------------------===//
 
+/// BestForm - Choose the best form for integer.
+///
+unsigned DIEInteger::BestForm(bool IsSigned) {
+  if (IsSigned) {
+    if ((char)Integer == (signed)Integer)   return DW_FORM_data1;
+    if ((short)Integer == (signed)Integer)  return DW_FORM_data2;
+    if ((int)Integer == (signed)Integer)    return DW_FORM_data4;
+  } else {
+    if ((unsigned char)Integer == Integer)  return DW_FORM_data1;
+    if ((unsigned short)Integer == Integer) return DW_FORM_data2;
+    if ((unsigned int)Integer == Integer)   return DW_FORM_data4;
+  }
+  return DW_FORM_data8;
+}
+    
 /// EmitValue - Emit integer of appropriate size.
 ///
 void DIEInteger::EmitValue(const DwarfWriter &DW, unsigned Form) const {
   switch (Form) {
   case DW_FORM_flag:  // Fall thru
+  case DW_FORM_ref1:  // Fall thru
   case DW_FORM_data1: DW.EmitInt8(Integer);         break;
+  case DW_FORM_ref2:  // Fall thru
   case DW_FORM_data2: DW.EmitInt16(Integer);        break;
+  case DW_FORM_ref4:  // Fall thru
   case DW_FORM_data4: DW.EmitInt32(Integer);        break;
+  case DW_FORM_ref8:  // Fall thru
   case DW_FORM_data8: DW.EmitInt64(Integer);        break;
   case DW_FORM_udata: DW.EmitULEB128Bytes(Integer); break;
   case DW_FORM_sdata: DW.EmitSLEB128Bytes(Integer); break;
@@ -461,9 +631,13 @@ void DIEInteger::EmitValue(const DwarfWriter &DW, unsigned Form) const {
 unsigned DIEInteger::SizeOf(const DwarfWriter &DW, unsigned Form) const {
   switch (Form) {
   case DW_FORM_flag:  // Fall thru
+  case DW_FORM_ref1:  // Fall thru
   case DW_FORM_data1: return sizeof(int8_t);
+  case DW_FORM_ref2:  // Fall thru
   case DW_FORM_data2: return sizeof(int16_t);
+  case DW_FORM_ref4:  // Fall thru
   case DW_FORM_data4: return sizeof(int32_t);
+  case DW_FORM_ref8:  // Fall thru
   case DW_FORM_data8: return sizeof(int64_t);
   case DW_FORM_udata: return DW.SizeULEB128(Integer);
   case DW_FORM_sdata: return DW.SizeSLEB128(Integer);
@@ -505,19 +679,13 @@ unsigned DIEDwarfLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
 /// EmitValue - Emit label value.
 ///
 void DIEObjectLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
-  DW.EmitInt8(sizeof(int8_t) + DW.getAddressSize());
-  DW.EOL("DW_FORM_block1 length");
-  
-  DW.EmitInt8(DW_OP_addr);
-  DW.EOL("DW_OP_addr");
-  
   DW.EmitReference(Label);
 }
 
 /// SizeOf - Determine size of label value in bytes.
 ///
 unsigned DIEObjectLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
-  return sizeof(int8_t) + sizeof(int8_t) + DW.getAddressSize();
+  return DW.getAddressSize();
 }
     
 //===----------------------------------------------------------------------===//
@@ -535,13 +703,13 @@ unsigned DIEDelta::SizeOf(const DwarfWriter &DW, unsigned Form) const {
 }
 
 //===----------------------------------------------------------------------===//
-/// EmitValue - Emit extry offset.
+/// EmitValue - Emit debug information entry offset.
 ///
 void DIEntry::EmitValue(const DwarfWriter &DW, unsigned Form) const {
   DW.EmitInt32(Entry->getOffset());
 }
 
-/// SizeOf - Determine size of label value in bytes.
+/// SizeOf - Determine size of debug information entry value in bytes.
 ///
 unsigned DIEntry::SizeOf(const DwarfWriter &DW, unsigned Form) const {
   return sizeof(int32_t);
@@ -549,6 +717,115 @@ unsigned DIEntry::SizeOf(const DwarfWriter &DW, unsigned Form) const {
     
 //===----------------------------------------------------------------------===//
 
+DIEBlock::~DIEBlock() {
+  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
+    delete Values[i];
+  }
+}
+
+/// ComputeSize - calculate the size of the block.
+///
+unsigned DIEBlock::ComputeSize(DwarfWriter &DW) {
+  Size = 0;
+  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
+    Size += Values[i]->SizeOf(DW, Forms[i]);
+  }
+  return Size;
+}
+
+/// BestForm - Choose the best form for data.
+///
+unsigned DIEBlock::BestForm() {
+  if ((unsigned char)Size == Size)  return DW_FORM_block1;
+  if ((unsigned short)Size == Size) return DW_FORM_block2;
+  if ((unsigned int)Size == Size)   return DW_FORM_block4;
+  return DW_FORM_block;
+}
+
+/// EmitValue - Emit block data.
+///
+void DIEBlock::EmitValue(const DwarfWriter &DW, unsigned Form) const {
+  switch (Form) {
+  case DW_FORM_block1: DW.EmitInt8(Size);         break;
+  case DW_FORM_block2: DW.EmitInt16(Size);        break;
+  case DW_FORM_block4: DW.EmitInt32(Size);        break;
+  case DW_FORM_block:  DW.EmitULEB128Bytes(Size); break;
+  default: assert(0 && "Improper form for block"); break;
+  }
+  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
+    DW.EOL("");
+    Values[i]->EmitValue(DW, Forms[i]);
+  }
+}
+
+/// SizeOf - Determine size of block data in bytes.
+///
+unsigned DIEBlock::SizeOf(const DwarfWriter &DW, unsigned Form) const {
+  switch (Form) {
+  case DW_FORM_block1: return Size + sizeof(int8_t);
+  case DW_FORM_block2: return Size + sizeof(int16_t);
+  case DW_FORM_block4: return Size + sizeof(int32_t);
+  case DW_FORM_block: return Size + DW.SizeULEB128(Size);
+  default: assert(0 && "Improper form for block"); break;
+  }
+  return 0;
+}
+
+/// AddUInt - Add an unsigned integer value.
+///
+void DIEBlock::AddUInt(unsigned Form, uint64_t Integer) {
+  DIEInteger *DI = new DIEInteger(Integer);
+  Values.push_back(DI);
+  if (Form == 0) Form = DI->BestForm(false);
+  Forms.push_back(Form);
+}
+
+/// AddSInt - Add an signed integer value.
+///
+void DIEBlock::AddSInt(unsigned Form, int64_t Integer) {
+  DIEInteger *DI = new DIEInteger(Integer);
+  Values.push_back(DI);
+  if (Form == 0) Form = DI->BestForm(true);
+  Forms.push_back(Form);
+}
+    
+/// AddString - Add a std::string value.
+///
+void DIEBlock::AddString(unsigned Form, const std::string &String) {
+  Values.push_back(new DIEString(String));
+  Forms.push_back(Form);
+}
+    
+/// AddLabel - Add a Dwarf label value.
+///
+void DIEBlock::AddLabel(unsigned Form, const DWLabel &Label) {
+  Values.push_back(new DIEDwarfLabel(Label));
+  Forms.push_back(Form);
+}
+    
+/// AddObjectLabel - Add a non-Dwarf label value.
+///
+void DIEBlock::AddObjectLabel(unsigned Form, const std::string &Label) {
+  Values.push_back(new DIEObjectLabel(Label));
+  Forms.push_back(Form);
+}
+    
+/// AddDelta - Add a label delta value.
+///
+void DIEBlock::AddDelta(unsigned Form, const DWLabel &Hi, const DWLabel &Lo) {
+  Values.push_back(new DIEDelta(Hi, Lo));
+  Forms.push_back(Form);
+}
+    
+/// AddDIEntry - Add a DIE value.
+///
+void DIEBlock::AddDIEntry(unsigned Form, DIE *Entry) {
+  Values.push_back(new DIEntry(Entry));
+  Forms.push_back(Form);
+}
+
+//===----------------------------------------------------------------------===//
+
 DIE::DIE(unsigned Tag)
 : Abbrev(new DIEAbbrev(Tag, DW_CHILDREN_no))
 , AbbrevID(0)
@@ -570,70 +847,78 @@ DIE::~DIE() {
   }
 }
     
+/// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
+///
+void DIE::AddSiblingOffset() {
+  DIEInteger *DI = new DIEInteger(0);
+  Values.insert(Values.begin(), DI);
+  Abbrev->AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
+}
+
 /// AddUInt - Add an unsigned integer attribute data and value.
 ///
 void DIE::AddUInt(unsigned Attribute, unsigned Form, uint64_t Integer) {
-  if (Form == 0) {
-      if ((unsigned char)Integer == Integer)       Form = DW_FORM_data1;
-      else if ((unsigned short)Integer == Integer) Form = DW_FORM_data2;
-      else if ((unsigned int)Integer == Integer)   Form = DW_FORM_data4;
-      else                                         Form = DW_FORM_data8;
-  }
+  DIEInteger *DI = new DIEInteger(Integer);
+  Values.push_back(DI);
+  if (!Form) Form = DI->BestForm(false);
   Abbrev->AddAttribute(Attribute, Form);
-  Values.push_back(new DIEInteger(Integer));
 }
     
 /// AddSInt - Add an signed integer attribute data and value.
 ///
 void DIE::AddSInt(unsigned Attribute, unsigned Form, int64_t Integer) {
-  if (Form == 0) {
-      if ((char)Integer == Integer)       Form = DW_FORM_data1;
-      else if ((short)Integer == Integer) Form = DW_FORM_data2;
-      else if ((int)Integer == Integer)   Form = DW_FORM_data4;
-      else                                Form = DW_FORM_data8;
-  }
+  DIEInteger *DI = new DIEInteger(Integer);
+  Values.push_back(DI);
+  if (!Form) Form = DI->BestForm(true);
   Abbrev->AddAttribute(Attribute, Form);
-  Values.push_back(new DIEInteger(Integer));
 }
     
 /// AddString - Add a std::string attribute data and value.
 ///
 void DIE::AddString(unsigned Attribute, unsigned Form,
                     const std::string &String) {
-  Abbrev->AddAttribute(Attribute, Form);
   Values.push_back(new DIEString(String));
+  Abbrev->AddAttribute(Attribute, Form);
 }
     
 /// AddLabel - Add a Dwarf label attribute data and value.
 ///
 void DIE::AddLabel(unsigned Attribute, unsigned Form,
                    const DWLabel &Label) {
-  Abbrev->AddAttribute(Attribute, Form);
   Values.push_back(new DIEDwarfLabel(Label));
+  Abbrev->AddAttribute(Attribute, Form);
 }
     
 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
 ///
 void DIE::AddObjectLabel(unsigned Attribute, unsigned Form,
                          const std::string &Label) {
-  Abbrev->AddAttribute(Attribute, Form);
   Values.push_back(new DIEObjectLabel(Label));
+  Abbrev->AddAttribute(Attribute, Form);
 }
     
 /// AddDelta - Add a label delta attribute data and value.
 ///
 void DIE::AddDelta(unsigned Attribute, unsigned Form,
                    const DWLabel &Hi, const DWLabel &Lo) {
-  Abbrev->AddAttribute(Attribute, Form);
   Values.push_back(new DIEDelta(Hi, Lo));
+  Abbrev->AddAttribute(Attribute, Form);
 }
     
 /// AddDIEntry - Add a DIE attribute data and value.
 ///
-void DIE::AddDIEntry(unsigned Attribute,
-                     unsigned Form, DIE *Entry) {
-  Abbrev->AddAttribute(Attribute, Form);
+void DIE::AddDIEntry(unsigned Attribute, unsigned Form, DIE *Entry) {
   Values.push_back(new DIEntry(Entry));
+  Abbrev->AddAttribute(Attribute, Form);
+}
+
+/// AddBlock - Add block data.
+///
+void DIE::AddBlock(unsigned Attribute, unsigned Form, DIEBlock *Block) {
+  assert(Block->Size && "Block size has not been computed");
+  Values.push_back(Block);
+  if (!Form) Form = Block->BestForm();
+  Abbrev->AddAttribute(Attribute, Form);
 }
 
 /// Complete - Indicate that all attributes have been added and ready to get an
@@ -667,7 +952,7 @@ void DwarfWriter::PrintHex(int Value) const {
 /// EOL - Print a newline character to asm stream.  If a comment is present
 /// then it will be printed first.  Comments should not contain '\n'.
 void DwarfWriter::EOL(const std::string &Comment) const {
-  if (DwarfVerbose) {
+  if (DwarfVerbose && !Comment.empty()) {
     O << "\t"
       << Asm->CommentString
       << " "
@@ -676,6 +961,12 @@ void DwarfWriter::EOL(const std::string &Comment) const {
   O << "\n";
 }
 
+/// EmitAlign - Print a align directive.
+///
+void DwarfWriter::EmitAlign(unsigned Alignment) const {
+  O << Asm->AlignDirective << Alignment << "\n";
+}
+
 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
 /// unsigned leb128 value.
 void DwarfWriter::EmitULEB128Bytes(unsigned Value) const {
@@ -911,116 +1202,59 @@ DWLabel DwarfWriter::NewString(const std::string &String) {
   return DWLabel("string", StringID);
 }
 
-/// NewBasicType - Creates a new basic type if necessary, then adds to the
-/// owner.
-/// FIXME - Should never be needed.
-DIE *DwarfWriter::NewBasicType(DIE *Owner, Type *Ty) {
-  DIE *&Slot = TypeToDieMap[Ty];
-  if (Slot) return Slot;
-  
-  const char *Name;
-  unsigned Size;
-  unsigned Encoding = 0;
-  
-  switch (Ty->getTypeID()) {
-  case Type::UByteTyID:
-    Name = "unsigned char";
-    Size = 1;
-    Encoding = DW_ATE_unsigned_char;
-    break;
-  case Type::SByteTyID:
-    Name = "char";
-    Size = 1;
-    Encoding = DW_ATE_signed_char;
-    break;
-  case Type::UShortTyID:
-    Name = "unsigned short";
-    Size = 2;
-    Encoding = DW_ATE_unsigned;
-    break;
-  case Type::ShortTyID:
-    Name = "short";
-    Size = 2;
-    Encoding = DW_ATE_signed;
-    break;
-  case Type::UIntTyID:
-    Name = "unsigned int";
-    Size = 4;
-    Encoding = DW_ATE_unsigned;
-    break;
-  case Type::IntTyID:
-    Name = "int";
-    Size = 4;
-    Encoding = DW_ATE_signed;
-    break;
-  case Type::ULongTyID:
-    Name = "unsigned long long";
-    Size = 7;
-    Encoding = DW_ATE_unsigned;
-    break;
-  case Type::LongTyID:
-    Name = "long long";
-    Size = 7;
-    Encoding = DW_ATE_signed;
-    break;
-  case Type::FloatTyID:
-    Name = "float";
-    Size = 4;
-    Encoding = DW_ATE_float;
-    break;
-  case Type::DoubleTyID:
-    Name = "double";
-    Size = 8;
-    Encoding = DW_ATE_float;
-    break;
-  default: 
-    // FIXME - handle more complex types.
-    Name = "unknown";
-    Size = 1;
-    Encoding = DW_ATE_address;
-    break;
+/// AddSourceLine - Add location information to specified debug information
+/// entry.
+void DwarfWriter::AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
+  if (File && Line) {
+    CompileUnit *FileUnit = FindCompileUnit(File);
+    unsigned FileID = FileUnit->getID();
+    Die->AddUInt(DW_AT_decl_file, 0, FileID);
+    Die->AddUInt(DW_AT_decl_line, 0, Line);
   }
-  
-  // construct the type DIE.
-  Slot = new DIE(DW_TAG_base_type);
-  Slot->AddString(DW_AT_name,      DW_FORM_string, Name);
-  Slot->AddUInt  (DW_AT_byte_size, 0,              Size);
-  Slot->AddUInt  (DW_AT_encoding,  DW_FORM_data1,  Encoding);
-  
-  // Add to context owner.
-  Owner->AddChild(Slot);
-  
-  return Slot;
 }
 
-/// NewGlobalType - Make the type visible globally using the given name.
-///
-void DwarfWriter::NewGlobalType(const std::string &Name, DIE *Type) {
-  assert(!GlobalTypes[Name] && "Duplicate global type");
-  GlobalTypes[Name] = Type;
+/// AddAddress - Add an address attribute to a die based on the location
+/// provided.
+void DwarfWriter::AddAddress(DIE *Die, unsigned Attribute,
+                             MachineLocation &Location) {
+  DIEBlock *Block = new DIEBlock();
+  if (Location.isRegister()) {
+    Block->AddUInt(DW_FORM_data1, DW_OP_reg0 + Location.getRegister());
+  } else {
+    Block->AddUInt(DW_FORM_data1, DW_OP_breg0 + Location.getRegister());
+    Block->AddUInt(DW_FORM_sdata, Location.getOffset());
+  }
+  Block->ComputeSize(*this);
+  Die->AddBlock(Attribute, 0, Block);
 }
 
-/// NewGlobalEntity - Make the entity visible globally using the given name.
-///
-void DwarfWriter::NewGlobalEntity(const std::string &Name, DIE *Entity) {
-  assert(!GlobalEntities[Name] && "Duplicate global variable or function");
-  GlobalEntities[Name] = Entity;
+/// getDieMapSlotFor - Returns the debug information entry map slot for the
+/// specified debug descriptor.
+DIE *&DwarfWriter::getDieMapSlotFor(DebugInfoDesc *DD) {
+  return DescToDieMap[DD];
 }
-
+                                 
 /// NewType - Create a new type DIE.
 ///
-DIE *DwarfWriter::NewType(DIE *Unit, TypeDesc *TyDesc) {
-  // FIXME - hack to get around NULL types short term.
-  if (!TyDesc)  return NewBasicType(Unit, Type::IntTy);
+DIE *DwarfWriter::NewType(DIE *Context, TypeDesc *TyDesc, CompileUnit *Unit) {
+  if (!TyDesc) {
+    // FIXME - Hack for missing types
+    DIE *Die = new DIE(DW_TAG_base_type);
+    Die->AddUInt(DW_AT_byte_size, 0, 4);
+    Die->AddUInt(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
+    Unit->getDie()->AddChild(Die);
+    return Die;
+  }
+  
+  // FIXME - Should handle other contexts that compile units.
 
   // Check for pre-existence.
-  DIE *&Slot = DescToDieMap[TyDesc];
+  DIE *&Slot = Unit->getDieMapSlotFor(TyDesc);
   if (Slot) return Slot;
 
   // Get core information.
   const std::string &Name = TyDesc->getName();
-  // FIXME - handle larger sizes.
-  unsigned Size = TyDesc->getSize() >> 3;
+  uint64_t Size = TyDesc->getSize() >> 3;
   
   DIE *Ty = NULL;
   
@@ -1030,21 +1264,135 @@ DIE *DwarfWriter::NewType(DIE *Unit, TypeDesc *TyDesc) {
     unsigned Encoding = BasicTy->getEncoding();
     Ty->AddUInt  (DW_AT_encoding,  DW_FORM_data1, Encoding);
   } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
-    // Determine which derived type.
-    unsigned T = 0;
-    switch (DerivedTy->getTag()) {
-    case DI_TAG_typedef:   T = DW_TAG_typedef;        break;
-    case DI_TAG_pointer:   T = DW_TAG_pointer_type;   break;
-    case DI_TAG_reference: T = DW_TAG_reference_type; break;
-    default: assert( 0 && "Unknown tag on derived type");
-    }
-    
     // Create specific DIE.
-    Slot = Ty = new DIE(T);
+    Slot = Ty = new DIE(DerivedTy->getTag());
     
     // Map to main type, void will not have a type.
     if (TypeDesc *FromTy = DerivedTy->getFromType()) {
-       Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4, NewType(Unit, FromTy));
+      Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
+                     NewType(Context, FromTy, Unit));
+    }
+  } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)) {
+    // Create specific DIE.
+    Slot = Ty = new DIE(CompTy->getTag());
+    std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
+    
+    switch (CompTy->getTag()) {
+    case DW_TAG_array_type: {
+      // Add element type.
+      if (TypeDesc *FromTy = CompTy->getFromType()) {
+        Ty->AddDIEntry(DW_AT_type, DW_FORM_ref4,
+                       NewType(Context, FromTy, Unit));
+      }
+      // Don't emit size attribute.
+      Size = 0;
+      
+      // Construct an anonymous type for index type.
+      DIE *IndexTy = new DIE(DW_TAG_base_type);
+      IndexTy->AddUInt(DW_AT_byte_size, 0, 4);
+      IndexTy->AddUInt(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
+      // Add to context.
+      Context->AddChild(IndexTy);
+    
+      // Add subranges to array type.
+      for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
+        SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
+        int64_t Lo = SRD->getLo();
+        int64_t Hi = SRD->getHi();
+        DIE *Subrange = new DIE(DW_TAG_subrange_type);
+        
+        // If a range is available.
+        if (Lo != Hi) {
+          Subrange->AddDIEntry(DW_AT_type, DW_FORM_ref4, IndexTy);
+          // Only add low if non-zero.
+          if (Lo) Subrange->AddSInt(DW_AT_lower_bound, 0, Lo);
+          Subrange->AddSInt(DW_AT_upper_bound, 0, Hi);
+        }
+        Ty->AddChild(Subrange);
+      }
+      
+      break;
+    }
+    case DW_TAG_structure_type:
+    case DW_TAG_union_type: {
+      // FIXME - this is just the basics.
+      // Add elements to structure type.
+      for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
+        DerivedTypeDesc *MemberDesc = cast<DerivedTypeDesc>(Elements[i]);
+        
+        // Extract the basic information.
+        const std::string &Name = MemberDesc->getName();
+        TypeDesc *MemTy = MemberDesc->getFromType();
+        uint64_t Size = MemberDesc->getSize();
+        uint64_t Align = MemberDesc->getAlign();
+        uint64_t Offset = MemberDesc->getOffset();
+   
+        // Construct member debug information entry.
+        DIE *Member = new DIE(DW_TAG_member);
+        
+        // Add name if not "".
+        if (!Name.empty()) Member->AddString(DW_AT_name, DW_FORM_string, Name);
+        // Add location if available.
+        AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
+        
+        // Most of the time the field info is the same as the members.
+        uint64_t FieldSize = Size;
+        uint64_t FieldAlign = Align;
+        uint64_t FieldOffset = Offset;
+        
+        if (TypeDesc *FromTy = MemberDesc->getFromType()) {
+          Member->AddDIEntry(DW_AT_type, DW_FORM_ref4,
+                             NewType(Context, FromTy, Unit));
+          FieldSize = FromTy->getSize();
+          FieldAlign = FromTy->getSize();
+        }
+        
+        // Unless we have a bit field.
+        if (FieldSize != Size) {
+          // Construct the alignment mask.
+          uint64_t AlignMask = ~(FieldAlign - 1);
+          // Determine the high bit + 1 of the declared size.
+          uint64_t HiMark = (Offset + FieldSize) & AlignMask;
+          // Work backwards to determine the base offset of the field.
+          FieldOffset = HiMark - FieldSize;
+          // Now normalize offset to the field.
+          Offset -= FieldOffset;
+          
+          // Maybe we need to work from the other.
+          const TargetData &TD = Asm->TM.getTargetData();
+          if (TD.isLittleEndian()) Offset = FieldSize - (Offset + Size);
+          
+          Member->AddUInt(DW_AT_byte_size, 0, FieldSize >> 3);
+          Member->AddUInt(DW_AT_bit_size, 0, Size);
+          Member->AddUInt(DW_AT_bit_offset, 0, Offset);
+        }
+        
+        // Add computation for offset.
+        DIEBlock *Block = new DIEBlock();
+        Block->AddUInt(DW_FORM_data1, DW_OP_plus_uconst);
+        Block->AddUInt(DW_FORM_udata, FieldOffset >> 3);
+        Block->ComputeSize(*this);
+        Member->AddBlock(DW_AT_data_member_location, 0, Block);
+        
+        Ty->AddChild(Member);
+      }
+      break;
+    }
+    case DW_TAG_enumeration_type: {
+      // Add enumerators to enumeration type.
+      for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
+        EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
+        const std::string &Name = ED->getName();
+        int64_t Value = ED->getValue();
+        DIE *Enumerator = new DIE(DW_TAG_enumerator);
+        Enumerator->AddString(DW_AT_name, DW_FORM_string, Name);
+        Enumerator->AddSInt(DW_AT_const_value, DW_FORM_sdata, Value);
+        Ty->AddChild(Enumerator);
+      }
+
+      break;
+    }
+    default: break;
     }
   }
   
@@ -1054,53 +1402,61 @@ DIE *DwarfWriter::NewType(DIE *Unit, TypeDesc *TyDesc) {
   if (Size) Ty->AddUInt(DW_AT_byte_size, 0, Size);
   // Add name if not anonymous or intermediate type.
   if (!Name.empty()) Ty->AddString(DW_AT_name, DW_FORM_string, Name);
-  // Add source line info if present.
-  if (CompileUnitDesc *File = TyDesc->getFile()) {
-    unsigned FileID = DebugInfo->RecordSource(File);
-    int Line = TyDesc->getLine();
-    Ty->AddUInt(DW_AT_decl_file, 0, FileID);
-    Ty->AddUInt(DW_AT_decl_line, 0, Line);
-  }
+  // Add source line info if available.
+  AddSourceLine(Ty, TyDesc->getFile(), TyDesc->getLine());
 
   // Add to context owner.
-  Unit->AddChild(Ty);
+  Context->AddChild(Ty);
   
   return Slot;
 }
 
-/// NewCompileUnit - Create new compile unit DIE.
+/// NewCompileUnit - Create new compile unit and it's debug information entry.
 ///
-DIE *DwarfWriter::NewCompileUnit(CompileUnitDesc *CompileUnit) {
-  // Check for pre-existence.
-  DIE *&Slot = DescToDieMap[CompileUnit];
-  if (Slot) return Slot;
-
-  DIE *Unit = new DIE(DW_TAG_compile_unit);
-  // FIXME - use the correct line set.
-  Unit->AddLabel (DW_AT_stmt_list, DW_FORM_data4,  DWLabel("section_line", 0));
-  Unit->AddLabel (DW_AT_high_pc,   DW_FORM_addr,   DWLabel("text_end", 0));
-  Unit->AddLabel (DW_AT_low_pc,    DW_FORM_addr,   DWLabel("text_begin", 0));
-  Unit->AddString(DW_AT_producer,  DW_FORM_string, CompileUnit->getProducer());
-  Unit->AddUInt  (DW_AT_language,  DW_FORM_data1,  CompileUnit->getLanguage());
-  Unit->AddString(DW_AT_name,      DW_FORM_string, CompileUnit->getFileName());
-  Unit->AddString(DW_AT_comp_dir,  DW_FORM_string, CompileUnit->getDirectory());
-  
-  Slot = Unit;
+CompileUnit *DwarfWriter::NewCompileUnit(CompileUnitDesc *UnitDesc,
+                                         unsigned ID) {
+  // Construct debug information entry.
+  DIE *Die = new DIE(DW_TAG_compile_unit);
+  Die->AddLabel (DW_AT_stmt_list, DW_FORM_data4,  DWLabel("line", 0));
+  Die->AddLabel (DW_AT_high_pc,   DW_FORM_addr,   DWLabel("text_end", 0));
+  Die->AddLabel (DW_AT_low_pc,    DW_FORM_addr,   DWLabel("text_begin", 0));
+  Die->AddString(DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
+  Die->AddUInt  (DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
+  Die->AddString(DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
+  Die->AddString(DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
+  
+  // Add debug information entry to descriptor map.
+  DIE *&Slot = getDieMapSlotFor(UnitDesc);
+  Slot = Die;
+  
+  // Construct compile unit.
+  CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
+  
+  // Add Unit to compile unit map.
+  DescToUnitMap[UnitDesc] = Unit;
   
   return Unit;
 }
 
+/// FindCompileUnit - Get the compile unit for the given descriptor.
+///
+CompileUnit *DwarfWriter::FindCompileUnit(CompileUnitDesc *UnitDesc) {
+  CompileUnit *Unit = DescToUnitMap[UnitDesc];
+  assert(Unit && "Missing compile unit.");
+  return Unit;
+}
+
 /// NewGlobalVariable - Add a new global variable DIE.
 ///
 DIE *DwarfWriter::NewGlobalVariable(GlobalVariableDesc *GVD) {
+  // Get the compile unit context.
+  CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(GVD->getContext());
+  CompileUnit *Unit = FindCompileUnit(UnitDesc);
+
   // Check for pre-existence.
-  DIE *&Slot = DescToDieMap[GVD];
+  DIE *&Slot = Unit->getDieMapSlotFor(GVD);
   if (Slot) return Slot;
   
-  // Get the compile unit context.
-  CompileUnitDesc *CompileUnit =
-                              static_cast<CompileUnitDesc *>(GVD->getContext());
-  DIE *Unit = NewCompileUnit(CompileUnit);
   // Get the global variable itself.
   GlobalVariable *GV = GVD->getGlobalVariable();
   // Generate the mangled name.
@@ -1108,30 +1464,35 @@ DIE *DwarfWriter::NewGlobalVariable(GlobalVariableDesc *GVD) {
 
   // Gather the details (simplify add attribute code.)
   const std::string &Name = GVD->getName();
-  unsigned FileID = DebugInfo->RecordSource(CompileUnit);
-  unsigned Line = GVD->getLine();
   
   // Get the global's type.
-  DIE *Type = NewType(Unit, GVD->getTypeDesc()); 
+  DIE *Type = NewType(Unit->getDie(), GVD->getType(), Unit); 
 
   // Create the globale variable DIE.
   DIE *VariableDie = new DIE(DW_TAG_variable);
   VariableDie->AddString     (DW_AT_name,      DW_FORM_string, Name);
-  VariableDie->AddUInt       (DW_AT_decl_file, 0,              FileID);
-  VariableDie->AddUInt       (DW_AT_decl_line, 0,              Line);
   VariableDie->AddDIEntry    (DW_AT_type,      DW_FORM_ref4,   Type);
   VariableDie->AddUInt       (DW_AT_external,  DW_FORM_flag,   1);
-  // FIXME - needs to be a proper expression.
-  VariableDie->AddObjectLabel(DW_AT_location,  DW_FORM_block1, MangledName);
+  
+  // Add source line info if available.
+  AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
+
+  // Add address.
+  DIEBlock *Block = new DIEBlock();
+  Block->AddUInt(DW_FORM_data1, DW_OP_addr);
+  Block->AddObjectLabel(DW_FORM_udata, MangledName);
+  Block->ComputeSize(*this);
+  VariableDie->AddBlock(DW_AT_location,  0, Block);
   
   // Add to map.
   Slot = VariableDie;
  
   // Add to context owner.
-  Unit->AddChild(VariableDie);
+  Unit->getDie()->AddChild(VariableDie);
   
   // Expose as global.
-  NewGlobalEntity(Name, VariableDie);
+  // FIXME - need to check external flag.
+  Unit->AddGlobal(Name, VariableDie);
   
   return VariableDie;
 }
@@ -1139,43 +1500,144 @@ DIE *DwarfWriter::NewGlobalVariable(GlobalVariableDesc *GVD) {
 /// NewSubprogram - Add a new subprogram DIE.
 ///
 DIE *DwarfWriter::NewSubprogram(SubprogramDesc *SPD) {
+  // Get the compile unit context.
+  CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
+  CompileUnit *Unit = FindCompileUnit(UnitDesc);
+
   // Check for pre-existence.
-  DIE *&Slot = DescToDieMap[SPD];
+  DIE *&Slot = Unit->getDieMapSlotFor(SPD);
   if (Slot) return Slot;
   
-  // Get the compile unit context.
-  CompileUnitDesc *CompileUnit =
-                              static_cast<CompileUnitDesc *>(SPD->getContext());
-  DIE *Unit = NewCompileUnit(CompileUnit);
-
   // Gather the details (simplify add attribute code.)
   const std::string &Name = SPD->getName();
-  unsigned FileID = DebugInfo->RecordSource(CompileUnit);
-  // FIXME - faking the line for the time being.
-  unsigned Line = 1;
-  
-  // FIXME - faking the type for the time being.
-  DIE *Type = NewBasicType(Unit, Type::IntTy); 
+  DIE *Type = NewType(Unit->getDie(), SPD->getType(), Unit); 
+  unsigned IsExternal = SPD->isStatic() ? 0 : 1;
                                     
-  DIE *SubprogramDie = new DIE(DW_TAG_variable);
+  DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
   SubprogramDie->AddString     (DW_AT_name,      DW_FORM_string, Name);
-  SubprogramDie->AddUInt       (DW_AT_decl_file, 0,              FileID);
-  SubprogramDie->AddUInt       (DW_AT_decl_line, 0,              Line);
   SubprogramDie->AddDIEntry    (DW_AT_type,      DW_FORM_ref4,   Type);
-  SubprogramDie->AddUInt       (DW_AT_external,  DW_FORM_flag,   1);
+  SubprogramDie->AddUInt       (DW_AT_external,  DW_FORM_flag,   IsExternal);
   
+  // Add source line info if available.
+  AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
+
   // Add to map.
   Slot = SubprogramDie;
  
   // Add to context owner.
-  Unit->AddChild(SubprogramDie);
+  Unit->getDie()->AddChild(SubprogramDie);
   
   // Expose as global.
-  NewGlobalEntity(Name, SubprogramDie);
+  Unit->AddGlobal(Name, SubprogramDie);
   
   return SubprogramDie;
 }
 
+/// NewScopeVariable - Create a new scope variable.
+///
+DIE *DwarfWriter::NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
+  // Get the descriptor.
+  VariableDesc *VD = DV->getDesc();
+
+  // Translate tag to proper Dwarf tag.  The result variable is dropped for now.
+  unsigned Tag;
+  switch (VD->getTag()) {
+  case DW_TAG_return_variable:  return NULL;
+  case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
+  case DW_TAG_auto_variable:    // fall thru
+  default:                      Tag = DW_TAG_variable; break;
+  }
+
+  // Define variable debug information entry.
+  DIE *VariableDie = new DIE(Tag);
+  VariableDie->AddString(DW_AT_name, DW_FORM_string, VD->getName());
+
+  // Add source line info if available.
+  AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
+  
+  // Add variable type.
+  DIE *Type = NewType(Unit->getDie(), VD->getType(), Unit); 
+  VariableDie->AddDIEntry(DW_AT_type, DW_FORM_ref4, Type);
+  
+  // Add variable address.
+  MachineLocation Location;
+  Asm->TM.getRegisterInfo()->getLocation(*MF, DV->getFrameIndex(), Location);
+  AddAddress(VariableDie, DW_AT_location, Location);
+  
+  return VariableDie;
+}
+
+/// ConstructScope - Construct the components of a scope.
+///
+void DwarfWriter::ConstructScope(DebugScope *ParentScope,
+                                 DIE *ParentDie, CompileUnit *Unit) {
+  // Add variables to scope.
+  std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
+  for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
+    DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
+    if (VariableDie) ParentDie->AddChild(VariableDie);
+  }
+  
+  // Add nested scopes.
+  std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
+  for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
+    // Define the Scope debug information entry.
+    DebugScope *Scope = Scopes[j];
+    // FIXME - Ignore inlined functions for the time being.
+    if (Scope->getParent()) continue;
+    
+    DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
+    
+    // Add the scope bounds.
+    if (unsigned StartID = Scope->getStartLabelID()) {
+      ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
+                         DWLabel("loc", StartID));
+    } else {
+      ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
+                         DWLabel("func_begin", SubprogramCount));
+    }
+    if (unsigned EndID = Scope->getEndLabelID()) {
+      ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
+                         DWLabel("loc", EndID));
+    } else {
+      ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
+                         DWLabel("func_end", SubprogramCount));
+    }
+                       
+    // Add the scope contents.
+    ConstructScope(Scope, ScopeDie, Unit);
+    ParentDie->AddChild(ScopeDie);
+  }
+}
+
+/// ConstructRootScope - Construct the scope for the subprogram.
+///
+void DwarfWriter::ConstructRootScope(DebugScope *RootScope) {
+  // Exit if there is no root scope.
+  if (!RootScope) return;
+  
+  // Get the subprogram debug information entry. 
+  SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
+  
+  // Get the compile unit context.
+  CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
+  CompileUnit *Unit = FindCompileUnit(UnitDesc);  
+  
+  // Get the subprogram die.
+  DIE *SPDie = Unit->getDieMapSlotFor(SPD);
+  assert(SPDie && "Missing subprogram descriptor");
+  
+  // Add the function bounds.
+  SPDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
+                  DWLabel("func_begin", SubprogramCount));
+  SPDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
+                  DWLabel("func_end", SubprogramCount));
+  MachineLocation Location(Asm->TM.getRegisterInfo()->getFrameRegister(*MF));
+  AddAddress(SPDie, DW_AT_frame_base, Location);
+                  
+  ConstructScope(RootScope, SPDie, Unit);
+}
+
 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
 /// tools to recognize the object file contains Dwarf information.
 ///
@@ -1257,8 +1719,6 @@ void DwarfWriter::EmitDIE(DIE *Die) const {
     const std::vector<DIE *> &Children = Die->getChildren();
     
     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
-      // FIXME - handle sibling offsets.
-      // FIXME - handle all DIE types.
       EmitDIE(Children[j]);
     }
     
@@ -1268,7 +1728,13 @@ void DwarfWriter::EmitDIE(DIE *Die) const {
 
 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
 ///
-unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset) {
+unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
+  // Get the children.
+  const std::vector<DIE *> &Children = Die->getChildren();
+  
+  // If not last sibling and has children then add sibling offset attribute.
+  if (!Last && !Children.empty()) Die->AddSiblingOffset();
+
   // Record the abbreviation.
   Die->Complete(*this);
   
@@ -1292,13 +1758,12 @@ unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset) {
   }
   
   // Emit the DIE children if any.
-  if (Abbrev.getChildrenFlag() == DW_CHILDREN_yes) {
-    const std::vector<DIE *> &Children = Die->getChildren();
+  if (!Children.empty()) {
+    assert(Abbrev.getChildrenFlag() == DW_CHILDREN_yes &&
+           "Children flag not set");
     
     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
-      // FIXME - handle sibling offsets.
-      // FIXME - handle all DIE types.
-      Offset = SizeAndOffsetDie(Children[j], Offset);
+      Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
     }
     
     // End of children marker.
@@ -1312,17 +1777,18 @@ unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset) {
 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
 ///
 void DwarfWriter::SizeAndOffsets() {
-  unsigned Offset = 0;
   
   // Process each compile unit.
   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
-    // Compute size of compile unit header
-    Offset += sizeof(int32_t) + // Length of Compilation Unit Info
-              sizeof(int16_t) + // DWARF version number
-              sizeof(int32_t) + // Offset Into Abbrev. Section
-              sizeof(int8_t);   // Pointer Size (in bytes)
-  
-    Offset = SizeAndOffsetDie(CompileUnits[i], Offset);
+    CompileUnit *Unit = CompileUnits[i];
+    if (Unit->hasContent()) {
+      // Compute size of compile unit header
+      unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
+                        sizeof(int16_t) + // DWARF version number
+                        sizeof(int32_t) + // Offset Into Abbrev. Section
+                        sizeof(int8_t);   // Pointer Size (in bytes)
+      SizeAndOffsetDie(Unit->getDie(), Offset, (i + 1) == N);
+    }
   }
 }
 
@@ -1332,19 +1798,16 @@ void DwarfWriter::EmitDebugInfo() const {
   // Start debug info section.
   Asm->SwitchSection(DwarfInfoSection, 0);
   
-  // Get the number of compile units.
-  unsigned N = CompileUnits.size();
-  
-  // If there are any compile units.
-  if (N) {
-    EmitLabel("info_begin", 0);
-
-    // Process each compile unit.
-    for (unsigned i = 0; i < N; ++i) {
+  // Process each compile unit.
+  for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
+    CompileUnit *Unit = CompileUnits[i];
+    
+    if (Unit->hasContent()) {
+      DIE *Die = Unit->getDie();
       // Emit the compile units header.
-
+      EmitLabel("info_begin", Unit->getID());
       // Emit size of content not including length itself
-      unsigned ContentSize = CompileUnits[i]->getSize() +
+      unsigned ContentSize = Die->getSize() +
                              sizeof(int16_t) + // DWARF version number
                              sizeof(int32_t) + // Offset Into Abbrev. Section
                              sizeof(int8_t);   // Pointer Size (in bytes)
@@ -1354,10 +1817,9 @@ void DwarfWriter::EmitDebugInfo() const {
       EmitReference("abbrev_begin", 0); EOL("Offset Into Abbrev. Section");
       EmitInt8(AddressSize); EOL("Address Size (in bytes)");
     
-      EmitDIE(CompileUnits[i]);
+      EmitDIE(Die);
+      EmitLabel("info_end", Unit->getID());
     }
-  
-    EmitLabel("info_end", 0);
     
     O << "\n";
   }
@@ -1487,13 +1949,13 @@ void DwarfWriter::EmitDebugLines() const {
     EmitInt8(0); EOL("Extended Op");
     EmitInt8(4 + 1); EOL("Op size");
     EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
-    EmitReference("loc", i + 1); EOL("Location label");
+    EmitReference("loc",  LineInfo->getLabelID()); EOL("Location label");
     
     // If change of source, then switch to the new source.
     if (Source != LineInfo->getSourceID()) {
       Source = LineInfo->getSourceID();
       EmitInt8(DW_LNS_set_file); EOL("DW_LNS_set_file");
-      EmitULEB128Bytes(0); EOL("New Source");
+      EmitULEB128Bytes(Source); EOL("New Source");
     }
     
     // If change of line.
@@ -1540,56 +2002,74 @@ void DwarfWriter::EmitDebugLines() const {
 /// EmitDebugFrame - Emit visible names into a debug frame section.
 ///
 void DwarfWriter::EmitDebugFrame() {
-  // FIXME - Should be per frame
+  // Start the dwarf pubnames section.
+  Asm->SwitchSection(DwarfFrameSection, 0);
+
+  EmitDifference("frame_common_end", 0,
+                 "frame_common_begin", 0);
+  EOL("Length of Common Information Entry");
+
+  EmitLabel("frame_common_begin", 0);
+  EmitInt32(DW_CIE_ID); EOL("CIE Identifier Tag");
+  EmitInt8(DW_CIE_VERSION); EOL("CIE Version");
+  EmitString("");  EOL("CIE Augmentation");
+  EmitULEB128Bytes(1); EOL("CIE Code Alignment Factor");
+  // FIXME - needs to change based on stack direction.
+  EmitSLEB128Bytes(-sizeof(int32_t)); EOL("CIE Data Alignment Factor");
+  // FIXME - hard coded for PPC (LR).
+  EmitInt8(0x41); EOL("CIE RA Column Hardcoded (PPC LR)");
+  // FIXME - hard coded for PPC 0(SP).
+  EmitULEB128Bytes(DW_CFA_def_cfa); EOL("DW_CFA_def_cfa");
+  EmitULEB128Bytes(1); EOL("PPC Register SP");
+  EmitULEB128Bytes(0); EOL("PPC offset 0 as in 0(SP)");
+  EmitAlign(2);
+  EmitLabel("frame_common_end", 0);
+  
+  O << "\n";
 }
 
 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
 ///
 void DwarfWriter::EmitDebugPubNames() {
-  // Check to see if it is worth the effort.
-  if (!GlobalEntities.empty()) {
-    // Start the dwarf pubnames section.
-    Asm->SwitchSection(DwarfPubNamesSection, 0);
-    
-    EmitDifference("pubnames_end", 0, "pubnames_begin", 0);
-    EOL("Length of Public Names Info");
-    
-    EmitLabel("pubnames_begin", 0);
+  // Start the dwarf pubnames section.
+  Asm->SwitchSection(DwarfPubNamesSection, 0);
     
-    EmitInt16(DWARF_VERSION); EOL("DWARF Version");
+  // Process each compile unit.
+  for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
+    CompileUnit *Unit = CompileUnits[i];
     
-    EmitReference("info_begin", 0); EOL("Offset of Compilation Unit Info");
+    if (Unit->hasContent()) {
+      EmitDifference("pubnames_end", Unit->getID(),
+                     "pubnames_begin", Unit->getID());
+      EOL("Length of Public Names Info");
+      
+      EmitLabel("pubnames_begin", Unit->getID());
+      
+      EmitInt16(DWARF_VERSION); EOL("DWARF Version");
+      
+      EmitReference("info_begin", Unit->getID());
+      EOL("Offset of Compilation Unit Info");
 
-    EmitDifference("info_end", 0, "info_begin", 0);
-    EOL("Compilation Unit Length");
-    
-    for (std::map<std::string, DIE *>::iterator GI = GlobalEntities.begin(),
-                                                GE = GlobalEntities.end();
-         GI != GE; ++GI) {
-      const std::string &Name = GI->first;
-      DIE * Entity = GI->second;
+      EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID());
+      EOL("Compilation Unit Length");
       
-      EmitInt32(Entity->getOffset()); EOL("DIE offset");
-      EmitString(Name); EOL("External Name");
+      std::map<std::string, DIE *> &Globals = Unit->getGlobals();
       
+      for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
+                                                  GE = Globals.end();
+           GI != GE; ++GI) {
+        const std::string &Name = GI->first;
+        DIE * Entity = GI->second;
+        
+        EmitInt32(Entity->getOffset()); EOL("DIE offset");
+        EmitString(Name); EOL("External Name");
+      }
+    
+      EmitInt32(0); EOL("End Mark");
+      EmitLabel("pubnames_end", Unit->getID());
+    
+      O << "\n";
     }
-  
-    EmitInt32(0); EOL("End Mark");
-    EmitLabel("pubnames_end", 0);
-  
-    O << "\n";
-  }
-}
-
-/// EmitDebugPubTypes - Emit visible names into a debug pubtypes section.
-///
-void DwarfWriter::EmitDebugPubTypes() {
-  // Check to see if it is worth the effort.
-  if (!GlobalTypes.empty()) {
-    // Start the dwarf pubtypes section.
-    Asm->SwitchSection(DwarfPubTypesSection, 0);
-  
-    O << "\n";
   }
 }
 
@@ -1601,7 +2081,7 @@ void DwarfWriter::EmitDebugStr() {
     // Start the dwarf str section.
     Asm->SwitchSection(DwarfStrSection, 0);
     
-    // For each of strings in teh string pool.
+    // For each of strings in the string pool.
     for (unsigned StringID = 1, N = StringPool.size();
          StringID <= N; ++StringID) {
       // Emit a label for reference from debug information entries.
@@ -1631,29 +2111,38 @@ void DwarfWriter::EmitDebugARanges() {
   Asm->SwitchSection(DwarfARangesSection, 0);
   
   // FIXME - Mock up
+#if 0
+  // Process each compile unit.
+  for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
+    CompileUnit *Unit = CompileUnits[i];
+    
+    if (Unit->hasContent()) {
+      // Don't include size of length
+      EmitInt32(0x1c); EOL("Length of Address Ranges Info");
+      
+      EmitInt16(DWARF_VERSION); EOL("Dwarf Version");
+      
+      EmitReference("info_begin", Unit->getID());
+      EOL("Offset of Compilation Unit Info");
 
-  // Don't include size of length
-  EmitInt32(0x1c); EOL("Length of Address Ranges Info");
-  
-  EmitInt16(DWARF_VERSION); EOL("Dwarf Version");
-  
-  EmitReference("info_begin", 0); EOL("Offset of Compilation Unit Info");
-
-  EmitInt8(AddressSize); EOL("Size of Address");
+      EmitInt8(AddressSize); EOL("Size of Address");
 
-  EmitInt8(0); EOL("Size of Segment Descriptor");
+      EmitInt8(0); EOL("Size of Segment Descriptor");
 
-  EmitInt16(0);  EOL("Pad (1)");
-  EmitInt16(0);  EOL("Pad (2)");
+      EmitInt16(0);  EOL("Pad (1)");
+      EmitInt16(0);  EOL("Pad (2)");
 
-  // Range 1
-  EmitReference("text_begin", 0); EOL("Address");
-  EmitDifference("text_end", 0, "text_begin", 0); EOL("Length");
+      // Range 1
+      EmitReference("text_begin", 0); EOL("Address");
+      EmitDifference("text_end", 0, "text_begin", 0); EOL("Length");
 
-  EmitInt32(0); EOL("EOM (1)");
-  EmitInt32(0); EOL("EOM (2)");
-  
-  O << "\n";
+      EmitInt32(0); EOL("EOM (1)");
+      EmitInt32(0); EOL("EOM (2)");
+      
+      O << "\n";
+    }
+  }
+#endif
 }
 
 /// EmitDebugRanges - Emit visible names into a debug ranges section.
@@ -1680,16 +2169,16 @@ void DwarfWriter::ConstructCompileUnitDIEs() {
   const UniqueVector<CompileUnitDesc *> CUW = DebugInfo->getCompileUnits();
   
   for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
-    DIE *Unit = NewCompileUnit(CUW[i]);
+    CompileUnit *Unit = NewCompileUnit(CUW[i], i);
     CompileUnits.push_back(Unit);
   }
 }
 
 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible global
 /// variables.
-void DwarfWriter::ConstructGlobalDIEs(Module &M) {
+void DwarfWriter::ConstructGlobalDIEs() {
   std::vector<GlobalVariableDesc *> GlobalVariables =
-                       DebugInfo->getAnchoredDescriptors<GlobalVariableDesc>(M);
+      DebugInfo->getAnchoredDescriptors<GlobalVariableDesc>(*M);
   
   for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
     GlobalVariableDesc *GVD = GlobalVariables[i];
@@ -1699,9 +2188,9 @@ void DwarfWriter::ConstructGlobalDIEs(Module &M) {
 
 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
 /// subprograms.
-void DwarfWriter::ConstructSubprogramDIEs(Module &M) {
+void DwarfWriter::ConstructSubprogramDIEs() {
   std::vector<SubprogramDesc *> Subprograms =
-                           DebugInfo->getAnchoredDescriptors<SubprogramDesc>(M);
+      DebugInfo->getAnchoredDescriptors<SubprogramDesc>(*M);
   
   for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
     SubprogramDesc *SPD = Subprograms[i];
@@ -1718,6 +2207,16 @@ bool DwarfWriter::ShouldEmitDwarf() {
   // Make sure initial declarations are made.
   if (!didInitial) {
     EmitInitial();
+  
+    // Create all the compile unit DIEs.
+    ConstructCompileUnitDIEs();
+    
+    // Create DIEs for each of the externally visible global variables.
+    ConstructGlobalDIEs();
+
+    // Create DIEs for each of the externally visible subprograms.
+    ConstructSubprogramDIEs();
+
     didInitial = true;
   }
   
@@ -1732,13 +2231,15 @@ bool DwarfWriter::ShouldEmitDwarf() {
 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A)
 : O(OS)
 , Asm(A)
+, M(NULL)
+, MF(NULL)
 , DebugInfo(NULL)
 , didInitial(false)
+, SubprogramCount(0)
 , CompileUnits()
 , Abbreviations()
-, GlobalTypes()
-, GlobalEntities()
 , StringPool()
+, DescToUnitMap()
 , DescToDieMap()
 , TypeToDieMap()
 , AddressSize(sizeof(int32_t))
@@ -1768,14 +2269,16 @@ DwarfWriter::~DwarfWriter() {
 
 /// BeginModule - Emit all Dwarf sections that should come prior to the content.
 ///
-void DwarfWriter::BeginModule(Module &M) {
+void DwarfWriter::BeginModule(Module *M) {
+  this->M = M;
+  
   if (!ShouldEmitDwarf()) return;
   EOL("Dwarf Begin Module");
 }
 
 /// EndModule - Emit all Dwarf sections that should come after the content.
 ///
-void DwarfWriter::EndModule(Module &M) {
+void DwarfWriter::EndModule() {
   if (!ShouldEmitDwarf()) return;
   EOL("Dwarf End Module");
   
@@ -1785,15 +2288,6 @@ void DwarfWriter::EndModule(Module &M) {
   Asm->SwitchSection(DataSection, 0);
   EmitLabel("data_end", 0);
   
-  // Create all the compile unit DIEs.
-  ConstructCompileUnitDIEs();
-  
-  // Create DIEs for each of the externally visible global variables.
-  ConstructGlobalDIEs(M);
-
-  // Create DIEs for each of the externally visible subprograms.
-  ConstructSubprogramDIEs(M);
-  
   // Compute DIE offsets and sizes.
   SizeAndOffsets();
   
@@ -1807,14 +2301,11 @@ void DwarfWriter::EndModule(Module &M) {
   EmitDebugLines();
   
   // Emit info into a debug frame section.
-  // EmitDebugFrame();
+  EmitDebugFrame();
   
   // Emit info into a debug pubnames section.
   EmitDebugPubNames();
   
-  // Emit info into a debug pubtypes section.
-  // EmitDebugPubTypes();
-  
   // Emit info into a debug str section.
   EmitDebugStr();
   
@@ -1833,14 +2324,29 @@ void DwarfWriter::EndModule(Module &M) {
 
 /// BeginFunction - Gather pre-function debug information.
 ///
-void DwarfWriter::BeginFunction(MachineFunction &MF) {
+void DwarfWriter::BeginFunction(MachineFunction *MF) {
+  this->MF = MF;
+  
   if (!ShouldEmitDwarf()) return;
   EOL("Dwarf Begin Function");
+  
+  // Define begin label for subprogram.
+  Asm->SwitchSection(TextSection, 0);
+  EmitLabel("func_begin", ++SubprogramCount);
 }
 
+
 /// EndFunction - Gather and emit post-function debug information.
 ///
-void DwarfWriter::EndFunction(MachineFunction &MF) {
+void DwarfWriter::EndFunction() {
   if (!ShouldEmitDwarf()) return;
   EOL("Dwarf End Function");
+  
+  // Define end label for subprogram.
+  Asm->SwitchSection(TextSection, 0);
+  EmitLabel("func_end", SubprogramCount);
+  
+  // Construct scopes for subprogram.
+  ConstructRootScope(DebugInfo->getRootScope());
+  DebugInfo->ClearScopes();
 }