Convert DwarfWriter into a pass.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfWriter.cpp
index 92a068b2c4551d7b7dd3df8dacc4accd342358f2..6293590fd67690c1e258c5920b05152374098355 100644 (file)
@@ -18,7 +18,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/UniqueVector.h"
 #include "llvm/Module.h"
-#include "llvm/Type.h"
+#include "llvm/DerivedTypes.h"
 #include "llvm/CodeGen/AsmPrinter.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 using namespace llvm;
 using namespace llvm::dwarf;
 
+static RegisterPass<DwarfWriter>
+X("dwarfwriter", "DWARF Information Writer");
+char DwarfWriter::ID = 0;
+
 namespace llvm {
 
 //===----------------------------------------------------------------------===//
@@ -59,6 +63,43 @@ static const unsigned InitValuesSetSize        = 9; // 512
 class DIE;
 class DIEValue;
 
+//===----------------------------------------------------------------------===//
+/// Utility routines.
+///
+/// getGlobalVariablesUsing - Return all of the GlobalVariables which have the            
+/// specified value in their initializer somewhere.                                       
+static void
+getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
+  // Scan though value users.                                                             
+  for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
+    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
+      // If the user is a GlobalVariable then add to result.                              
+      Result.push_back(GV);
+    } else if (Constant *C = dyn_cast<Constant>(*I)) {
+      // If the user is a constant variable then scan its users                           
+      getGlobalVariablesUsing(C, Result);
+    }
+  }
+}
+
+/// getGlobalVariablesUsing - Return all of the GlobalVariables that use the              
+/// named GlobalVariable.                                                                 
+static void
+getGlobalVariablesUsing(Module &M, const std::string &RootName,
+                        std::vector<GlobalVariable*> &Result) {
+  std::vector<const Type*> FieldTypes;
+  FieldTypes.push_back(Type::Int32Ty);
+  FieldTypes.push_back(Type::Int32Ty);
+
+  // Get the GlobalVariable root.                                                         
+  GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
+                                                StructType::get(FieldTypes));
+
+  // If present and linkonce then scan for users.                                         
+  if (UseRoot && UseRoot->hasLinkOnceLinkage())
+    getGlobalVariablesUsing(UseRoot, Result);
+}
+
 //===----------------------------------------------------------------------===//
 /// DWLabel - Labels are used to track locations in the assembler file.
 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
@@ -743,6 +784,11 @@ private:
   std::vector<DIE *> Dies;
 
 public:
+  CompileUnit(unsigned I, DIE *D)
+    : ID(I), Die(D), DescToDieMap(), GVToDieMap(), DescToDIEntryMap(),
+      GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize), Dies()
+  {}
+
   CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
   : Desc(CUD)
   , ID(I)
@@ -1123,6 +1169,26 @@ public:
 
 };
 
+//===----------------------------------------------------------------------===//
+/// SourceLineInfo - This class is used to record source line correspondence.
+///
+class SrcLineInfo {
+  unsigned Line;                        // Source line number.
+  unsigned Column;                      // Source column.
+  unsigned SourceID;                    // Source ID number.
+  unsigned LabelID;                     // Label in code ID number.
+public:
+  SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
+  : Line(L), Column(C), SourceID(S), LabelID(I) {}
+  
+  // Accessors
+  unsigned getLine()     const { return Line; }
+  unsigned getColumn()   const { return Column; }
+  unsigned getSourceID() const { return SourceID; }
+  unsigned getLabelID()  const { return LabelID; }
+};
+
+
 //===----------------------------------------------------------------------===//
 /// SrcFileInfo - This class is used to track source information.
 ///
@@ -1150,6 +1216,60 @@ public:
   }
 };
 
+//===----------------------------------------------------------------------===//
+/// DbgVariable - This class is used to track local variable information.
+///
+class DbgVariable {
+private:
+  DIVariable *Var;                   // Variable Descriptor.
+  unsigned FrameIndex;               // Variable frame index.
+
+public:
+  DbgVariable(DIVariable *V, unsigned I) : Var(V), FrameIndex(I)  {}
+  
+  // Accessors.
+  DIVariable *getVariable()  const { return Var; }
+  unsigned getFrameIndex() const { return FrameIndex; }
+};
+
+//===----------------------------------------------------------------------===//
+/// DbgScope - This class is used to track scope information.
+///
+class DbgScope {
+private:
+  DbgScope *Parent;                   // Parent to this scope.
+  DIDescriptor *Desc;                 // Debug info descriptor for scope.
+                                      // Either subprogram or block.
+  unsigned StartLabelID;              // Label ID of the beginning of scope.
+  unsigned EndLabelID;                // Label ID of the end of scope.
+  SmallVector<DbgScope *, 8> Scopes;     // Scopes defined in scope.
+  SmallVector<DbgVariable *, 32> Variables;// Variables declared in scope.
+  
+public:
+  DbgScope(DbgScope *P, DIDescriptor *D)
+  : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
+  {}
+  ~DbgScope();
+  
+  // Accessors.
+  DbgScope *getParent()        const { return Parent; }
+  DIDescriptor *getDesc()       const { return Desc; }
+  unsigned getStartLabelID()     const { return StartLabelID; }
+  unsigned getEndLabelID()       const { return EndLabelID; }
+  SmallVector<DbgScope *, 8> &getScopes() { return Scopes; }
+  SmallVector<DbgVariable *, 32> &getVariables() { return Variables; }
+  void setStartLabelID(unsigned S) { StartLabelID = S; }
+  void setEndLabelID(unsigned E)   { EndLabelID = E; }
+  
+  /// AddScope - Add a scope to the scope.
+  ///
+  void AddScope(DbgScope *S) { Scopes.push_back(S); }
+  
+  /// AddVariable - Add a variable to the scope.
+  ///
+  void AddVariable(DbgVariable *V) { Variables.push_back(V); }
+};
+
 //===----------------------------------------------------------------------===//
 /// DwarfDebug - Emits Dwarf debug directives.
 ///
@@ -1163,7 +1283,7 @@ private:
   /// CompileUnits - All the compile units involved in this build.  The index
   /// of each entry in this vector corresponds to the sources in MMI.
   std::vector<CompileUnit *> CompileUnits;
-  DenseMap<GlobalVariable *, CompileUnit *> DW_CUs;
+  DenseMap<Value *, CompileUnit *> DW_CUs;
 
   /// AbbreviationsSet - Used to uniquely define abbreviations.
   ///
@@ -1181,6 +1301,9 @@ private:
   // SourceFiles - Uniquing vector for source files.                                      
   UniqueVector<SrcFileInfo> SrcFiles;
 
+  // Lines - List of of source line correspondence.
+  std::vector<SrcLineInfo> Lines;
+
   FoldingSet<DIEValue> ValuesSet;
 
   /// Values - A list of all the unique values in use.
@@ -1211,6 +1334,44 @@ private:
   ///
   bool shouldEmit;
 
+  // RootScope - Top level scope for the current function.
+  //
+  DbgScope *RootDbgScope;
+  
+  // DbgScopeMap - Tracks the scopes in the current function.
+  DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
+  
+  // DbgLabelIDList - One entry per assigned label.  Normally the entry is equal to
+  // the list index(+1).  If the entry is zero then the label has been deleted.
+  // Any other value indicates the label has been deleted by is mapped to
+  // another label.
+  SmallVector<unsigned, 32> DbgLabelIDList;
+
+  /// NextLabelID - Return the next unique label id.
+  ///
+  unsigned NextLabelID() {
+    unsigned ID = (unsigned)DbgLabelIDList.size() + 1;
+    DbgLabelIDList.push_back(ID);
+    return ID;
+  }
+
+  /// RemapLabel - Indicate that a label has been merged into another.
+  ///
+  void RemapLabel(unsigned OldLabelID, unsigned NewLabelID) {
+    assert(0 < OldLabelID && OldLabelID <= DbgLabelIDList.size() &&
+          "Old label ID out of range.");
+    assert(NewLabelID <= DbgLabelIDList.size() &&
+          "New label ID out of range.");
+    DbgLabelIDList[OldLabelID - 1] = NewLabelID;
+  }
+  
+  /// MappedLabel - Find out the label's final ID.  Zero indicates deletion.
+  /// ID != Mapped ID indicates that the label was folded into another label.
+  unsigned MappedLabel(unsigned LabelID) const {
+    assert(LabelID <= DbgLabelIDList.size() && "Debug label ID out of range.");
+    return LabelID ? DbgLabelIDList[LabelID - 1] : 0;
+  }
+
   struct FunctionDebugFrameInfo {
     unsigned Number;
     std::vector<MachineMove> Moves;
@@ -1450,6 +1611,25 @@ private:
     }
   }
 
+  /// AddSourceLine - Add location information to specified debug information
+  /// entry.
+  void AddSourceLine(DIE *Die, DIVariable *V) {
+    unsigned FileID = 0;
+    unsigned Line = V->getLineNumber();
+    if (V->getVersion() < DIDescriptor::Version7) {
+      // Version6 or earlier. Use compile unit info to get file id.
+      CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
+      FileID = Unit->getID();
+    } else {
+      // Version7 or newer, use filename and directory info from DIVariable
+      // directly.
+      unsigned DID = Directories.idFor(V->getDirectory());
+      FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
+    }
+    AddUInt(Die, DW_AT_decl_file, 0, FileID);
+    AddUInt(Die, DW_AT_decl_line, 0, Line);
+  }
+
   /// AddSourceLine - Add location information to specified debug information
   /// entry.
   void AddSourceLine(DIE *Die, DIGlobal *G) {
@@ -2351,6 +2531,235 @@ private:
     return VariableDie;
   }
 
+  /// NewScopeVariable - Create a new scope variable.
+  ///
+  DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
+    // Get the descriptor.
+    DIVariable *VD = DV->getVariable();
+
+    // 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);
+    AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
+
+    // Add source line info if available.
+    AddSourceLine(VariableDie, VD);
+
+    // Add variable type.
+    AddType(Unit, VariableDie, VD->getType());
+
+    // Add variable address.
+    MachineLocation Location;
+    Location.set(RI->getFrameRegister(*MF),
+                 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
+    AddAddress(VariableDie, DW_AT_location, Location);
+
+    return VariableDie;
+  }
+
+  unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
+    CompileUnit *Unit = DW_CUs[V];
+    assert (Unit && "Unable to find CompileUnit");
+    unsigned ID = NextLabelID();
+    Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
+    return ID;
+  }
+  
+  unsigned getRecordSourceLineCount() {
+    return Lines.size();
+  }
+                            
+  unsigned RecordSource(const std::string &Directory,
+                        const std::string &File) {
+    unsigned DID = Directories.insert(Directory);
+    return SrcFiles.insert(SrcFileInfo(DID,File));
+  }
+
+  /// RecordRegionStart - Indicate the start of a region.
+  ///
+  unsigned RecordRegionStart(GlobalVariable *V) {
+    DbgScope *Scope = getOrCreateScope(V);
+    unsigned ID = NextLabelID();
+    if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
+    return ID;
+  }
+
+  /// RecordRegionEnd - Indicate the end of a region.
+  ///
+  unsigned RecordRegionEnd(GlobalVariable *V) {
+    DbgScope *Scope = getOrCreateScope(V);
+    unsigned ID = NextLabelID();
+    Scope->setEndLabelID(ID);
+    return ID;
+  }
+
+  /// RecordVariable - Indicate the declaration of  a local variable.
+  ///
+  void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
+    DbgScope *Scope = getOrCreateScope(GV);
+    DIVariable *VD = new DIVariable(GV);
+    DbgVariable *DV = new DbgVariable(VD, FrameIndex);
+    Scope->AddVariable(DV);
+  }
+
+  /// getOrCreateScope - Returns the scope associated with the given descriptor.
+  ///
+  DbgScope *getOrCreateScope(GlobalVariable *V) {
+    DbgScope *&Slot = DbgScopeMap[V];
+    if (!Slot) {
+      // FIXME - breaks down when the context is an inlined function.
+      DIDescriptor ParentDesc;
+      DIBlock *DB = new DIBlock(V);
+      if (DIBlock *Block = dyn_cast<DIBlock>(DB)) {
+        ParentDesc = Block->getContext();
+      }
+      DbgScope *Parent = ParentDesc.isNull() ? 
+        getOrCreateScope(ParentDesc.getGV()) : NULL;
+      Slot = new DbgScope(Parent, DB);
+      if (Parent) {
+        Parent->AddScope(Slot);
+      } else if (RootDbgScope) {
+        // FIXME - Add inlined function scopes to the root so we can delete
+        // them later.  Long term, handle inlined functions properly.
+        RootDbgScope->AddScope(Slot);
+      } else {
+        // First function is top level function.
+        RootDbgScope = Slot;
+      }
+    }
+    return Slot;
+  }
+
+  /// ConstructDbgScope - Construct the components of a scope.
+  ///
+  void ConstructDbgScope(DbgScope *ParentScope,
+                         unsigned ParentStartID, unsigned ParentEndID,
+                         DIE *ParentDie, CompileUnit *Unit) {
+    // Add variables to scope.
+    SmallVector<DbgVariable *, 32> &Variables = ParentScope->getVariables();
+    for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
+      DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
+      if (VariableDie) ParentDie->AddChild(VariableDie);
+    }
+
+    // Add nested scopes.
+    SmallVector<DbgScope *, 8> &Scopes = ParentScope->getScopes();
+    for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
+      // Define the Scope debug information entry.
+      DbgScope *Scope = Scopes[j];
+      // FIXME - Ignore inlined functions for the time being.
+      if (!Scope->getParent()) continue;
+
+      unsigned StartID = MappedLabel(Scope->getStartLabelID());
+      unsigned EndID = MappedLabel(Scope->getEndLabelID());
+
+      // Ignore empty scopes.
+      if (StartID == EndID && StartID != 0) continue;
+      if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
+
+      if (StartID == ParentStartID && EndID == ParentEndID) {
+        // Just add stuff to the parent scope.
+        ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
+      } else {
+        DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
+
+        // Add the scope bounds.
+        if (StartID) {
+          AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
+                             DWLabel("label", StartID));
+        } else {
+          AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
+                             DWLabel("func_begin", SubprogramCount));
+        }
+        if (EndID) {
+          AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
+                             DWLabel("label", EndID));
+        } else {
+          AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
+                             DWLabel("func_end", SubprogramCount));
+        }
+
+        // Add the scope contents.
+        ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
+        ParentDie->AddChild(ScopeDie);
+      }
+    }
+  }
+
+  /// ConstructRootDbgScope - Construct the scope for the subprogram.
+  ///
+  void ConstructRootDbgScope(DbgScope *RootScope) {
+    // Exit if there is no root scope.
+    if (!RootScope) return;
+
+    // Get the subprogram debug information entry.
+    DISubprogram *SPD = cast<DISubprogram>(RootScope->getDesc());
+
+    // Get the compile unit context.
+    CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
+
+    // Get the subprogram die.
+    DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
+    assert(SPDie && "Missing subprogram descriptor");
+
+    // Add the function bounds.
+    AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
+                    DWLabel("func_begin", SubprogramCount));
+    AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
+                    DWLabel("func_end", SubprogramCount));
+    MachineLocation Location(RI->getFrameRegister(*MF));
+    AddAddress(SPDie, DW_AT_frame_base, Location);
+
+    ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
+  }
+
+  /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
+  ///
+  void ConstructDefaultDbgScope(MachineFunction *MF) {
+    // Find the correct subprogram descriptor.
+    std::string SPName = "llvm.dbg.subprograms";
+    std::vector<GlobalVariable*> Result;
+    getGlobalVariablesUsing(*M, SPName, Result);
+    for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
+           E = Result.end(); I != E; ++I) {
+
+      DISubprogram *SPD = new DISubprogram(*I);
+
+      if (SPD->getName() == MF->getFunction()->getName()) {
+        // Get the compile unit context.
+        CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
+
+        // Get the subprogram die.
+        DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
+        assert(SPDie && "Missing subprogram descriptor");
+
+        // Add the function bounds.
+        AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
+                 DWLabel("func_begin", SubprogramCount));
+        AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
+                 DWLabel("func_end", SubprogramCount));
+
+        MachineLocation Location(RI->getFrameRegister(*MF));
+        AddAddress(SPDie, DW_AT_frame_base, Location);
+        return;
+      }
+    }
+#if 0
+    // FIXME: This is causing an abort because C++ mangled names are compared
+    // with their unmangled counterparts. See PR2885. Don't do this assert.
+    assert(0 && "Couldn't find DIE for machine function!");
+#endif
+  }
+
   /// ConstructScope - Construct the components of a scope.
   ///
   void ConstructScope(DebugScope *ParentScope,
@@ -3074,6 +3483,32 @@ private:
     Asm->EOL();
   }
 
+  /// ConstructCompileUnits - Create a compile unit DIEs.
+  void ConstructCompileUnits() {
+    std::string CUName = "llvm.dbg.compile_units";
+    std::vector<GlobalVariable*> Result;
+    getGlobalVariablesUsing(*M, CUName, Result);
+    for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
+           RE = Result.end(); RI != RE; ++RI) {
+      DICompileUnit *DIUnit = new DICompileUnit(*RI);
+      unsigned ID = RecordSource(DIUnit->getDirectory(),
+                                 DIUnit->getFilename());
+
+      DIE *Die = new DIE(DW_TAG_compile_unit);
+      AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
+                       DWLabel("section_line", 0), DWLabel("section_line", 0),
+                       false);
+      AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit->getProducer());
+      AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit->getLanguage());
+      AddString(Die, DW_AT_name, DW_FORM_string, DIUnit->getFilename());
+      if (!DIUnit->getDirectory().empty())
+        AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit->getDirectory());
+
+      CompileUnit *Unit = new CompileUnit(ID, Die);
+      DW_CUs[DIUnit->getGV()] = Unit;
+    }
+  }
+
   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
   /// header file.
   void ConstructCompileUnitDIEs() {
@@ -3086,6 +3521,53 @@ private:
     }
   }
 
+  /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally 
+  /// visible global variables.
+  void ConstructGlobalVariableDIEs() {
+    std::string GVName = "llvm.dbg.global_variables";
+    std::vector<GlobalVariable*> Result;
+    getGlobalVariablesUsing(*M, GVName, Result);
+    for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
+           GVE = Result.end(); GVI != GVE; ++GVI) {
+      DIGlobalVariable *DI_GV = new DIGlobalVariable(*GVI);
+      CompileUnit *DW_Unit = FindCompileUnit(DI_GV->getCompileUnit());
+
+      // Check for pre-existence.
+      DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV->getGV());
+      if (Slot) continue;
+
+      DIE *VariableDie = new DIE(DW_TAG_variable);
+      AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV->getName());
+      const std::string &LinkageName  = DI_GV->getLinkageName();
+      if (!LinkageName.empty())
+        AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
+                  LinkageName);
+      AddType(DW_Unit, VariableDie, DI_GV->getType());
+
+      if (!DI_GV->isLocalToUnit())
+        AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);              
+
+      // Add source line info, if available.
+      AddSourceLine(VariableDie, DI_GV);
+
+      // Add address.
+      DIEBlock *Block = new DIEBlock();
+      AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
+      AddObjectLabel(Block, 0, DW_FORM_udata,
+                     Asm->getGlobalLinkName(DI_GV->getGV()));
+      AddBlock(VariableDie, DW_AT_location, 0, Block);
+
+      //Add to map.
+      Slot = VariableDie;
+
+      //Add to context owner.
+      DW_Unit->getDie()->AddChild(VariableDie);
+
+      //Expose as global. FIXME - need to check external flag.
+      DW_Unit->AddGlobal(DI_GV->getName(), VariableDie);
+    }
+  }
+
   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
   /// global variables.
   void ConstructGlobalDIEs() {
@@ -3098,6 +3580,45 @@ private:
     }
   }
 
+  /// ConstructSubprograms - Create DIEs for each of the externally visible
+  /// subprograms.
+  void ConstructSubprograms() {
+
+    std::string SPName = "llvm.dbg.subprograms";
+    std::vector<GlobalVariable*> Result;
+    getGlobalVariablesUsing(*M, SPName, Result);
+    for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
+           RE = Result.end(); RI != RE; ++RI) {
+
+      DISubprogram *SP = new DISubprogram(*RI);
+      CompileUnit *Unit = FindCompileUnit(SP->getCompileUnit());
+
+      // Check for pre-existence.                                                         
+      DIE *&Slot = Unit->getDieMapSlotFor(SP->getGV());
+      if (Slot) continue;
+
+      DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
+      AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP->getName());
+      const std::string &LinkageName = SP->getLinkageName();
+      if (!LinkageName.empty())
+        AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
+                  LinkageName);
+      DIType SPTy = SP->getType();
+      AddType(Unit, SubprogramDie, SPTy);
+      if (!SP->isLocalToUnit())
+        AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
+      AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
+
+      AddSourceLine(SubprogramDie, SP);
+      //Add to map.
+      Slot = SubprogramDie;
+      //Add to context owner.
+      Unit->getDie()->AddChild(SubprogramDie);
+      //Expose as global.
+      Unit->AddGlobal(SP->getName(), SubprogramDie);
+    }
+  }
+
   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
   /// subprograms.
   void ConstructSubprogramDIEs() {
@@ -3127,6 +3648,7 @@ public:
   , SectionSourceLines()
   , didInitial(false)
   , shouldEmit(false)
+  , RootDbgScope(NULL)
   {
   }
   virtual ~DwarfDebug() {
@@ -3136,6 +3658,39 @@ public:
       delete Values[j];
   }
 
+  /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
+  /// This is inovked by the target AsmPrinter.
+  void SetDebugInfo() {
+    // FIXME - Check if the module has debug info or not.
+      // Create all the compile unit DIEs.
+      ConstructCompileUnits();
+
+      // Create DIEs for each of the externally visible global variables.
+      ConstructGlobalVariableDIEs();
+
+      // Create DIEs for each of the externally visible subprograms.
+      ConstructSubprograms();
+
+      // Prime section data.
+      SectionMap.insert(TAI->getTextSection());
+
+      // Print out .file directives to specify files for .loc directives. These
+      // are printed out early so that they precede any .loc directives.
+      if (TAI->hasDotLocAndDotFile()) {
+        for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
+          sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
+          bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
+          assert(AppendOk && "Could not append filename to directory!");
+          AppendOk = false;
+          Asm->EmitFile(i, FullPath.toString());
+          Asm->EOL();
+        }
+      }
+
+      // Emit initial sections
+      EmitInitial();
+  }
+
   /// SetModuleInfo - Set machine module information when it's known that pass
   /// manager has created it.  Set by the target AsmPrinter.
   void SetModuleInfo(MachineModuleInfo *mmi) {
@@ -3498,10 +4053,10 @@ private:
 
       Asm->EOL("FDE CIE offset");
 
-      EmitReference("eh_func_begin", EHFrameInfo.Number, true);
+      EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
       Asm->EOL("FDE initial location");
       EmitDifference("eh_func_end", EHFrameInfo.Number,
-                     "eh_func_begin", EHFrameInfo.Number);
+                     "eh_func_begin", EHFrameInfo.Number, true);
       Asm->EOL("FDE address range");
 
       // If there is a personality and landing pads then point to the language
@@ -4346,10 +4901,7 @@ void DIE::dump() {
 /// DwarfWriter Implementation
 ///
 
-DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
-                         const TargetAsmInfo *T) {
-  DE = new DwarfException(OS, A, T);
-  DD = new DwarfDebug(OS, A, T);
+DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
 }
 
 DwarfWriter::~DwarfWriter() {
@@ -4357,18 +4909,18 @@ DwarfWriter::~DwarfWriter() {
   delete DD;
 }
 
-/// SetModuleInfo - Set machine module info when it's known that pass manager
-/// has created it.  Set by the target AsmPrinter.
-void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
-  DD->SetModuleInfo(MMI);
-  DE->SetModuleInfo(MMI);
-}
-
 /// BeginModule - Emit all Dwarf sections that should come prior to the
 /// content.
-void DwarfWriter::BeginModule(Module *M) {
+void DwarfWriter::BeginModule(Module *M,
+                              MachineModuleInfo *MMI,
+                              raw_ostream &OS, AsmPrinter *A,
+                              const TargetAsmInfo *T) {
+  DE = new DwarfException(OS, A, T);
+  DD = new DwarfDebug(OS, A, T);
   DE->BeginModule(M);
   DD->BeginModule(M);
+  DD->SetModuleInfo(MMI);
+  DE->SetModuleInfo(MMI);
 }
 
 /// EndModule - Emit all Dwarf sections that should come after the content.