Change references from Method to Function
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
index c3f4c907fea88cc003d7f864e474257ea983fcbb..0b2e935ed4e56bf7f741fda6253e95f1d5688c74 100644 (file)
@@ -1,4 +1,4 @@
-//===- Reader.cpp - Code to read bytecode files -----------------------------===
+//===- Reader.cpp - Code to read bytecode files ---------------------------===//
 //
 // This library implements the functionality defined in llvm/Bytecode/Reader.h
 //
@@ -8,32 +8,44 @@
 // TODO: Make error message outputs be configurable depending on an option?
 // TODO: Allow passing in an option to ignore the symbol table
 //
-//===------------------------------------------------------------------------===
+//===----------------------------------------------------------------------===//
 
+#include "ReaderInternals.h"
 #include "llvm/Bytecode/Reader.h"
 #include "llvm/Bytecode/Format.h"
+#include "llvm/GlobalVariable.h"
 #include "llvm/Module.h"
 #include "llvm/BasicBlock.h"
-#include "llvm/DerivedTypes.h"
-#include "llvm/ConstPoolVals.h"
+#include "llvm/ConstantVals.h"
+#include "llvm/iPHINode.h"
 #include "llvm/iOther.h"
-#include "ReaderInternals.h"
 #include <sys/types.h>
-#include <sys/mman.h>
 #include <sys/stat.h>
+#include <sys/mman.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <algorithm>
+#include <iostream>
+using std::cerr;
+using std::make_pair;
 
 bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
   if (Ty->isPrimitiveType()) {
     Slot = Ty->getPrimitiveID();
   } else {
-    TypeMapType::iterator I = TypeMap.find(Ty);
-    if (I == TypeMap.end()) return true;   // Didn't find type!
-    Slot = I->second;
+    // Check the method level types first...
+    TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
+                                       MethodTypeValues.end(), Ty);
+    if (I != MethodTypeValues.end()) {
+      Slot = FirstDerivedTyID+ModuleTypeValues.size()+
+             (&*I - &MethodTypeValues[0]);
+    } else {
+      I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
+      if (I == ModuleTypeValues.end()) return true;   // Didn't find type!
+      Slot = FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
+    }
   }
-  //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << endl;
+  //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << "\n";
   return false;
 }
 
@@ -41,60 +53,57 @@ const Type *BytecodeParser::getType(unsigned ID) {
   const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
   if (T) return T;
   
-  //cerr << "Looking up Type ID: " << ID << endl;
+  //cerr << "Looking up Type ID: " << ID << "\n";
 
   const Value *D = getValue(Type::TypeTy, ID, false);
-  if (D == 0) return 0;
+  if (D == 0) return failure<const Type*>(0);
 
-  assert(D->getType() == Type::TypeTy &&
-        D->getValueType() == Value::ConstantVal);
-
-
-  return ((const ConstPoolType*)D)->getValue();;
+  return cast<Type>(D);
 }
 
-bool BytecodeParser::insertValue(Value *Def, vector<ValueList> &ValueTab) {
+int BytecodeParser::insertValue(Value *Val, std::vector<ValueList> &ValueTab) {
   unsigned type;
-  if (getTypeSlot(Def->getType(), type)) return true;
+  if (getTypeSlot(Val->getType(), type)) return failure<int>(-1);
+  assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
  
   if (ValueTab.size() <= type)
     ValueTab.resize(type+1, ValueList());
 
   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
-  //     << "] = " << Def << endl;
-
-  if (type == Type::TypeTyID && Def->getValueType() == Value::ConstantVal) {
-    const Type *Ty = ((const ConstPoolType*)Def)->getValue();
-    unsigned ValueOffset = FirstDerivedTyID;
-
-    if (&ValueTab == &Values)    // Take into consideration module level types
-      ValueOffset += ModuleValues[type].size();
+  //     << "] = " << Val << "\n";
+  ValueTab[type].push_back(Val);
 
-    if (TypeMap.find(Ty) == TypeMap.end())
-      TypeMap[Ty] = ValueTab[type].size()+ValueOffset;
-  }
-
-  ValueTab[type].push_back(Def);
-
-  return false;
+  return ValueTab[type].size()-1;
 }
 
 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
   unsigned Num = oNum;
   unsigned type;   // The type plane it lives in...
 
-  if (getTypeSlot(Ty, type)) return 0; // TODO: true
+  if (getTypeSlot(Ty, type)) return failure<Value*>(0); // TODO: true
 
   if (type == Type::TypeTyID) {  // The 'type' plane has implicit values
+    assert(Create == false);
     const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
     if (T) return (Value*)T;   // Asked for a primitive type...
 
     // Otherwise, derived types need offset...
     Num -= FirstDerivedTyID;
+
+    // Is it a module level type?
+    if (Num < ModuleTypeValues.size())
+      return (Value*)ModuleTypeValues[Num].get();
+
+    // Nope, is it a method level type?
+    Num -= ModuleTypeValues.size();
+    if (Num < MethodTypeValues.size())
+      return (Value*)MethodTypeValues[Num].get();
+
+    return 0;
   }
 
-  if (ModuleValues.size() > type) {
-    if (ModuleValues[type].size() > Num)
+  if (type < ModuleValues.size()) {
+    if (Num < ModuleValues[type].size())
       return ModuleValues[type][Num];
     Num -= ModuleValues[type].size();
   }
@@ -102,28 +111,28 @@ Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
   if (Values.size() > type && Values[type].size() > Num)
     return Values[type][Num];
 
-  if (!Create) return 0;  // Do not create a placeholder?
+  if (!Create) return failure<Value*>(0);  // Do not create a placeholder?
 
   Value *d = 0;
   switch (Ty->getPrimitiveID()) {
   case Type::LabelTyID: d = new    BBPHolder(Ty, oNum); break;
   case Type::MethodTyID:
     cerr << "Creating method pholder! : " << type << ":" << oNum << " " 
-        << Ty->getName() << endl;
+        << Ty->getName() << "\n";
     d = new MethPHolder(Ty, oNum);
-    insertValue(d, LateResolveModuleValues);
+    if (insertValue(d, LateResolveModuleValues) ==-1) return failure<Value*>(0);
     return d;
   default:                   d = new   DefPHolder(Ty, oNum); break;
   }
 
   assert(d != 0 && "How did we not make something?");
-  if (insertValue(d, LateResolveValues)) return 0;
+  if (insertValue(d, LateResolveValues) == -1) return failure<Value*>(0);
   return d;
 }
 
 bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
   bool Error = false;
-  for (unsigned ty = 0; ty < ValTab.size(); ty++) {
+  for (unsigned ty = 0; ty < ValTab.size(); ++ty) {
     ValueList &DL = ValTab[ty];
     unsigned Size;
     while ((Size = DL.size())) {
@@ -135,8 +144,8 @@ bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
       Value *NewDef = getValue(D->getType(), IDNumber, false);
       if (NewDef == 0) {
        Error = true;  // Unresolved thinger
-       cerr << "Unresolvable reference found: <" << D->getType()->getName()
-            << ">:" << IDNumber << "!\n";
+       cerr << "Unresolvable reference found: <"
+             << D->getType()->getDescription() << ">:" << IDNumber << "!\n";
       } else {
        // Fixup all of the uses of this placeholder def...
         D->replaceAllUsesWith(NewDef);
@@ -156,86 +165,151 @@ bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf,
   BB = new BasicBlock();
 
   while (Buf < EndBuf) {
-    Instruction *Def;
-    if (ParseInstruction(Buf, EndBuf, Def)) {
+    Instruction *Inst;
+    if (ParseInstruction(Buf, EndBuf, Inst)) {
       delete BB;
-      return true;
+      return failure(true);
     }
 
-    if (Def == 0) { delete BB; return true; }
-    if (insertValue(Def, Values)) { delete BB; return true; }
+    if (Inst == 0) { delete BB; return failure(true); }
+    if (insertValue(Inst, Values) == -1) { delete BB; return failure(true); }
+
+    BB->getInstList().push_back(Inst);
 
-    BB->getInstList().push_back(Def);
+    BCR_TRACE(4, Inst);
   }
 
   return false;
 }
 
-bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf) {
+bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
+                                     SymbolTable *ST) {
   while (Buf < EndBuf) {
     // Symtab block header: [num entries][type id number]
     unsigned NumEntries, Typ;
     if (read_vbr(Buf, EndBuf, NumEntries) ||
-        read_vbr(Buf, EndBuf, Typ)) return true;
+        read_vbr(Buf, EndBuf, Typ)) return failure(true);
     const Type *Ty = getType(Typ);
-    if (Ty == 0) return true;
+    if (Ty == 0) return failure(true);
 
-    for (unsigned i = 0; i < NumEntries; i++) {
+    BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
+             " entries\n");
+
+    for (unsigned i = 0; i < NumEntries; ++i) {
       // Symtab entry: [def slot #][name]
       unsigned slot;
-      if (read_vbr(Buf, EndBuf, slot)) return true;
-      string Name;
+      if (read_vbr(Buf, EndBuf, slot)) return failure(true);
+      std::string Name;
       if (read(Buf, EndBuf, Name, false))  // Not aligned...
-       return true;
+       return failure(true);
 
       Value *D = getValue(Ty, slot, false); // Find mapping...
-      if (D == 0) return true;
-      D->setName(Name);
+      if (D == 0) {
+       BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << "\n");
+       return failure(true);
+      }
+      BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << D;
+               if (!isa<Instruction>(D)) cerr << "\n");
+
+      D->setName(Name, ST);
     }
   }
 
-  return Buf > EndBuf;
+  if (Buf > EndBuf) return failure(true);
+  return false;
 }
 
+// DeclareNewGlobalValue - Patch up forward references to global values in the
+// form of ConstantPointerRef.
+//
+void BytecodeParser::DeclareNewGlobalValue(GlobalValue *GV, unsigned Slot) {
+  // Check to see if there is a forward reference to this global variable...
+  // if there is, eliminate it and patch the reference to use the new def'n.
+  GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), Slot));
+
+  if (I != GlobalRefs.end()) {
+    GlobalVariable *OldGV = I->second;   // Get the placeholder...
+    BCR_TRACE(3, "Mutating CPPR Forward Ref!\n");
+      
+    // Loop over all of the uses of the GlobalValue.  The only thing they are
+    // allowed to be at this point is ConstantPointerRef's.
+    assert(OldGV->use_size() == 1 && "Only one reference should exist!");
+    while (!OldGV->use_empty()) {
+      User *U = OldGV->use_back();  // Must be a ConstantPointerRef...
+      ConstantPointerRef *CPPR = cast<ConstantPointerRef>(U);
+      assert(CPPR->getValue() == OldGV && "Something isn't happy");
+      
+      BCR_TRACE(4, "Mutating Forward Ref!\n");
+      
+      // Change the const pool reference to point to the real global variable
+      // now.  This should drop a use from the OldGV.
+      CPPR->mutateReference(GV);
+    }
+    
+    // Remove GV from the module...
+    GV->getParent()->getGlobalList().remove(OldGV);
+    delete OldGV;                        // Delete the old placeholder
+    
+    // Remove the map entry for the global now that it has been created...
+    GlobalRefs.erase(I);
+  }
+}
 
 bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf, 
                                 Module *C) {
   // Clear out the local values table...
   Values.clear();
-  if (MethodSignatureList.empty()) return true;  // Unexpected method!
+  if (MethodSignatureList.empty()) {
+    Error = "Method found, but MethodSignatureList empty!";
+    return failure(true);  // Unexpected method!
+  }
+
+  const PointerType *PMTy = MethodSignatureList.front().first; // PtrMeth
+  const MethodType  *MTy  = dyn_cast<const MethodType>(PMTy->getElementType());
+  if (MTy == 0) return failure(true);  // Not ptr to method!
+
+  unsigned isInternal;
+  if (read_vbr(Buf, EndBuf, isInternal)) return failure(true);
 
-  const MethodType *MTy = MethodSignatureList.front().first;
   unsigned MethSlot = MethodSignatureList.front().second;
   MethodSignatureList.pop_front();
-  Method *M = new Method(MTy);
+  Method *M = new Method(MTy, isInternal != 0);
+
+  BCR_TRACE(2, "METHOD TYPE: " << MTy << "\n");
 
   const MethodType::ParamTypes &Params = MTy->getParamTypes();
   for (MethodType::ParamTypes::const_iterator It = Params.begin();
-       It != Params.end(); It++) {
-    MethodArgument *MA = new MethodArgument(*It);
-    if (insertValue(MA, Values)) { delete M; return true; }
-    M->getArgumentList().push_back(MA);
+       It != Params.end(); ++It) {
+    FunctionArgument *FA = new FunctionArgument(*It);
+    if (insertValue(FA, Values) == -1) {
+      Error = "Error reading method arguments!\n";
+      delete M; return failure(true); 
+    }
+    M->getArgumentList().push_back(FA);
   }
 
   while (Buf < EndBuf) {
     unsigned Type, Size;
     const uchar *OldBuf = Buf;
-    if (readBlock(Buf, EndBuf, Type, Size)) { delete M; return true; }
+    if (readBlock(Buf, EndBuf, Type, Size)) {
+      Error = "Error reading Method level block!";
+      delete M; return failure(true); 
+    }
 
     switch (Type) {
     case BytecodeFormat::ConstantPool:
-      if (ParseConstantPool(Buf, Buf+Size, M->getConstantPool(), Values)) {
-       cerr << "Error reading constant pool!\n";
-       delete M; return true;
+      BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
+      if (ParseConstantPool(Buf, Buf+Size, Values, MethodTypeValues)) {
+       delete M; return failure(true);
       }
       break;
 
     case BytecodeFormat::BasicBlock: {
+      BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
       BasicBlock *BB;
       if (ParseBasicBlock(Buf, Buf+Size, BB) ||
-         insertValue(BB, Values)) {
-       cerr << "Error parsing basic block!\n";
-       delete M; return true;                       // Parse error... :(
+         insertValue(BB, Values) == -1) {
+       delete M; return failure(true);                // Parse error... :(
       }
 
       M->getBasicBlocks().push_back(BB);
@@ -243,90 +317,155 @@ bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf,
     }
 
     case BytecodeFormat::SymbolTable:
-      if (ParseSymbolTable(Buf, Buf+Size)) {
-       cerr << "Error reading method symbol table!\n";
-       delete M; return true;
+      BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
+      if (ParseSymbolTable(Buf, Buf+Size, M->getSymbolTableSure())) {
+       delete M; return failure(true);
       }
       break;
 
     default:
+      BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
       Buf += Size;
-      if (OldBuf > Buf) return true; // Wrap around!
+      if (OldBuf > Buf) return failure(true); // Wrap around!
       break;
     }
+    BCR_TRACE(2, "} end block\n");
+
     if (align32(Buf, EndBuf)) {
+      Error = "Error aligning Method level block!";
       delete M;    // Malformed bc file, read past end of block.
-      return true;
+      return failure(true);
     }
   }
 
   if (postResolveValues(LateResolveValues) ||
       postResolveValues(LateResolveModuleValues)) {
-    delete M; return true;     // Unresolvable references!
+    Error = "Error resolving method values!";
+    delete M; return failure(true);     // Unresolvable references!
   }
 
-  Value *MethPHolder = getValue(MTy, MethSlot, false);
+  Value *MethPHolder = getValue(PMTy, MethSlot, false);
   assert(MethPHolder && "Something is broken no placeholder found!");
-  assert(MethPHolder->getValueType() == Value::MethodVal && "Not a method?");
+  assert(isa<Method>(MethPHolder) && "Not a method?");
 
   unsigned type;  // Type slot
   assert(!getTypeSlot(MTy, type) && "How can meth type not exist?");
-  getTypeSlot(MTy, type);
+  getTypeSlot(PMTy, type);
 
-  C->getMethodList().push_back(M);
+  C->getFunctionList().push_back(M);
 
   // Replace placeholder with the real method pointer...
   ModuleValues[type][MethSlot] = M;
 
+  // Clear out method level types...
+  MethodTypeValues.clear();
+
   // If anyone is using the placeholder make them use the real method instead
   MethPHolder->replaceAllUsesWith(M);
 
   // We don't need the placeholder anymore!
   delete MethPHolder;
 
+  // If the method is empty, we don't need the method argument entries...
+  if (M->isExternal())
+    M->getArgumentList().delete_all();
+
+  DeclareNewGlobalValue(M, MethSlot);
+
   return false;
 }
 
 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
-                                         Module *C) {
+                                          Module *Mod) {
+  if (!MethodSignatureList.empty()) {
+    Error = "Two ModuleGlobalInfo packets found!";
+    return failure(true);  // Two ModuleGlobal blocks?
+  }
+
+  // Read global variables...
+  unsigned VarType;
+  if (read_vbr(Buf, End, VarType)) return failure(true);
+  while (VarType != Type::VoidTyID) { // List is terminated by Void
+    // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
+    // bit2 = isInternal, bit3+ = slot#
+    const Type *Ty = getType(VarType >> 3);
+    if (!Ty || !Ty->isPointerType()) { 
+      Error = "Global not pointer type!  Ty = " + Ty->getDescription();
+      return failure(true); 
+    }
+
+    const PointerType *PTy = cast<const PointerType>(Ty);
+    const Type *ElTy = PTy->getElementType();
+
+    Constant *Initializer = 0;
+    if (VarType & 2) { // Does it have an initalizer?
+      // Do not improvise... values must have been stored in the constant pool,
+      // which should have been read before now.
+      //
+      unsigned InitSlot;
+      if (read_vbr(Buf, End, InitSlot)) return failure(true);
+      
+      Value *V = getValue(ElTy, InitSlot, false);
+      if (V == 0) return failure(true);
+      Initializer = cast<Constant>(V);
+    }
+
+    // Create the global variable...
+    GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, VarType & 4,
+                                           Initializer);
+    int DestSlot = insertValue(GV, ModuleValues);
+    if (DestSlot == -1) return failure(true);
 
-  if (!MethodSignatureList.empty()) return true;  // Two ModuleGlobal blocks?
+    Mod->getGlobalList().push_back(GV);
+
+    DeclareNewGlobalValue(GV, unsigned(DestSlot));
+
+    BCR_TRACE(2, "Global Variable of type: " << PTy->getDescription() 
+             << " into slot #" << DestSlot << "\n");
+
+    if (read_vbr(Buf, End, VarType)) return failure(true);
+  }
 
   // Read the method signatures for all of the methods that are coming, and 
   // create fillers in the Value tables.
   unsigned MethSignature;
-  if (read_vbr(Buf, End, MethSignature)) return true;
+  if (read_vbr(Buf, End, MethSignature)) return failure(true);
   while (MethSignature != Type::VoidTyID) { // List is terminated by Void
     const Type *Ty = getType(MethSignature);
-    if (!Ty || !Ty->isMethodType()) { 
-      cerr << "Method not meth type! ";
-      if (Ty) cerr << Ty->getName(); else cerr << MethSignature; cerr << endl; 
-      return true
+    if (!Ty || !isa<PointerType>(Ty) ||
+        !isa<MethodType>(cast<PointerType>(Ty)->getElementType())) { 
+      Error = "Method not ptr to meth type!  Ty = " + Ty->getDescription();
+      return failure(true)
     }
+    
+    // We create methods by passing the underlying MethodType to create...
+    Ty = cast<PointerType>(Ty)->getElementType();
 
-    // When the ModuleGlobalInfo section is read, we load the type of each method
-    // and the 'ModuleValues' slot that it lands in.  We then load a placeholder
-    // into its slot to reserve it.  When the method is loaded, this placeholder
-    // is replaced.
+    // When the ModuleGlobalInfo section is read, we load the type of each 
+    // method and the 'ModuleValues' slot that it lands in.  We then load a 
+    // placeholder into its slot to reserve it.  When the method is loaded, this
+    // placeholder is replaced.
 
     // Insert the placeholder...
-    Value *Def = new MethPHolder(Ty, 0);
-    insertValue(Def, ModuleValues);
+    Value *Val = new MethPHolder(Ty, 0);
+    if (insertValue(Val, ModuleValues) == -1) return failure(true);
 
     // Figure out which entry of its typeslot it went into...
     unsigned TypeSlot;
-    if (getTypeSlot(Def->getType(), TypeSlot)) return true;
+    if (getTypeSlot(Val->getType(), TypeSlot)) return failure(true);
 
     unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
     
     // Keep track of this information in a linked list that is emptied as 
     // methods are loaded...
     //
-    MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
-    if (read_vbr(Buf, End, MethSignature)) return true;
+    MethodSignatureList.push_back(
+           make_pair(cast<const PointerType>(Val->getType()), SlotNo));
+    if (read_vbr(Buf, End, MethSignature)) return failure(true);
+    BCR_TRACE(2, "Method of type: " << Ty << "\n");
   }
 
-  if (align32(Buf, End)) return true;
+  if (align32(Buf, End)) return failure(true);
 
   // This is for future proofing... in the future extra fields may be added that
   // we don't understand, so we transparently ignore them.
@@ -339,61 +478,71 @@ bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
                                Module *&C) {
 
   unsigned Type, Size;
-  if (readBlock(Buf, EndBuf, Type, Size)) return true;
-  if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
-    return true;                               // Hrm, not a class?
+  if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
+  if (Type != BytecodeFormat::Module || Buf+Size != EndBuf) {
+    Error = "Expected Module packet!";
+    return failure(true);                      // Hrm, not a class?
+  }
 
+  BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
   MethodSignatureList.clear();                 // Just in case...
 
   // Read into instance variables...
-  if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return true;
-  if (align32(Buf, EndBuf)) return true;
-
-  C = new Module();
+  if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
+  if (align32(Buf, EndBuf)) return failure(true);
+  BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
 
+  TheModule = C = new Module();
   while (Buf < EndBuf) {
     const uchar *OldBuf = Buf;
-    if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return true; }
+    if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
     switch (Type) {
-    case BytecodeFormat::ModuleGlobalInfo:
-      if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
-       cerr << "Error reading class global info section!\n";
-       delete C; return true;
+    case BytecodeFormat::ConstantPool:
+      BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
+      if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
+       delete C; return failure(true);
       }
       break;
 
-    case BytecodeFormat::ConstantPool:
-      if (ParseConstantPool(Buf, Buf+Size, C->getConstantPool(), ModuleValues)) {
-       cerr << "Error reading class constant pool!\n";
-       delete C; return true;
+    case BytecodeFormat::ModuleGlobalInfo:
+      BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
+
+      if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
+       delete C; return failure(true);
       }
       break;
 
     case BytecodeFormat::Method: {
+      BCR_TRACE(1, "BLOCK BytecodeFormat::Method: {\n");
       if (ParseMethod(Buf, Buf+Size, C)) {
-       delete C; return true;               // Error parsing method
+       delete C; return failure(true);               // Error parsing method
       }
       break;
     }
 
     case BytecodeFormat::SymbolTable:
-      if (ParseSymbolTable(Buf, Buf+Size)) {
-       cerr << "Error reading class symbol table!\n";
-       delete C; return true;
+      BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
+      if (ParseSymbolTable(Buf, Buf+Size, C->getSymbolTableSure())) {
+       delete C; return failure(true);
       }
       break;
 
     default:
-      cerr << "Unknown class block: " << Type << endl;
+      Error = "Expected Module Block!";
       Buf += Size;
-      if (OldBuf > Buf) return true; // Wrap around!
+      if (OldBuf > Buf) return failure(true); // Wrap around!
       break;
     }
-    if (align32(Buf, EndBuf)) { delete C; return true; }
+    BCR_TRACE(1, "} end block\n");
+    if (align32(Buf, EndBuf)) { delete C; return failure(true); }
+  }
+
+  if (!MethodSignatureList.empty()) {     // Expected more methods!
+    Error = "Method expected, but bytecode stream at end!";
+    return failure(true);
   }
 
-  if (!MethodSignatureList.empty())      // Expected more methods!
-    return true;
+  BCR_TRACE(0, "} end block\n\n");
   return false;
 }
 
@@ -402,8 +551,10 @@ Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
   unsigned Sig;
   // Read and check signature...
   if (read(Buf, EndBuf, Sig) ||
-      Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
-    return 0;                                         // Invalid signature!
+      Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24)) {
+    Error = "Invalid bytecode signature!";
+    return failure<Module*>(0);                          // Invalid signature!
+  }
 
   Module *Result;
   if (ParseModule(Buf, EndBuf, Result)) return 0;
@@ -418,48 +569,61 @@ Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
 
 // Parse and return a class file...
 //
-Module *ParseBytecodeFile(const string &Filename) {
+Module *ParseBytecodeFile(const std::string &Filename, std::string *ErrorStr) {
   struct stat StatBuf;
   Module *Result = 0;
 
-  if (Filename != string("-")) {        // Read from a file...
-    int FD = open(Filename.data(), O_RDONLY);
-    if (FD == -1) return 0;
+  if (Filename != std::string("-")) {        // Read from a file...
+    int FD = open(Filename.c_str(), O_RDONLY);
+    if (FD == -1) {
+      if (ErrorStr) *ErrorStr = "Error opening file!";
+      return failure<Module*>(0);
+    }
 
-    if (fstat(FD, &StatBuf) == -1) { close(FD); return 0; }
+    if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
 
     int Length = StatBuf.st_size;
-    if (Length == 0) { close(FD); return 0; }
+    if (Length == 0) { 
+      if (ErrorStr) *ErrorStr = "Error stat'ing file!";
+      close(FD); return failure<Module*>(0); 
+    }
     uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ, 
                                MAP_PRIVATE, FD, 0);
-    if (Buffer == (uchar*)-1) { close(FD); return 0; }
+    if (Buffer == (uchar*)-1) {
+      if (ErrorStr) *ErrorStr = "Error mmapping file!";
+      close(FD); return failure<Module*>(0);
+    }
 
     BytecodeParser Parser;
     Result  = Parser.ParseBytecode(Buffer, Buffer+Length);
 
     munmap((char*)Buffer, Length);
     close(FD);
+    if (ErrorStr) *ErrorStr = Parser.getError();
   } else {                              // Read from stdin
     size_t FileSize = 0;
     int BlockSize;
     uchar Buffer[4096], *FileData = 0;
     while ((BlockSize = read(0, Buffer, 4))) {
-      if (BlockSize == -1) { free(FileData); return 0; }
+      if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
 
       FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
       memcpy(FileData+FileSize, Buffer, BlockSize);
       FileSize += BlockSize;
     }
 
-    if (FileSize == 0) { free(FileData); return 0; }
+    if (FileSize == 0) {
+      if (ErrorStr) *ErrorStr = "Standard Input empty!";
+      free(FileData); return failure<Module*>(0);
+    }
 
 #define ALIGN_PTRS 1
 #if ALIGN_PTRS
     uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE, 
                              MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
     assert((Buf != (uchar*)-1) && "mmap returned error!");
-    free(FileData);
     memcpy(Buf, FileData, FileSize);
+    free(FileData);
 #else
     uchar *Buf = FileData;
 #endif
@@ -472,6 +636,8 @@ Module *ParseBytecodeFile(const string &Filename) {
 #else
     free(FileData);          // Free realloc'd block of memory
 #endif
+
+    if (ErrorStr) *ErrorStr = Parser.getError();
   }
 
   return Result;