Major refactoring of the bytecode reader. This includes the following
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
index 805b7e7292b2e37620a4567287af9596cc8246c4..e649cdc08f142e6e14d4c6b23d1fdb0981a413aa 100644 (file)
 #include "ReaderInternals.h"
 #include "llvm/Bytecode/Reader.h"
 #include "llvm/Bytecode/Format.h"
-#include "llvm/Module.h"
 #include "llvm/Constants.h"
 #include "llvm/iPHINode.h"
 #include "llvm/iOther.h"
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/mman.h>
-#include <fcntl.h>
-#include <unistd.h>
+#include "llvm/Module.h"
+#include "Support/StringExtras.h"
+#include "Config/unistd.h"
+#include "Config/sys/mman.h"
+#include "Config/sys/stat.h"
+#include "Config/sys/types.h"
 #include <algorithm>
+#include <memory>
 
-bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
-  if (Ty->isPrimitiveType()) {
-    Slot = Ty->getPrimitiveID();
-  } else {
-    // Check the function level types first...
-    TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
-                                       FunctionTypeValues.end(), Ty);
-    if (I != FunctionTypeValues.end()) {
-      Slot = FirstDerivedTyID+ModuleTypeValues.size()+
+static inline void ALIGN32(const unsigned char *&begin,
+                           const unsigned char *end) {
+  if (align32(begin, end))
+    throw std::string("Alignment error in buffer: read past end of block.");
+}
+
+unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
+  if (Ty->isPrimitiveType())
+    return Ty->getPrimitiveID();
+
+  // Check the function level types first...
+  TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
+                                      FunctionTypeValues.end(), Ty);
+  if (I != FunctionTypeValues.end())
+    return FirstDerivedTyID + ModuleTypeValues.size() +
              (&*I - &FunctionTypeValues[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 << "\n";
-  return false;
+
+  I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
+  if (I == ModuleTypeValues.end())
+    throw std::string("Didn't find type in ModuleTypeValues.");
+  return FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
 }
 
 const Type *BytecodeParser::getType(unsigned ID) {
-  if (ID < Type::NumPrimitiveIDs) {
-    const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
-    if (T) return T;
-  }
+  if (ID < Type::NumPrimitiveIDs)
+    if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
+      return T;
   
   //cerr << "Looking up Type ID: " << ID << "\n";
-  const Value *V = getValue(Type::TypeTy, ID, false);
-  return cast_or_null<Type>(V);
+
+  if (ID < Type::NumPrimitiveIDs)
+    if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
+      return T;   // Asked for a primitive type...
+
+  // Otherwise, derived types need offset...
+  ID -= FirstDerivedTyID;
+
+  // Is it a module-level type?
+  if (ID < ModuleTypeValues.size())
+    return ModuleTypeValues[ID].get();
+
+  // Nope, is it a function-level type?
+  ID -= ModuleTypeValues.size();
+  if (ID < FunctionTypeValues.size())
+    return FunctionTypeValues[ID].get();
+
+  throw std::string("Illegal type reference!");
 }
 
-int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
+unsigned BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
   assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
           Val->getType()->isPrimitiveType() ||
           !cast<Constant>(Val)->isNullValue()) &&
          "Cannot read null values from bytecode!");
-  unsigned type;
-  if (getTypeSlot(Val->getType(), type)) return -1;
+  unsigned type = getTypeSlot(Val->getType());
   assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
  
   if (ValueTab.size() <= type) {
@@ -72,60 +90,28 @@ int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
   }
 
   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
-  //     << "] = " << Val << "\n";
+  //   << "] = " << Val << "\n";
   ValueTab[type]->push_back(Val);
 
   bool HasOffset = HasImplicitZeroInitializer &&
-                       !Val->getType()->isPrimitiveType();
+    !Val->getType()->isPrimitiveType();
 
   return ValueTab[type]->size()-1 + HasOffset;
 }
 
 
-void BytecodeParser::setValueTo(ValueTable &ValueTab, unsigned Slot,
-                                Value *Val) {
-  assert(&ValueTab == &ModuleValues && "Can only setValueTo on Module values!");
-  unsigned type;
-  if (getTypeSlot(Val->getType(), type))
-    assert(0 && "getTypeSlot failed!");
-  
-  assert((!HasImplicitZeroInitializer || Slot != 0) &&
-         "Cannot change zero init");
-  assert(type < ValueTab.size() && Slot <= ValueTab[type]->size());
-  ValueTab[type]->setOperand(Slot-HasImplicitZeroInitializer, Val);
+Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
+  return getValue(getTypeSlot(Ty), oNum, Create);
 }
 
-Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
+Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
+  assert(type != Type::TypeTyID && "getValue() cannot get types!");
+  assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
   unsigned Num = oNum;
-  unsigned type;   // The type plane it lives in...
-
-  if (getTypeSlot(Ty, type)) return 0;
-
-  if (type == Type::TypeTyID) {  // The 'type' plane has implicit values
-    assert(Create == false);
-    if (Num < Type::NumPrimitiveIDs) {
-      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 function level type?
-    Num -= ModuleTypeValues.size();
-    if (Num < FunctionTypeValues.size())
-      return (Value*)FunctionTypeValues[Num].get();
-
-    return 0;
-  }
 
   if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
     if (Num == 0)
-      return Constant::getNullValue(Ty);
+      return Constant::getNullValue(getType(type));
     --Num;
   }
 
@@ -140,19 +126,34 @@ Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
 
   if (!Create) return 0;  // Do not create a placeholder?
 
-  Value *d = 0;
-  switch (Ty->getPrimitiveID()) {
-  case Type::LabelTyID:
-    d = new BBPHolder(Ty, oNum);
-    break;
-  default:
-    d = new ValPHolder(Ty, oNum);
-    break;
-  }
+  std::pair<unsigned,unsigned> KeyValue(type, oNum);
+  std::map<std::pair<unsigned,unsigned>, Value*>::iterator I = 
+    ForwardReferences.lower_bound(KeyValue);
+  if (I != ForwardReferences.end() && I->first == KeyValue)
+    return I->second;   // We have already created this placeholder
 
-  assert(d != 0 && "How did we not make something?");
-  if (insertValue(d, LateResolveValues) == -1) return 0;
-  return d;
+  Value *Val = new Argument(getType(type));
+  ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
+  return Val;
+}
+
+/// getBasicBlock - Get a particular numbered basic block, which might be a
+/// forward reference.  This works together with ParseBasicBlock to handle these
+/// forward references in a clean manner.
+///
+BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
+  // Make sure there is room in the table...
+  if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
+
+  // First check to see if this is a backwards reference, i.e., ParseBasicBlock
+  // has already created this block, or if the forward reference has already
+  // been created.
+  if (ParsedBasicBlocks[ID])
+    return ParsedBasicBlocks[ID];
+
+  // Otherwise, the basic block has not yet been created.  Do so and add it to
+  // the ParsedBasicBlocks list.
+  return ParsedBasicBlocks[ID] = new BasicBlock();
 }
 
 /// getConstantValue - Just like getValue, except that it returns a null pointer
@@ -184,94 +185,69 @@ Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
 }
 
 
-bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
-  bool Error = false;
-  while (!ValTab.empty()) {
-    ValueList &DL = *ValTab.back();
-    ValTab.pop_back();    
-
-    while (!DL.empty()) {
-      Value *D = DL.back();
-      unsigned IDNumber = getValueIDNumberFromPlaceHolder(D);
-      DL.pop_back();
-
-      Value *NewDef = getValue(D->getType(), IDNumber, false);
-      if (NewDef == 0) {
-       Error = true;  // Unresolved thinger
-       std::cerr << "Unresolvable reference found: <"
-                  << *D->getType() << ">:" << IDNumber <<"!\n";
-      } else {
-       // Fixup all of the uses of this placeholder def...
-        D->replaceAllUsesWith(NewDef);
-
-        // Now that all the uses are gone, delete the placeholder...
-        // If we couldn't find a def (error case), then leak a little
-       delete D;  // memory, 'cause otherwise we can't remove all uses!
-      }
-    }
-    delete &DL;
-  }
-
-  return Error;
-}
-
-bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf, 
-                                    BasicBlock *&BB) {
-  BB = new BasicBlock();
+BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
+                                            const unsigned char *EndBuf,
+                                            unsigned BlockNo) {
+  BasicBlock *BB;
+  if (ParsedBasicBlocks.size() == BlockNo)
+    ParsedBasicBlocks.push_back(BB = new BasicBlock());
+  else if (ParsedBasicBlocks[BlockNo] == 0)
+    BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
+  else
+    BB = ParsedBasicBlocks[BlockNo];
 
   while (Buf < EndBuf) {
-    Instruction *Inst;
-    if (ParseInstruction(Buf, EndBuf, Inst, /*HACK*/BB)) {
-      delete BB;
-      return true;
-    }
-
-    if (Inst == 0) { delete BB; return true; }
-    if (insertValue(Inst, Values) == -1) { delete BB; return true; }
-
+    Instruction *Inst = ParseInstruction(Buf, EndBuf);
+    insertValue(Inst, Values);
     BB->getInstList().push_back(Inst);
-
     BCR_TRACE(4, Inst);
   }
 
-  return false;
+  return BB;
 }
 
-bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
-                                     SymbolTable *ST) {
+void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
+                                      const unsigned char *EndBuf,
+                                      SymbolTable *ST,
+                                      Function *CurrentFunction) {
   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)) throw Error_readvbr;
     const Type *Ty = getType(Typ);
-    if (Ty == 0) return true;
-
-    BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
-             " entries\n");
+    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;
+      if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
       std::string Name;
       if (read(Buf, EndBuf, Name, false))  // Not aligned...
-       return true;
-
-      Value *V = getValue(Ty, slot, false); // Find mapping...
-      if (V == 0) {
-       BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << "\n");
-       return true;
-      }
+        throw std::string("Buffer not aligned.");
+
+      Value *V = 0;
+      if (Typ == Type::TypeTyID)
+        V = (Value*)getType(slot);
+      else if (Typ == Type::LabelTyID) {
+        if (CurrentFunction) {
+          // FIXME: THIS IS N^2!!!
+          Function::iterator BlockIterator = CurrentFunction->begin();
+          std::advance(BlockIterator, slot);
+          V = BlockIterator;
+        }
+      } else
+        V = getValue(Typ, slot, false); // Find mapping...
+      if (V == 0) throw std::string("Failed value look-up.");
       BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
-               if (!isa<Instruction>(V)) std::cerr << "\n");
+                if (!isa<Instruction>(V)) std::cerr << "\n");
 
       V->setName(Name, ST);
     }
   }
 
-  if (Buf > EndBuf) return true;
-  return false;
+  if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
 }
 
 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
@@ -293,138 +269,192 @@ void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
   GlobalRefs.erase(I);                // Remove the map entry for it
 }
 
-
-bool BytecodeParser::ParseFunction(const uchar *&Buf, const uchar *EndBuf) {
-  // Clear out the local values table...
-  if (FunctionSignatureList.empty()) {
-    Error = "Function found, but FunctionSignatureList empty!";
-    return true;  // Unexpected function!
-  }
-
-  unsigned isInternal;
-  if (read_vbr(Buf, EndBuf, isInternal)) return true;
+void BytecodeParser::ParseFunction(const unsigned char *&Buf,
+                                   const unsigned char *EndBuf) {
+  if (FunctionSignatureList.empty())
+    throw std::string("FunctionSignatureList empty!");
 
   Function *F = FunctionSignatureList.back().first;
   unsigned FunctionSlot = FunctionSignatureList.back().second;
   FunctionSignatureList.pop_back();
-  F->setInternalLinkage(isInternal != 0);
+
+  // Save the information for future reading of the function
+  LazyFunctionInfo *LFI = new LazyFunctionInfo();
+  LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
+  LazyFunctionLoadMap[F] = LFI;
+  // Pretend we've `parsed' this function
+  Buf = EndBuf;
+}
+
+void BytecodeParser::materializeFunction(Function* F) {
+  // Find {start, end} pointers and slot in the map. If not there, we're done.
+  std::map<Function*, LazyFunctionInfo*>::iterator Fi =
+    LazyFunctionLoadMap.find(F);
+  if (Fi == LazyFunctionLoadMap.end()) return;
+  
+  LazyFunctionInfo *LFI = Fi->second;
+  const unsigned char *Buf = LFI->Buf;
+  const unsigned char *EndBuf = LFI->EndBuf;
+  unsigned FunctionSlot = LFI->FunctionSlot;
+  LazyFunctionLoadMap.erase(Fi);
+  delete LFI;
+
+  GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
+
+  if (!hasInternalMarkerOnly) {
+    unsigned LinkageType;
+    if (read_vbr(Buf, EndBuf, LinkageType)) 
+      throw std::string("ParseFunction: Error reading from buffer.");
+    if (LinkageType & ~0x3) 
+      throw std::string("Invalid linkage type for Function.");
+    Linkage = (GlobalValue::LinkageTypes)LinkageType;
+  } else {
+    // We used to only support two linkage models: internal and external
+    unsigned isInternal;
+    if (read_vbr(Buf, EndBuf, isInternal)) 
+      throw std::string("ParseFunction: Error reading from buffer.");
+    if (isInternal) Linkage = GlobalValue::InternalLinkage;
+  }
+
+  F->setLinkage(Linkage);
 
   const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
   Function::aiterator AI = F->abegin();
   for (FunctionType::ParamTypes::const_iterator It = Params.begin();
-       It != Params.end(); ++It, ++AI) {
-    if (insertValue(AI, Values) == -1) {
-      Error = "Error reading function arguments!\n";
-      return true; 
-    }
-  }
+       It != Params.end(); ++It, ++AI)
+    insertValue(AI, Values);
+
+  // Keep track of how many basic blocks we have read in...
+  unsigned BlockNum = 0;
 
   while (Buf < EndBuf) {
     unsigned Type, Size;
     const unsigned char *OldBuf = Buf;
-    if (readBlock(Buf, EndBuf, Type, Size)) {
-      Error = "Error reading Function level block!";
-      return true; 
-    }
+    readBlock(Buf, EndBuf, Type, Size);
 
     switch (Type) {
-    case BytecodeFormat::ConstantPool:
+    case BytecodeFormat::ConstantPool: {
       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
-      if (ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues))
-       return true;
+      ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
       break;
+    }
 
     case BytecodeFormat::BasicBlock: {
       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
-      BasicBlock *BB;
-      if (ParseBasicBlock(Buf, Buf+Size, BB) ||
-         insertValue(BB, Values) == -1)
-       return true;                // Parse error... :(
-
+      BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
       F->getBasicBlockList().push_back(BB);
       break;
     }
 
-    case BytecodeFormat::SymbolTable:
+    case BytecodeFormat::SymbolTable: {
       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
-      if (ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable()))
-       return true;
+      ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
       break;
+    }
 
     default:
       BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
       Buf += Size;
-      if (OldBuf > Buf) return true; // Wrap around!
+      if (OldBuf > Buf) 
+        throw std::string("Wrapped around reading bytecode.");
       break;
     }
     BCR_TRACE(2, "} end block\n");
 
-    if (align32(Buf, EndBuf)) {
-      Error = "Error aligning Function level block!";
-      return true;   // Malformed bc file, read past end of block.
-    }
+    // Malformed bc file if read past end of block.
+    ALIGN32(Buf, EndBuf);
   }
 
-  if (postResolveValues(LateResolveValues)) {
-    Error = "Error resolving function values!";
-    return true;     // Unresolvable references!
+  // Make sure there were no references to non-existant basic blocks.
+  if (BlockNum != ParsedBasicBlocks.size())
+    throw std::string("Illegal basic block operand reference");
+  ParsedBasicBlocks.clear();
+
+
+  // Resolve forward references
+  while (!ForwardReferences.empty()) {
+    std::map<std::pair<unsigned,unsigned>, Value*>::iterator I = ForwardReferences.begin();
+    unsigned type = I->first.first;
+    unsigned Slot = I->first.second;
+    Value *PlaceHolder = I->second;
+    ForwardReferences.erase(I);
+
+    Value *NewVal = getValue(type, Slot, false);
+    if (NewVal == 0)
+      throw std::string("Unresolvable reference found: <" +
+                        PlaceHolder->getType()->getDescription() + ">:" + 
+                        utostr(Slot) + ".");
+
+    // Fixup all of the uses of this placeholder def...
+    PlaceHolder->replaceAllUsesWith(NewVal);
+      
+    // Now that all the uses are gone, delete the placeholder...
+    // If we couldn't find a def (error case), then leak a little
+    // memory, because otherwise we can't remove all uses!
+    delete PlaceHolder;
   }
 
-  ResolveReferencesToValue(F, FunctionSlot);
-
-  // Clear out function level types...
+  // Clear out function-level types...
   FunctionTypeValues.clear();
 
   freeTable(Values);
-  return false;
 }
 
-bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End){
-  if (!FunctionSignatureList.empty()) {
-    Error = "Two ModuleGlobalInfo packets found!";
-    return true;  // Two ModuleGlobal blocks?
-  }
+void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
+                                           const unsigned char *End) {
+  if (!FunctionSignatureList.empty())
+    throw std::string("Two ModuleGlobalInfo packets found!");
 
   // Read global variables...
   unsigned VarType;
-  if (read_vbr(Buf, End, VarType)) return true;
+  if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
   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 || !isa<PointerType>(Ty)) { 
-      Error = "Global not pointer type!  Ty = " + Ty->getDescription();
-      return true; 
+    unsigned SlotNo;
+    GlobalValue::LinkageTypes Linkage;
+
+    if (!hasInternalMarkerOnly) {
+      // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
+      // bit2,3 = Linkage, bit4+ = slot#
+      SlotNo = VarType >> 4;
+      Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
+    } else {
+      // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
+      // bit2 = isInternal, bit3+ = slot#
+      SlotNo = VarType >> 3;
+      Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
+        GlobalValue::ExternalLinkage;
     }
 
+    const Type *Ty = getType(SlotNo);
+    if (!isa<PointerType>(Ty))
+      throw std::string("Global not pointer type!  Ty = " + 
+                        Ty->getDescription());
+
     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
 
     // Create the global variable...
-    GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, VarType & 4,
+    GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
                                             0, "", TheModule);
-    int DestSlot = insertValue(GV, ModuleValues);
-    if (DestSlot == -1) return true;
     BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
-    ResolveReferencesToValue(GV, (unsigned)DestSlot);
+    ResolveReferencesToValue(GV, insertValue(GV, ModuleValues));
 
-    if (VarType & 2) { // Does it have an initalizer?
+    if (VarType & 2) { // Does it have an initializer?
       unsigned InitSlot;
-      if (read_vbr(Buf, End, InitSlot)) return true;
+      if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
       GlobalInits.push_back(std::make_pair(GV, InitSlot));
     }
-    if (read_vbr(Buf, End, VarType)) return true;
+    if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
   }
 
   // Read the function objects for all of the functions that are coming
   unsigned FnSignature;
-  if (read_vbr(Buf, End, FnSignature)) return true;
+  if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
     const Type *Ty = getType(FnSignature);
-    if (!Ty || !isa<PointerType>(Ty) ||
-        !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) { 
-      Error = "Function not ptr to func type!  Ty = " + Ty->getDescription();
-      return true; 
-    }
+    if (!isa<PointerType>(Ty) ||
+        !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
+      throw std::string("Function not ptr to func type!  Ty = " +
+                        Ty->getDescription());
 
     // We create functions by passing the underlying FunctionType to create...
     Ty = cast<PointerType>(Ty)->getElementType();
@@ -435,21 +465,21 @@ bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End){
     // this placeholder is replaced.
 
     // Insert the placeholder...
-    Function *Func = new Function(cast<FunctionType>(Ty), false, "", TheModule);
-    int DestSlot = insertValue(Func, ModuleValues);
-    if (DestSlot == -1) return true;
-    ResolveReferencesToValue(Func, (unsigned)DestSlot);
+    Function *Func = new Function(cast<FunctionType>(Ty),
+                                  GlobalValue::InternalLinkage, "", TheModule);
+    unsigned DestSlot = insertValue(Func, ModuleValues);
+    ResolveReferencesToValue(Func, DestSlot);
 
     // Keep track of this information in a list that is emptied as functions are
     // loaded...
     //
     FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
 
-    if (read_vbr(Buf, End, FnSignature)) return true;
+    if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
     BCR_TRACE(2, "Function of type: " << Ty << "\n");
   }
 
-  if (align32(Buf, End)) return true;
+  ALIGN32(Buf, End);
 
   // Now that the function signature list is set up, reverse it so that we can 
   // remove elements efficiently from the back of the vector.
@@ -459,18 +489,28 @@ bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End){
   // we don't understand, so we transparently ignore them.
   //
   Buf = End;
-  return false;
 }
 
-bool BytecodeParser::ParseVersionInfo(const uchar *&Buf, const uchar *EndBuf) {
+void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
+                                      const unsigned char *EndBuf) {
   unsigned Version;
-  if (read_vbr(Buf, EndBuf, Version)) return true;
+  if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
 
   // Unpack version number: low four bits are for flags, top bits = version
-  isBigEndian     = Version & 1;
-  hasLongPointers = Version & 2;
-  RevisionNum     = Version >> 4;
+  Module::Endianness  Endianness;
+  Module::PointerSize PointerSize;
+  Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
+  PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
+
+  bool hasNoEndianness = Version & 4;
+  bool hasNoPointerSize = Version & 8;
+  
+  RevisionNum = Version >> 4;
+
+  // Default values for the current bytecode version
   HasImplicitZeroInitializer = true;
+  hasInternalMarkerOnly = false;
+  FirstDerivedTyID = 14;
 
   switch (RevisionNum) {
   case 0:                  // Initial revision
@@ -478,83 +518,90 @@ bool BytecodeParser::ParseVersionInfo(const uchar *&Buf, const uchar *EndBuf) {
     // only valid with a 14 in the flags values.  Also, it does not support
     // encoding zero initializers for arrays compactly.
     //
-    if (Version != 14) return true;  // Unknown revision 0 flags?
-    FirstDerivedTyID = 14;
+    if (Version != 14) throw std::string("Unknown revision 0 flags?");
     HasImplicitZeroInitializer = false;
-    isBigEndian = hasLongPointers = true;
+    Endianness  = Module::BigEndian;
+    PointerSize = Module::Pointer64;
+    hasInternalMarkerOnly = true;
+    hasNoEndianness = hasNoPointerSize = false;
     break;
   case 1:
-    // Version #1 has two bit fields: isBigEndian and hasLongPointers
-    FirstDerivedTyID = 14;
+    // Version #1 has four bit fields: isBigEndian, hasLongPointers,
+    // hasNoEndianness, and hasNoPointerSize.
+    hasInternalMarkerOnly = true;
+    break;
+  case 2:
+    // Version #2 added information about all 4 linkage types instead of just
+    // having internal and external.
     break;
   default:
-    Error = "Unknown bytecode version number!";
-    return true;
+    throw std::string("Unknown bytecode version number!");
   }
 
+  if (hasNoEndianness) Endianness  = Module::AnyEndianness;
+  if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
+
+  TheModule->setEndianness(Endianness);
+  TheModule->setPointerSize(PointerSize);
   BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
-  BCR_TRACE(1, "BigEndian/LongPointers = " << isBigEndian << ","
-               << hasLongPointers << "\n");
+  BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
+               << PointerSize << "\n");
   BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
-  return false;
 }
 
-bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf) {
+void BytecodeParser::ParseModule(const unsigned char *Buf,
+                                 const unsigned char *EndBuf) {
   unsigned Type, Size;
-  if (readBlock(Buf, EndBuf, Type, Size)) return true;
-  if (Type != BytecodeFormat::Module || Buf+Size != EndBuf) {
-    Error = "Expected Module packet!";
-    return true;                      // Hrm, not a class?
-  }
+  readBlock(Buf, EndBuf, Type, Size);
+  if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
+    throw std::string("Expected Module packet! B: "+
+        utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
+        " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
 
   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
   FunctionSignatureList.clear();                 // Just in case...
 
   // Read into instance variables...
-  if (ParseVersionInfo(Buf, EndBuf)) return true;
-  if (align32(Buf, EndBuf)) return true;
+  ParseVersionInfo(Buf, EndBuf);
+  ALIGN32(Buf, EndBuf);
 
   while (Buf < EndBuf) {
     const unsigned char *OldBuf = Buf;
-    if (readBlock(Buf, EndBuf, Type, Size)) return true;
+    readBlock(Buf, EndBuf, Type, Size);
     switch (Type) {
     case BytecodeFormat::GlobalTypePlane:
       BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
-      if (ParseGlobalTypes(Buf, Buf+Size)) return true;
+      ParseGlobalTypes(Buf, Buf+Size);
       break;
 
     case BytecodeFormat::ModuleGlobalInfo:
       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
-      if (ParseModuleGlobalInfo(Buf, Buf+Size)) return true;
+      ParseModuleGlobalInfo(Buf, Buf+Size);
       break;
 
     case BytecodeFormat::ConstantPool:
       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
-      if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues))
-       return true;
+      ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
       break;
 
     case BytecodeFormat::Function: {
       BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
-      if (ParseFunction(Buf, Buf+Size))
-        return true;  // Error parsing function
+      ParseFunction(Buf, Buf+Size);
       break;
     }
 
     case BytecodeFormat::SymbolTable:
       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
-      if (ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable()))
-        return true;
+      ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
       break;
 
     default:
-      Error = "Expected Module Block!";
       Buf += Size;
-      if (OldBuf > Buf) return true; // Wrap around!
+      if (OldBuf > Buf) throw std::string("Expected Module Block!");
       break;
     }
     BCR_TRACE(1, "} end block\n");
-    if (align32(Buf, EndBuf)) return true;
+    ALIGN32(Buf, EndBuf);
   }
 
   // After the module constant pool has been read, we can safely initialize
@@ -566,122 +613,38 @@ bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf) {
 
     // Look up the initializer value...
     if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
-      if (GV->hasInitializer()) return true;
+      if (GV->hasInitializer()) 
+        throw std::string("Global *already* has an initializer?!");
       GV->setInitializer(cast<Constant>(V));
     } else
-      return true;
+      throw std::string("Cannot find initializer value.");
   }
 
-  if (!FunctionSignatureList.empty()) {     // Expected more functions!
-    Error = "Function expected, but bytecode stream at end!";
-    return true;
-  }
+  if (!FunctionSignatureList.empty())
+    throw std::string("Function expected, but bytecode stream ended!");
 
   BCR_TRACE(0, "} end block\n\n");
-  return false;
 }
 
-static inline Module *Error(std::string *ErrorStr, const char *Message) {
-  if (ErrorStr) *ErrorStr = Message;
-  return 0;
-}
+void
+BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
+                              const std::string &ModuleID) {
+
+  unsigned char *EndBuf = (unsigned char*)(Buf + Length);
 
-Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
-  unsigned Sig;
   // Read and check signature...
+  unsigned Sig;
   if (read(Buf, EndBuf, Sig) ||
-      Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
-    return ::Error(&Error, "Invalid bytecode signature!");
-
-  TheModule = new Module();
-  if (ParseModule(Buf, EndBuf)) {
+      Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
+    throw std::string("Invalid bytecode signature!");
+
+  TheModule = new Module(ModuleID);
+  try { 
+    ParseModule(Buf, EndBuf);
+  } catch (std::string &Error) {
+    freeState();       // Must destroy handles before deleting module!
     delete TheModule;
     TheModule = 0;
+    throw;
   }
-  return TheModule;
-}
-
-
-Module *ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
-                            std::string *ErrorStr) {
-  BytecodeParser Parser;
-  Module *R = Parser.ParseBytecode(Buffer, Buffer+Length);
-  if (ErrorStr) *ErrorStr = Parser.getError();
-  return R;
-}
-
-
-/// FDHandle - Simple handle class to make sure a file descriptor gets closed
-/// when the object is destroyed.
-class FDHandle {
-  int FD;
-public:
-  FDHandle(int fd) : FD(fd) {}
-  operator int() const { return FD; }
-  ~FDHandle() {
-    if (FD != -1) close(FD);
-  }
-};
-
-// Parse and return a class file...
-//
-Module *ParseBytecodeFile(const std::string &Filename, std::string *ErrorStr) {
-  Module *Result = 0;
-
-  if (Filename != std::string("-")) {        // Read from a file...
-    FDHandle FD = open(Filename.c_str(), O_RDONLY);
-    if (FD == -1)
-      return Error(ErrorStr, "Error opening file!");
-
-    // Stat the file to get its length...
-    struct stat StatBuf;
-    if (fstat(FD, &StatBuf) == -1 || StatBuf.st_size == 0)
-      return Error(ErrorStr, "Error stat'ing file!");
-
-    // mmap in the file all at once...
-    int Length = StatBuf.st_size;
-    unsigned char *Buffer = (unsigned char*)mmap(0, Length, PROT_READ, 
-                                                 MAP_PRIVATE, FD, 0);
-    if (Buffer == (unsigned char*)MAP_FAILED)
-      return Error(ErrorStr, "Error mmapping file!");
-
-    // Parse the bytecode we mmapped in
-    Result = ParseBytecodeBuffer(Buffer, Length, ErrorStr);
-
-    // Unmmap the bytecode...
-    munmap((char*)Buffer, Length);
-  } else {                              // Read from stdin
-    int BlockSize;
-    uchar Buffer[4096*4];
-    std::vector<unsigned char> FileData;
-
-    // Read in all of the data from stdin, we cannot mmap stdin...
-    while ((BlockSize = read(0 /*stdin*/, Buffer, 4096*4))) {
-      if (BlockSize == -1)
-        return Error(ErrorStr, "Error reading from stdin!");
-
-      FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
-    }
-
-    if (FileData.empty())
-      return Error(ErrorStr, "Standard Input empty!");
-
-#define ALIGN_PTRS 0
-#if ALIGN_PTRS
-    uchar *Buf = (uchar*)mmap(0, FileData.size(), PROT_READ|PROT_WRITE, 
-                             MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
-    assert((Buf != (uchar*)-1) && "mmap returned error!");
-    memcpy(Buf, &FileData[0], FileData.size());
-#else
-    unsigned char *Buf = &FileData[0];
-#endif
-
-    Result = ParseBytecodeBuffer(Buf, FileData.size(), ErrorStr);
-
-#if ALIGN_PTRS
-    munmap((char*)Buf, FileData.size());   // Free mmap'd data area
-#endif
-  }
-
-  return Result;
 }