Move the metadata constructors back to 2.5 syntax.
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
index 299ce0b94a4a03a3e5de73515baed97bf5bd5610..81fdbd29afb95ed9efc046dc137b32a9488e6339 100644 (file)
 #include "llvm/DerivedTypes.h"
 #include "llvm/InlineAsm.h"
 #include "llvm/Instructions.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Metadata.h"
 #include "llvm/Module.h"
+#include "llvm/Operator.h"
 #include "llvm/AutoUpgrade.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -58,18 +61,20 @@ static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
   switch (Val) {
   default: // Map unknown/new linkages to external
-  case 0: return GlobalValue::ExternalLinkage;
-  case 1: return GlobalValue::WeakAnyLinkage;
-  case 2: return GlobalValue::AppendingLinkage;
-  case 3: return GlobalValue::InternalLinkage;
-  case 4: return GlobalValue::LinkOnceAnyLinkage;
-  case 5: return GlobalValue::DLLImportLinkage;
-  case 6: return GlobalValue::DLLExportLinkage;
-  case 7: return GlobalValue::ExternalWeakLinkage;
-  case 8: return GlobalValue::CommonLinkage;
-  case 9: return GlobalValue::PrivateLinkage;
+  case 0:  return GlobalValue::ExternalLinkage;
+  case 1:  return GlobalValue::WeakAnyLinkage;
+  case 2:  return GlobalValue::AppendingLinkage;
+  case 3:  return GlobalValue::InternalLinkage;
+  case 4:  return GlobalValue::LinkOnceAnyLinkage;
+  case 5:  return GlobalValue::DLLImportLinkage;
+  case 6:  return GlobalValue::DLLExportLinkage;
+  case 7:  return GlobalValue::ExternalWeakLinkage;
+  case 8:  return GlobalValue::CommonLinkage;
+  case 9:  return GlobalValue::PrivateLinkage;
   case 10: return GlobalValue::WeakODRLinkage;
   case 11: return GlobalValue::LinkOnceODRLinkage;
+  case 12: return GlobalValue::AvailableExternallyLinkage;
+  case 13: return GlobalValue::LinkerPrivateLinkage;
   }
 }
 
@@ -102,9 +107,12 @@ static int GetDecodedCastOpcode(unsigned Val) {
 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
   switch (Val) {
   default: return -1;
-  case bitc::BINOP_ADD:  return Instruction::Add;
-  case bitc::BINOP_SUB:  return Instruction::Sub;
-  case bitc::BINOP_MUL:  return Instruction::Mul;
+  case bitc::BINOP_ADD:
+    return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
+  case bitc::BINOP_SUB:
+    return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
+  case bitc::BINOP_MUL:
+    return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
   case bitc::BINOP_UDIV: return Instruction::UDiv;
   case bitc::BINOP_SDIV:
     return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
@@ -132,7 +140,7 @@ namespace {
     void *operator new(size_t s) {
       return User::operator new(s, 1);
     }
-    explicit ConstantPlaceHolder(const Type *Ty)
+    explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
       Op<0>() = UndefValue::get(Type::Int32Ty);
     }
@@ -146,64 +154,67 @@ namespace {
     
     
     /// Provide fast operand accessors
-    DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+    //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
   };
 }
 
-
-  // FIXME: can we inherit this from ConstantExpr?
+// FIXME: can we inherit this from ConstantExpr?
 template <>
 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
 };
-
-DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
 }
 
-void BitcodeReaderValueList::resize(unsigned Desired) {
-  if (Desired > Capacity) {
-    // Since we expect many values to come from the bitcode file we better
-    // allocate the double amount, so that the array size grows exponentially
-    // at each reallocation.  Also, add a small amount of 100 extra elements
-    // each time, to reallocate less frequently when the array is still small.
-    //
-    Capacity = Desired * 2 + 100;
-    Use *New = allocHungoffUses(Capacity);
-    Use *Old = OperandList;
-    unsigned Ops = getNumOperands();
-    for (int i(Ops - 1); i >= 0; --i)
-      New[i] = Old[i].get();
-    OperandList = New;
-    if (Old) Use::zap(Old, Old + Ops, true);
+
+void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
+  if (Idx == size()) {
+    push_back(V);
+    return;
+  }
+  
+  if (Idx >= size())
+    resize(Idx+1);
+  
+  WeakVH &OldV = ValuePtrs[Idx];
+  if (OldV == 0) {
+    OldV = V;
+    return;
+  }
+  
+  // Handle constants and non-constants (e.g. instrs) differently for
+  // efficiency.
+  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
+    ResolveConstants.push_back(std::make_pair(PHC, Idx));
+    OldV = V;
+  } else {
+    // If there was a forward reference to this value, replace it.
+    Value *PrevVal = OldV;
+    OldV->replaceAllUsesWith(V);
+    delete PrevVal;
   }
 }
+  
 
 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
                                                     const Type *Ty) {
-  if (Idx >= size()) {
-    // Insert a bunch of null values.
+  if (Idx >= size())
     resize(Idx + 1);
-    NumOperands = Idx+1;
-  }
 
-  if (Value *V = OperandList[Idx]) {
+  if (Value *V = ValuePtrs[Idx]) {
     assert(Ty == V->getType() && "Type mismatch in constant table!");
     return cast<Constant>(V);
   }
 
   // Create and return a placeholder, which will later be RAUW'd.
-  Constant *C = new ConstantPlaceHolder(Ty);
-  OperandList[Idx] = C;
+  Constant *C = new ConstantPlaceHolder(Ty, Context);
+  ValuePtrs[Idx] = C;
   return C;
 }
 
 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
-  if (Idx >= size()) {
-    // Insert a bunch of null values.
+  if (Idx >= size())
     resize(Idx + 1);
-    NumOperands = Idx+1;
-  }
   
-  if (Value *V = OperandList[Idx]) {
+  if (Value *V = ValuePtrs[Idx]) {
     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
     return V;
   }
@@ -213,7 +224,7 @@ Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
   
   // Create and return a placeholder, which will later be RAUW'd.
   Value *V = new Argument(Ty);
-  OperandList[Idx] = V;
+  ValuePtrs[Idx] = V;
   return V;
 }
 
@@ -232,7 +243,7 @@ void BitcodeReaderValueList::ResolveConstantForwardRefs() {
   SmallVector<Constant*, 64> NewOps;
   
   while (!ResolveConstants.empty()) {
-    Value *RealVal = getOperand(ResolveConstants.back().second);
+    Value *RealVal = operator[](ResolveConstants.back().second);
     Constant *Placeholder = ResolveConstants.back().first;
     ResolveConstants.pop_back();
     
@@ -268,7 +279,7 @@ void BitcodeReaderValueList::ResolveConstantForwardRefs() {
                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
                                                             0));
           assert(It != ResolveConstants.end() && It->first == *I);
-          NewOp = this->getOperand(It->second);
+          NewOp = operator[](It->second);
         }
 
         NewOps.push_back(cast<Constant>(NewOp));
@@ -277,14 +288,15 @@ void BitcodeReaderValueList::ResolveConstantForwardRefs() {
       // Make the new constant.
       Constant *NewC;
       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
-        NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
+        NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
+                                        NewOps.size());
       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
         NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
-                                   UserCS->getType()->isPacked());
+                                         UserCS->getType()->isPacked());
       } else if (isa<ConstantVector>(UserC)) {
         NewC = ConstantVector::get(&NewOps[0], NewOps.size());
       } else {
-        // Must be a constant expression.
+        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
         NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
                                                           NewOps.size());
       }
@@ -294,6 +306,8 @@ void BitcodeReaderValueList::ResolveConstantForwardRefs() {
       NewOps.clear();
     }
     
+    // Update all ValueHandles, they should be the only users at this point.
+    Placeholder->replaceAllUsesWith(RealVal);
     delete Placeholder;
   }
 }
@@ -491,6 +505,9 @@ bool BitcodeReader::ParseTypeTable() {
     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
       ResultTy = 0;
       break;
+    case bitc::TYPE_CODE_METADATA:  // METADATA
+      ResultTy = Type::MetadataTy;
+      break;
     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
       if (Record.size() < 1)
         return Error("Invalid Integer type record");
@@ -504,7 +521,8 @@ bool BitcodeReader::ParseTypeTable() {
       unsigned AddressSpace = 0;
       if (Record.size() == 2)
         AddressSpace = Record[1];
-      ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
+      ResultTy = PointerType::get(getTypeByID(Record[0], true),
+                                        AddressSpace);
       break;
     }
     case bitc::TYPE_CODE_FUNCTION: {
@@ -656,13 +674,13 @@ bool BitcodeReader::ParseValueSymbolTable() {
       break;
     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
       if (ConvertToString(Record, 1, ValueName))
-        return Error("Invalid TST_ENTRY record");
+        return Error("Invalid VST_ENTRY record");
       unsigned ValueID = Record[0];
       if (ValueID >= ValueList.size())
         return Error("Invalid Value ID in VST_ENTRY record");
       Value *V = ValueList[ValueID];
       
-      V->setName(&ValueName[0], ValueName.size());
+      V->setName(StringRef(ValueName.data(), ValueName.size()));
       ValueName.clear();
       break;
     }
@@ -673,7 +691,7 @@ bool BitcodeReader::ParseValueSymbolTable() {
       if (BB == 0)
         return Error("Invalid BB ID in VST_BBENTRY record");
       
-      BB->setName(&ValueName[0], ValueName.size());
+      BB->setName(StringRef(ValueName.data(), ValueName.size()));
       ValueName.clear();
       break;
     }
@@ -681,6 +699,100 @@ bool BitcodeReader::ParseValueSymbolTable() {
   }
 }
 
+bool BitcodeReader::ParseMetadata() {
+  unsigned NextValueNo = ValueList.size();
+
+  if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
+    return Error("Malformed block record");
+  
+  SmallVector<uint64_t, 64> Record;
+  
+  // Read all the records.
+  while (1) {
+    unsigned Code = Stream.ReadCode();
+    if (Code == bitc::END_BLOCK) {
+      if (Stream.ReadBlockEnd())
+        return Error("Error at end of PARAMATTR block");
+      return false;
+    }
+    
+    if (Code == bitc::ENTER_SUBBLOCK) {
+      // No known subblocks, always skip them.
+      Stream.ReadSubBlockID();
+      if (Stream.SkipBlock())
+        return Error("Malformed block record");
+      continue;
+    }
+    
+    if (Code == bitc::DEFINE_ABBREV) {
+      Stream.ReadAbbrevRecord();
+      continue;
+    }
+    
+    // Read a record.
+    Record.clear();
+    switch (Stream.ReadRecord(Code, Record)) {
+    default:  // Default behavior: ignore.
+      break;
+    case bitc::METADATA_NAME: {
+      // Read named of the named metadata.
+      unsigned NameLength = Record.size();
+      SmallString<8> Name;
+      Name.resize(NameLength);
+      for (unsigned i = 0; i != NameLength; ++i)
+        Name[i] = Record[i];
+      Record.clear();
+      Code = Stream.ReadCode();
+
+      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
+      if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
+        assert ( 0 && "Inavlid Named Metadata record");
+
+      // Read named metadata elements.
+      unsigned Size = Record.size();
+      SmallVector<MetadataBase*, 8> Elts;
+      for (unsigned i = 0; i != Size; ++i) {
+        Value *MD = ValueList.getValueFwdRef(Record[i], Type::MetadataTy);
+        if (MetadataBase *B = dyn_cast<MetadataBase>(MD))
+        Elts.push_back(B);
+      }
+      Value *V = NamedMDNode::Create(Name.c_str(), Elts.data(), Elts.size(), 
+                                     TheModule);
+      ValueList.AssignValue(V, NextValueNo++);
+      break;
+    }
+    case bitc::METADATA_NODE: {
+      if (Record.empty() || Record.size() % 2 == 1)
+        return Error("Invalid METADATA_NODE record");
+      
+      unsigned Size = Record.size();
+      SmallVector<Value*, 8> Elts;
+      for (unsigned i = 0; i != Size; i += 2) {
+        const Type *Ty = getTypeByID(Record[i], false);
+        if (Ty != Type::VoidTy)
+          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
+        else
+          Elts.push_back(NULL);
+      }
+      Value *V = MDNode::get(Context, &Elts[0], Elts.size());
+      ValueList.AssignValue(V, NextValueNo++);
+      break;
+    }
+    case bitc::METADATA_STRING: {
+      unsigned MDStringLength = Record.size();
+      SmallString<8> String;
+      String.resize(MDStringLength);
+      for (unsigned i = 0; i != MDStringLength; ++i)
+        String[i] = Record[i];
+      Value *V = MDString::get(Context, 
+                               StringRef(String.data(), String.size()));
+      ValueList.AssignValue(V, NextValueNo++);
+      break;
+    }
+    }
+  }
+}
+
 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
 /// the LSB for dense VBR encoding.
 static uint64_t DecodeSignRotatedValue(uint64_t V) {
@@ -730,6 +842,18 @@ bool BitcodeReader::ResolveGlobalAndAliasInits() {
   return false;
 }
 
+static void SetOptimizationFlags(Value *V, uint64_t Flags) {
+  if (OverflowingBinaryOperator *OBO =
+        dyn_cast<OverflowingBinaryOperator>(V)) {
+    if (Flags & (1 << bitc::OBO_NO_SIGNED_OVERFLOW))
+      OBO->setHasNoSignedOverflow(true);
+    if (Flags & (1 << bitc::OBO_NO_UNSIGNED_OVERFLOW))
+      OBO->setHasNoUnsignedOverflow(true);
+  } else if (SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
+    if (Flags & (1 << bitc::SDIV_EXACT))
+      Div->setIsExact(true);
+  }
+}
 
 bool BitcodeReader::ParseConstants() {
   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
@@ -761,7 +885,8 @@ bool BitcodeReader::ParseConstants() {
     // Read a record.
     Record.clear();
     Value *V = 0;
-    switch (Stream.ReadRecord(Code, Record)) {
+    unsigned BitCode = Stream.ReadRecord(Code, Record);
+    switch (BitCode) {
     default:  // Default behavior: unknown constant
     case bitc::CST_CODE_UNDEF:     // UNDEF
       V = UndefValue::get(CurTy);
@@ -790,23 +915,28 @@ bool BitcodeReader::ParseConstants() {
       Words.resize(NumWords);
       for (unsigned i = 0; i != NumWords; ++i)
         Words[i] = DecodeSignRotatedValue(Record[i]);
-      V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
-                                 NumWords, &Words[0]));
+      V = ConstantInt::get(Context, 
+                           APInt(cast<IntegerType>(CurTy)->getBitWidth(),
+                           NumWords, &Words[0]));
       break;
     }
     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
       if (Record.empty())
         return Error("Invalid FLOAT record");
       if (CurTy == Type::FloatTy)
-        V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
+        V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
       else if (CurTy == Type::DoubleTy)
-        V = ConstantFP::get(APFloat(APInt(64, Record[0])));
-      else if (CurTy == Type::X86_FP80Ty)
-        V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
-      else if (CurTy == Type::FP128Ty)
-        V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
+        V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
+      else if (CurTy == Type::X86_FP80Ty) {
+        // Bits are not stored the same way as a normal i80 APInt, compensate.
+        uint64_t Rearrange[2];
+        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
+        Rearrange[1] = Record[0] >> 48;
+        V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
+      } else if (CurTy == Type::FP128Ty)
+        V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
       else if (CurTy == Type::PPC_FP128Ty)
-        V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
+        V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
       else
         V = UndefValue::get(CurTy);
       break;
@@ -878,6 +1008,8 @@ bool BitcodeReader::ParseConstants() {
         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
         V = ConstantExpr::get(Opc, LHS, RHS);
       }
+      if (Record.size() >= 4)
+        SetOptimizationFlags(V, Record[3]);
       break;
     }  
     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
@@ -893,6 +1025,7 @@ bool BitcodeReader::ParseConstants() {
       }
       break;
     }  
+    case bitc::CST_CODE_CE_INBOUNDS_GEP:
     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
       if (Record.size() & 1) return Error("Invalid CE_GEP record");
       SmallVector<Constant*, 16> Elts;
@@ -901,7 +1034,10 @@ bool BitcodeReader::ParseConstants() {
         if (!ElTy) return Error("Invalid CE_GEP record");
         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
       }
-      V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
+      V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], 
+                                               Elts.size()-1);
+      if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
+        cast<GEPOperator>(V)->setIsInBounds(true);
       break;
     }
     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
@@ -938,7 +1074,8 @@ bool BitcodeReader::ParseConstants() {
         return Error("Invalid CE_SHUFFLEVEC record");
       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
-      const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
+      const Type *ShufTy = VectorType::get(Type::Int32Ty, 
+                                                 OpTy->getNumElements());
       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
       break;
@@ -950,7 +1087,8 @@ bool BitcodeReader::ParseConstants() {
         return Error("Invalid CE_SHUFVEC_EX record");
       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
-      const Type *ShufTy=VectorType::get(Type::Int32Ty, RTy->getNumElements());
+      const Type *ShufTy = VectorType::get(Type::Int32Ty, 
+                                                 RTy->getNumElements());
       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
       break;
@@ -964,12 +1102,8 @@ bool BitcodeReader::ParseConstants() {
 
       if (OpTy->isFloatingPoint())
         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
-      else if (!isa<VectorType>(OpTy))
-        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
-      else if (OpTy->isFPOrFPVector())
-        V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
       else
-        V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
+        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
       break;
     }
     case bitc::CST_CODE_INLINEASM: {
@@ -1044,7 +1178,7 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) {
     return Error("Malformed block record");
 
   // Otherwise, create the module.
-  TheModule = new Module(ModuleID);
+  TheModule = new Module(ModuleID, Context);
   
   SmallVector<uint64_t, 64> Record;
   std::vector<std::string> SectionTable;
@@ -1110,6 +1244,10 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) {
         if (ParseConstants() || ResolveGlobalAndAliasInits())
           return true;
         break;
+      case bitc::METADATA_BLOCK_ID:
+        if (ParseMetadata())
+          return true;
+        break;
       case bitc::FUNCTION_BLOCK_ID:
         // If this is the first function body we've seen, reverse the
         // FunctionsWithBodies list.
@@ -1210,7 +1348,7 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) {
         isThreadLocal = Record[7];
 
       GlobalVariable *NewGV =
-        new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule
+        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0
                            isThreadLocal, AddressSpace);
       NewGV->setAlignment(Alignment);
       if (!Section.empty())
@@ -1298,48 +1436,6 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) {
   return Error("Premature end of bitstream");
 }
 
-/// SkipWrapperHeader - Some systems wrap bc files with a special header for
-/// padding or other reasons.  The format of this header is:
-///
-/// struct bc_header {
-///   uint32_t Magic;         // 0x0B17C0DE
-///   uint32_t Version;       // Version, currently always 0.
-///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
-///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
-///   ... potentially other gunk ...
-/// };
-/// 
-/// This function is called when we find a file with a matching magic number.
-/// In this case, skip down to the subsection of the file that is actually a BC
-/// file.
-static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
-  enum {
-    KnownHeaderSize = 4*4,  // Size of header we read.
-    OffsetField = 2*4,      // Offset in bytes to Offset field.
-    SizeField = 3*4         // Offset in bytes to Size field.
-  };
-  
-  
-  // Must contain the header!
-  if (BufEnd-BufPtr < KnownHeaderSize) return true;
-  
-  unsigned Offset = ( BufPtr[OffsetField  ]        |
-                     (BufPtr[OffsetField+1] << 8)  |
-                     (BufPtr[OffsetField+2] << 16) |
-                     (BufPtr[OffsetField+3] << 24));
-  unsigned Size   = ( BufPtr[SizeField    ]        |
-                     (BufPtr[SizeField  +1] << 8)  |
-                     (BufPtr[SizeField  +2] << 16) |
-                     (BufPtr[SizeField  +3] << 24));
-  
-  // Verify that Offset+Size fits in the file.
-  if (Offset+Size > unsigned(BufEnd-BufPtr))
-    return true;
-  BufPtr += Offset;
-  BufEnd = BufPtr+Size;
-  return false;
-}
-
 bool BitcodeReader::ParseBitcode() {
   TheModule = 0;
   
@@ -1351,12 +1447,12 @@ bool BitcodeReader::ParseBitcode() {
   
   // If we have a wrapper header, parse it and ignore the non-bc file contents.
   // The magic number is 0x0B17C0DE stored in little endian.
-  if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 && 
-      BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
-    if (SkipWrapperHeader(BufPtr, BufEnd))
+  if (isBitcodeWrapper(BufPtr, BufEnd))
+    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
       return Error("Invalid bitcode wrapper header");
   
-  Stream.init(BufPtr, BufEnd);
+  StreamFile.init(BufPtr, BufEnd);
+  Stream.init(StreamFile);
   
   // Sniff for the signature.
   if (Stream.Read(8) != 'B' ||
@@ -1448,7 +1544,8 @@ bool BitcodeReader::ParseFunctionBody(Function *F) {
     // Read a record.
     Record.clear();
     Instruction *I = 0;
-    switch (Stream.ReadRecord(Code, Record)) {
+    unsigned BitCode = Stream.ReadRecord(Code, Record);
+    switch (BitCode) {
     default: // Default behavior: reject
       return Error("Unknown instruction");
     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
@@ -1466,12 +1563,14 @@ bool BitcodeReader::ParseFunctionBody(Function *F) {
       Value *LHS, *RHS;
       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
           getValue(Record, OpNum, LHS->getType(), RHS) ||
-          OpNum+1 != Record.size())
+          OpNum+1 > Record.size())
         return Error("Invalid BINOP record");
       
-      int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
+      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
       if (Opc == -1) return Error("Invalid BINOP record");
       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
+      if (OpNum < Record.size())
+        SetOptimizationFlags(I, Record[3]);
       break;
     }
     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
@@ -1488,6 +1587,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) {
       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
       break;
     }
+    case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
       unsigned OpNum = 0;
       Value *BasePtr;
@@ -1503,6 +1603,8 @@ bool BitcodeReader::ParseFunctionBody(Function *F) {
       }
 
       I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
+      if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
+        cast<GEPOperator>(I)->setIsInBounds(true);
       break;
     }
       
@@ -1597,7 +1699,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) {
       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
           getValue(Record, OpNum, Type::Int32Ty, Idx))
         return Error("Invalid EXTRACTELT record");
-      I = new ExtractElementInst(Vec, Idx);
+      I = ExtractElementInst::Create(Vec, Idx);
       break;
     }
       
@@ -1626,41 +1728,27 @@ bool BitcodeReader::ParseFunctionBody(Function *F) {
       break;
     }
 
-    case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
-      // VFCmp/VICmp
-      // or old form of ICmp/FCmp returning bool
-      unsigned OpNum = 0;
-      Value *LHS, *RHS;
-      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
-          getValue(Record, OpNum, LHS->getType(), RHS) ||
-          OpNum+1 != Record.size())
-        return Error("Invalid CMP record");
-      
-      if (LHS->getType()->isFloatingPoint())
-        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
-      else if (!isa<VectorType>(LHS->getType()))
-        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
-      else if (LHS->getType()->isFPOrFPVector())
-        I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
-      else
-        I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
-      break;
-    }
+    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
+      // Old form of ICmp/FCmp returning bool
+      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
+      // both legal on vectors but had different behaviour.
     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
-      // Fcmp/ICmp returning bool or vector of bool
+      // FCmp/ICmp returning bool or vector of bool
+
       unsigned OpNum = 0;
       Value *LHS, *RHS;
       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
           getValue(Record, OpNum, LHS->getType(), RHS) ||
           OpNum+1 != Record.size())
-        return Error("Invalid CMP2 record");
+        return Error("Invalid CMP record");
       
       if (LHS->getType()->isFPOrFPVector())
-        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
-      else 
-        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
+        I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
+      else
+        I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
       break;
     }
+
     case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
       if (Record.size() != 2)
         return Error("Invalid GETRESULT record");
@@ -1879,7 +1967,8 @@ bool BitcodeReader::ParseFunctionBody(Function *F) {
       unsigned OpNum = 0;
       Value *Val, *Ptr;
       if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
-          getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
+          getValue(Record, OpNum, 
+                   PointerType::getUnqual(Val->getType()), Ptr)||
           OpNum+2 != Record.size())
         return Error("Invalid STORE record");
       
@@ -2039,14 +2128,13 @@ void BitcodeReader::dematerializeFunction(Function *F) {
 
 
 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
-  for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I = 
-       DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
-       ++I) {
-    Function *F = I->first;
+  // Iterate over the module, deserializing any functions that are still on
+  // disk.
+  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
+       F != E; ++F)
     if (F->hasNotBeenReadFromBitcode() &&
         materializeFunction(F, ErrInfo))
       return 0;
-  }
 
   // Upgrade any intrinsic calls that slipped through (should not happen!) and 
   // delete the old functions to clean up. We can't do this unless the entire 
@@ -2060,7 +2148,8 @@ Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
           UpgradeIntrinsicCall(CI, I->second);
       }
-      ValueList.replaceUsesOfWith(I->first, I->second);
+      if (!I->first->use_empty())
+        I->first->replaceAllUsesWith(I->second);
       I->first->eraseFromParent();
     }
   }
@@ -2089,8 +2178,9 @@ Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
 ///
 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
+                                               LLVMContext& Context,
                                                std::string *ErrMsg) {
-  BitcodeReader *R = new BitcodeReader(Buffer);
+  BitcodeReader *R = new BitcodeReader(Buffer, Context);
   if (R->ParseBitcode()) {
     if (ErrMsg)
       *ErrMsg = R->getErrorString();
@@ -2105,9 +2195,11 @@ ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
 
 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
 /// If an error occurs, return null and fill in *ErrMsg if non-null.
-Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
+Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 
+                               std::string *ErrMsg){
   BitcodeReader *R;
-  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
+  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context, 
+                                                           ErrMsg));
   if (!R) return 0;
   
   // Read in the entire module.
@@ -2121,7 +2213,7 @@ Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
   // is run.
   if (M)
     M = R->releaseModule(ErrMsg);
-  
+   
   delete R;
   return M;
 }